babylon.max.js 3.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647
  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 (renderWidthOrEngine, renderHeight) {
  4010. if (renderWidthOrEngine._gl) {
  4011. var engine = renderWidthOrEngine;
  4012. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4013. }
  4014. var renderWidth = renderWidthOrEngine;
  4015. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4016. };
  4017. /**
  4018. * Returns a new Viewport copied from the current one.
  4019. */
  4020. Viewport.prototype.clone = function () {
  4021. return new Viewport(this.x, this.y, this.width, this.height);
  4022. };
  4023. return Viewport;
  4024. }());
  4025. BABYLON.Viewport = Viewport;
  4026. var Frustum = (function () {
  4027. function Frustum() {
  4028. }
  4029. /**
  4030. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4031. */
  4032. Frustum.GetPlanes = function (transform) {
  4033. var frustumPlanes = [];
  4034. for (var index = 0; index < 6; index++) {
  4035. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4036. }
  4037. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4038. return frustumPlanes;
  4039. };
  4040. /**
  4041. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4042. */
  4043. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4044. // Near
  4045. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4046. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4047. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4048. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4049. frustumPlanes[0].normalize();
  4050. // Far
  4051. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4052. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4053. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4054. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4055. frustumPlanes[1].normalize();
  4056. // Left
  4057. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4058. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4059. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4060. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4061. frustumPlanes[2].normalize();
  4062. // Right
  4063. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4064. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4065. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4066. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4067. frustumPlanes[3].normalize();
  4068. // Top
  4069. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4070. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4071. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4072. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4073. frustumPlanes[4].normalize();
  4074. // Bottom
  4075. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4076. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4077. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4078. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4079. frustumPlanes[5].normalize();
  4080. };
  4081. return Frustum;
  4082. }());
  4083. BABYLON.Frustum = Frustum;
  4084. var Space;
  4085. (function (Space) {
  4086. Space[Space["LOCAL"] = 0] = "LOCAL";
  4087. Space[Space["WORLD"] = 1] = "WORLD";
  4088. Space[Space["BONE"] = 2] = "BONE";
  4089. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4090. var Axis = (function () {
  4091. function Axis() {
  4092. }
  4093. return Axis;
  4094. }());
  4095. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4096. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4097. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4098. BABYLON.Axis = Axis;
  4099. ;
  4100. var BezierCurve = (function () {
  4101. function BezierCurve() {
  4102. }
  4103. /**
  4104. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4105. */
  4106. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4107. // Extract X (which is equal to time here)
  4108. var f0 = 1 - 3 * x2 + 3 * x1;
  4109. var f1 = 3 * x2 - 6 * x1;
  4110. var f2 = 3 * x1;
  4111. var refinedT = t;
  4112. for (var i = 0; i < 5; i++) {
  4113. var refinedT2 = refinedT * refinedT;
  4114. var refinedT3 = refinedT2 * refinedT;
  4115. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4116. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4117. refinedT -= (x - t) * slope;
  4118. refinedT = Math.min(1, Math.max(0, refinedT));
  4119. }
  4120. // Resolve cubic bezier for the given x
  4121. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4122. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4123. Math.pow(refinedT, 3);
  4124. };
  4125. return BezierCurve;
  4126. }());
  4127. BABYLON.BezierCurve = BezierCurve;
  4128. var Orientation;
  4129. (function (Orientation) {
  4130. Orientation[Orientation["CW"] = 0] = "CW";
  4131. Orientation[Orientation["CCW"] = 1] = "CCW";
  4132. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4133. var Angle = (function () {
  4134. /**
  4135. * Creates an Angle object of "radians" radians (float).
  4136. */
  4137. function Angle(radians) {
  4138. var _this = this;
  4139. /**
  4140. * Returns the Angle value in degrees (float).
  4141. */
  4142. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4143. /**
  4144. * Returns the Angle value in radians (float).
  4145. */
  4146. this.radians = function () { return _this._radians; };
  4147. this._radians = radians;
  4148. if (this._radians < 0.0)
  4149. this._radians += (2.0 * Math.PI);
  4150. }
  4151. /**
  4152. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4153. */
  4154. Angle.BetweenTwoPoints = function (a, b) {
  4155. var delta = b.subtract(a);
  4156. var theta = Math.atan2(delta.y, delta.x);
  4157. return new Angle(theta);
  4158. };
  4159. /**
  4160. * Returns a new Angle object from the passed float in radians.
  4161. */
  4162. Angle.FromRadians = function (radians) {
  4163. return new Angle(radians);
  4164. };
  4165. /**
  4166. * Returns a new Angle object from the passed float in degrees.
  4167. */
  4168. Angle.FromDegrees = function (degrees) {
  4169. return new Angle(degrees * Math.PI / 180.0);
  4170. };
  4171. return Angle;
  4172. }());
  4173. BABYLON.Angle = Angle;
  4174. var Arc2 = (function () {
  4175. /**
  4176. * Creates an Arc object from the three passed points : start, middle and end.
  4177. */
  4178. function Arc2(startPoint, midPoint, endPoint) {
  4179. this.startPoint = startPoint;
  4180. this.midPoint = midPoint;
  4181. this.endPoint = endPoint;
  4182. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4183. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4184. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4185. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4186. 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);
  4187. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4188. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4189. var a1 = this.startAngle.degrees();
  4190. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4191. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4192. // angles correction
  4193. if (a2 - a1 > +180.0)
  4194. a2 -= 360.0;
  4195. if (a2 - a1 < -180.0)
  4196. a2 += 360.0;
  4197. if (a3 - a2 > +180.0)
  4198. a3 -= 360.0;
  4199. if (a3 - a2 < -180.0)
  4200. a3 += 360.0;
  4201. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4202. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4203. }
  4204. return Arc2;
  4205. }());
  4206. BABYLON.Arc2 = Arc2;
  4207. var Path2 = (function () {
  4208. /**
  4209. * Creates a Path2 object from the starting 2D coordinates x and y.
  4210. */
  4211. function Path2(x, y) {
  4212. this._points = new Array();
  4213. this._length = 0.0;
  4214. this.closed = false;
  4215. this._points.push(new Vector2(x, y));
  4216. }
  4217. /**
  4218. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4219. * Returns the updated Path2.
  4220. */
  4221. Path2.prototype.addLineTo = function (x, y) {
  4222. if (closed) {
  4223. //Tools.Error("cannot add lines to closed paths");
  4224. return this;
  4225. }
  4226. var newPoint = new Vector2(x, y);
  4227. var previousPoint = this._points[this._points.length - 1];
  4228. this._points.push(newPoint);
  4229. this._length += newPoint.subtract(previousPoint).length();
  4230. return this;
  4231. };
  4232. /**
  4233. * 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.
  4234. * Returns the updated Path2.
  4235. */
  4236. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4237. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4238. if (closed) {
  4239. //Tools.Error("cannot add arcs to closed paths");
  4240. return this;
  4241. }
  4242. var startPoint = this._points[this._points.length - 1];
  4243. var midPoint = new Vector2(midX, midY);
  4244. var endPoint = new Vector2(endX, endY);
  4245. var arc = new Arc2(startPoint, midPoint, endPoint);
  4246. var increment = arc.angle.radians() / numberOfSegments;
  4247. if (arc.orientation === Orientation.CW)
  4248. increment *= -1;
  4249. var currentAngle = arc.startAngle.radians() + increment;
  4250. for (var i = 0; i < numberOfSegments; i++) {
  4251. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4252. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4253. this.addLineTo(x, y);
  4254. currentAngle += increment;
  4255. }
  4256. return this;
  4257. };
  4258. /**
  4259. * Closes the Path2.
  4260. * Returns the Path2.
  4261. */
  4262. Path2.prototype.close = function () {
  4263. this.closed = true;
  4264. return this;
  4265. };
  4266. /**
  4267. * Returns the Path2 total length (float).
  4268. */
  4269. Path2.prototype.length = function () {
  4270. var result = this._length;
  4271. if (!this.closed) {
  4272. var lastPoint = this._points[this._points.length - 1];
  4273. var firstPoint = this._points[0];
  4274. result += (firstPoint.subtract(lastPoint).length());
  4275. }
  4276. return result;
  4277. };
  4278. /**
  4279. * Returns the Path2 internal array of points.
  4280. */
  4281. Path2.prototype.getPoints = function () {
  4282. return this._points;
  4283. };
  4284. /**
  4285. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4286. */
  4287. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4288. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4289. //Tools.Error("normalized length position should be between 0 and 1.");
  4290. return Vector2.Zero();
  4291. }
  4292. var lengthPosition = normalizedLengthPosition * this.length();
  4293. var previousOffset = 0;
  4294. for (var i = 0; i < this._points.length; i++) {
  4295. var j = (i + 1) % this._points.length;
  4296. var a = this._points[i];
  4297. var b = this._points[j];
  4298. var bToA = b.subtract(a);
  4299. var nextOffset = (bToA.length() + previousOffset);
  4300. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4301. var dir = bToA.normalize();
  4302. var localOffset = lengthPosition - previousOffset;
  4303. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4304. }
  4305. previousOffset = nextOffset;
  4306. }
  4307. //Tools.Error("internal error");
  4308. return Vector2.Zero();
  4309. };
  4310. /**
  4311. * Returns a new Path2 starting at the coordinates (x, y).
  4312. */
  4313. Path2.StartingAt = function (x, y) {
  4314. return new Path2(x, y);
  4315. };
  4316. return Path2;
  4317. }());
  4318. BABYLON.Path2 = Path2;
  4319. var Path3D = (function () {
  4320. /**
  4321. * new Path3D(path, normal, raw)
  4322. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4323. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4324. * path : an array of Vector3, the curve axis of the Path3D
  4325. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4326. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4327. */
  4328. function Path3D(path, firstNormal, raw) {
  4329. this.path = path;
  4330. this._curve = new Array();
  4331. this._distances = new Array();
  4332. this._tangents = new Array();
  4333. this._normals = new Array();
  4334. this._binormals = new Array();
  4335. for (var p = 0; p < path.length; p++) {
  4336. this._curve[p] = path[p].clone(); // hard copy
  4337. }
  4338. this._raw = raw || false;
  4339. this._compute(firstNormal);
  4340. }
  4341. /**
  4342. * Returns the Path3D array of successive Vector3 designing its curve.
  4343. */
  4344. Path3D.prototype.getCurve = function () {
  4345. return this._curve;
  4346. };
  4347. /**
  4348. * Returns an array populated with tangent vectors on each Path3D curve point.
  4349. */
  4350. Path3D.prototype.getTangents = function () {
  4351. return this._tangents;
  4352. };
  4353. /**
  4354. * Returns an array populated with normal vectors on each Path3D curve point.
  4355. */
  4356. Path3D.prototype.getNormals = function () {
  4357. return this._normals;
  4358. };
  4359. /**
  4360. * Returns an array populated with binormal vectors on each Path3D curve point.
  4361. */
  4362. Path3D.prototype.getBinormals = function () {
  4363. return this._binormals;
  4364. };
  4365. /**
  4366. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4367. */
  4368. Path3D.prototype.getDistances = function () {
  4369. return this._distances;
  4370. };
  4371. /**
  4372. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4373. * Returns the same object updated.
  4374. */
  4375. Path3D.prototype.update = function (path, firstNormal) {
  4376. for (var p = 0; p < path.length; p++) {
  4377. this._curve[p].x = path[p].x;
  4378. this._curve[p].y = path[p].y;
  4379. this._curve[p].z = path[p].z;
  4380. }
  4381. this._compute(firstNormal);
  4382. return this;
  4383. };
  4384. // private function compute() : computes tangents, normals and binormals
  4385. Path3D.prototype._compute = function (firstNormal) {
  4386. var l = this._curve.length;
  4387. // first and last tangents
  4388. this._tangents[0] = this._getFirstNonNullVector(0);
  4389. if (!this._raw) {
  4390. this._tangents[0].normalize();
  4391. }
  4392. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4393. if (!this._raw) {
  4394. this._tangents[l - 1].normalize();
  4395. }
  4396. // normals and binormals at first point : arbitrary vector with _normalVector()
  4397. var tg0 = this._tangents[0];
  4398. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4399. this._normals[0] = pp0;
  4400. if (!this._raw) {
  4401. this._normals[0].normalize();
  4402. }
  4403. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4404. if (!this._raw) {
  4405. this._binormals[0].normalize();
  4406. }
  4407. this._distances[0] = 0.0;
  4408. // normals and binormals : next points
  4409. var prev; // previous vector (segment)
  4410. var cur; // current vector (segment)
  4411. var curTang; // current tangent
  4412. // previous normal
  4413. var prevBinor; // previous binormal
  4414. for (var i = 1; i < l; i++) {
  4415. // tangents
  4416. prev = this._getLastNonNullVector(i);
  4417. if (i < l - 1) {
  4418. cur = this._getFirstNonNullVector(i);
  4419. this._tangents[i] = prev.add(cur);
  4420. this._tangents[i].normalize();
  4421. }
  4422. this._distances[i] = this._distances[i - 1] + prev.length();
  4423. // normals and binormals
  4424. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4425. curTang = this._tangents[i];
  4426. prevBinor = this._binormals[i - 1];
  4427. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4428. if (!this._raw) {
  4429. this._normals[i].normalize();
  4430. }
  4431. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4432. if (!this._raw) {
  4433. this._binormals[i].normalize();
  4434. }
  4435. }
  4436. };
  4437. // private function getFirstNonNullVector(index)
  4438. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4439. Path3D.prototype._getFirstNonNullVector = function (index) {
  4440. var i = 1;
  4441. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4442. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4443. i++;
  4444. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4445. }
  4446. return nNVector;
  4447. };
  4448. // private function getLastNonNullVector(index)
  4449. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4450. Path3D.prototype._getLastNonNullVector = function (index) {
  4451. var i = 1;
  4452. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4453. while (nLVector.length() === 0 && index > i + 1) {
  4454. i++;
  4455. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4456. }
  4457. return nLVector;
  4458. };
  4459. // private function normalVector(v0, vt, va) :
  4460. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4461. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4462. Path3D.prototype._normalVector = function (v0, vt, va) {
  4463. var normal0;
  4464. var tgl = vt.length();
  4465. if (tgl === 0.0) {
  4466. tgl = 1.0;
  4467. }
  4468. if (va === undefined || va === null) {
  4469. var point;
  4470. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4471. point = new Vector3(0.0, -1.0, 0.0);
  4472. }
  4473. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4474. point = new Vector3(1.0, 0.0, 0.0);
  4475. }
  4476. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4477. point = new Vector3(0.0, 0.0, 1.0);
  4478. }
  4479. normal0 = Vector3.Cross(vt, point);
  4480. }
  4481. else {
  4482. normal0 = Vector3.Cross(vt, va);
  4483. Vector3.CrossToRef(normal0, vt, normal0);
  4484. }
  4485. normal0.normalize();
  4486. return normal0;
  4487. };
  4488. return Path3D;
  4489. }());
  4490. BABYLON.Path3D = Path3D;
  4491. var Curve3 = (function () {
  4492. /**
  4493. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4494. * A Curve3 is designed from a series of successive Vector3.
  4495. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4496. */
  4497. function Curve3(points) {
  4498. this._length = 0.0;
  4499. this._points = points;
  4500. this._length = this._computeLength(points);
  4501. }
  4502. /**
  4503. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4504. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4505. * @param v1 (Vector3) the control point
  4506. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4507. * @param nbPoints (integer) the wanted number of points in the curve
  4508. */
  4509. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4510. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4511. var bez = new Array();
  4512. var equation = function (t, val0, val1, val2) {
  4513. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4514. return res;
  4515. };
  4516. for (var i = 0; i <= nbPoints; i++) {
  4517. 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)));
  4518. }
  4519. return new Curve3(bez);
  4520. };
  4521. /**
  4522. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4523. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4524. * @param v1 (Vector3) the first control point
  4525. * @param v2 (Vector3) the second control point
  4526. * @param v3 (Vector3) the end point of the Cubic Bezier
  4527. * @param nbPoints (integer) the wanted number of points in the curve
  4528. */
  4529. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4530. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4531. var bez = new Array();
  4532. var equation = function (t, val0, val1, val2, val3) {
  4533. 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;
  4534. return res;
  4535. };
  4536. for (var i = 0; i <= nbPoints; i++) {
  4537. 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)));
  4538. }
  4539. return new Curve3(bez);
  4540. };
  4541. /**
  4542. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4543. * @param p1 (Vector3) the origin point of the Hermite Spline
  4544. * @param t1 (Vector3) the tangent vector at the origin point
  4545. * @param p2 (Vector3) the end point of the Hermite Spline
  4546. * @param t2 (Vector3) the tangent vector at the end point
  4547. * @param nbPoints (integer) the wanted number of points in the curve
  4548. */
  4549. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4550. var hermite = new Array();
  4551. var step = 1.0 / nbPoints;
  4552. for (var i = 0; i <= nbPoints; i++) {
  4553. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4554. }
  4555. return new Curve3(hermite);
  4556. };
  4557. /**
  4558. * Returns a Curve3 object along a CatmullRom Spline curve :
  4559. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4560. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4561. */
  4562. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4563. var totalPoints = new Array();
  4564. totalPoints.push(points[0].clone());
  4565. Array.prototype.push.apply(totalPoints, points);
  4566. totalPoints.push(points[points.length - 1].clone());
  4567. var catmullRom = new Array();
  4568. var step = 1.0 / nbPoints;
  4569. for (var i = 0; i < totalPoints.length - 3; i++) {
  4570. var amount = 0.0;
  4571. for (var c = 0; c < nbPoints; c++) {
  4572. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4573. amount += step;
  4574. }
  4575. }
  4576. i--;
  4577. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4578. return new Curve3(catmullRom);
  4579. };
  4580. /**
  4581. * Returns the Curve3 stored array of successive Vector3
  4582. */
  4583. Curve3.prototype.getPoints = function () {
  4584. return this._points;
  4585. };
  4586. /**
  4587. * Returns the computed length (float) of the curve.
  4588. */
  4589. Curve3.prototype.length = function () {
  4590. return this._length;
  4591. };
  4592. /**
  4593. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4594. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4595. * curveA and curveB keep unchanged.
  4596. */
  4597. Curve3.prototype.continue = function (curve) {
  4598. var lastPoint = this._points[this._points.length - 1];
  4599. var continuedPoints = this._points.slice();
  4600. var curvePoints = curve.getPoints();
  4601. for (var i = 1; i < curvePoints.length; i++) {
  4602. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4603. }
  4604. var continuedCurve = new Curve3(continuedPoints);
  4605. return continuedCurve;
  4606. };
  4607. Curve3.prototype._computeLength = function (path) {
  4608. var l = 0;
  4609. for (var i = 1; i < path.length; i++) {
  4610. l += (path[i].subtract(path[i - 1])).length();
  4611. }
  4612. return l;
  4613. };
  4614. return Curve3;
  4615. }());
  4616. BABYLON.Curve3 = Curve3;
  4617. // SphericalHarmonics
  4618. var SphericalHarmonics = (function () {
  4619. function SphericalHarmonics() {
  4620. this.L00 = Vector3.Zero();
  4621. this.L1_1 = Vector3.Zero();
  4622. this.L10 = Vector3.Zero();
  4623. this.L11 = Vector3.Zero();
  4624. this.L2_2 = Vector3.Zero();
  4625. this.L2_1 = Vector3.Zero();
  4626. this.L20 = Vector3.Zero();
  4627. this.L21 = Vector3.Zero();
  4628. this.L22 = Vector3.Zero();
  4629. }
  4630. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4631. var colorVector = new Vector3(color.r, color.g, color.b);
  4632. var c = colorVector.scale(deltaSolidAngle);
  4633. this.L00 = this.L00.add(c.scale(0.282095));
  4634. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4635. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4636. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4637. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4638. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4639. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4640. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4641. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4642. };
  4643. SphericalHarmonics.prototype.scale = function (scale) {
  4644. this.L00 = this.L00.scale(scale);
  4645. this.L1_1 = this.L1_1.scale(scale);
  4646. this.L10 = this.L10.scale(scale);
  4647. this.L11 = this.L11.scale(scale);
  4648. this.L2_2 = this.L2_2.scale(scale);
  4649. this.L2_1 = this.L2_1.scale(scale);
  4650. this.L20 = this.L20.scale(scale);
  4651. this.L21 = this.L21.scale(scale);
  4652. this.L22 = this.L22.scale(scale);
  4653. };
  4654. return SphericalHarmonics;
  4655. }());
  4656. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4657. // SphericalPolynomial
  4658. var SphericalPolynomial = (function () {
  4659. function SphericalPolynomial() {
  4660. this.x = Vector3.Zero();
  4661. this.y = Vector3.Zero();
  4662. this.z = Vector3.Zero();
  4663. this.xx = Vector3.Zero();
  4664. this.yy = Vector3.Zero();
  4665. this.zz = Vector3.Zero();
  4666. this.xy = Vector3.Zero();
  4667. this.yz = Vector3.Zero();
  4668. this.zx = Vector3.Zero();
  4669. }
  4670. SphericalPolynomial.prototype.addAmbient = function (color) {
  4671. var colorVector = new Vector3(color.r, color.g, color.b);
  4672. this.xx = this.xx.add(colorVector);
  4673. this.yy = this.yy.add(colorVector);
  4674. this.zz = this.zz.add(colorVector);
  4675. };
  4676. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4677. var result = new SphericalPolynomial();
  4678. result.x = harmonics.L11.scale(1.02333);
  4679. result.y = harmonics.L1_1.scale(1.02333);
  4680. result.z = harmonics.L10.scale(1.02333);
  4681. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4682. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4683. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4684. result.yz = harmonics.L2_1.scale(0.858086);
  4685. result.zx = harmonics.L21.scale(0.858086);
  4686. result.xy = harmonics.L2_2.scale(0.858086);
  4687. return result;
  4688. };
  4689. return SphericalPolynomial;
  4690. }());
  4691. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4692. // Vertex formats
  4693. var PositionNormalVertex = (function () {
  4694. function PositionNormalVertex(position, normal) {
  4695. if (position === void 0) { position = Vector3.Zero(); }
  4696. if (normal === void 0) { normal = Vector3.Up(); }
  4697. this.position = position;
  4698. this.normal = normal;
  4699. }
  4700. PositionNormalVertex.prototype.clone = function () {
  4701. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4702. };
  4703. return PositionNormalVertex;
  4704. }());
  4705. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4706. var PositionNormalTextureVertex = (function () {
  4707. function PositionNormalTextureVertex(position, normal, uv) {
  4708. if (position === void 0) { position = Vector3.Zero(); }
  4709. if (normal === void 0) { normal = Vector3.Up(); }
  4710. if (uv === void 0) { uv = Vector2.Zero(); }
  4711. this.position = position;
  4712. this.normal = normal;
  4713. this.uv = uv;
  4714. }
  4715. PositionNormalTextureVertex.prototype.clone = function () {
  4716. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4717. };
  4718. return PositionNormalTextureVertex;
  4719. }());
  4720. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4721. // Temporary pre-allocated objects for engine internal use
  4722. // usage in any internal function :
  4723. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4724. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4725. var Tmp = (function () {
  4726. function Tmp() {
  4727. }
  4728. return Tmp;
  4729. }());
  4730. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4731. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4732. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4733. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4734. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4735. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4736. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4737. Matrix.Zero(), Matrix.Zero(),
  4738. Matrix.Zero(), Matrix.Zero(),
  4739. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4740. BABYLON.Tmp = Tmp;
  4741. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4742. var MathTmp = (function () {
  4743. function MathTmp() {
  4744. }
  4745. return MathTmp;
  4746. }());
  4747. MathTmp.Vector3 = [Vector3.Zero()];
  4748. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4749. MathTmp.Quaternion = [Quaternion.Zero()];
  4750. })(BABYLON || (BABYLON = {}));
  4751. //# sourceMappingURL=babylon.math.js.map
  4752. //# sourceMappingURL=babylon.mixins.js.map
  4753. var BABYLON;
  4754. (function (BABYLON) {
  4755. function generateSerializableMember(type, sourceName) {
  4756. return function (target, propertyKey) {
  4757. if (!target.__serializableMembers) {
  4758. target.__serializableMembers = {};
  4759. }
  4760. if (!target.__serializableMembers[propertyKey]) {
  4761. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4762. }
  4763. };
  4764. }
  4765. function generateExpandMember(setCallback, targetKey) {
  4766. return function (target, propertyKey) {
  4767. var key = targetKey || ("_" + propertyKey);
  4768. Object.defineProperty(target, propertyKey, {
  4769. get: function () {
  4770. return this[key];
  4771. },
  4772. set: function (value) {
  4773. if (this[key] === value) {
  4774. return;
  4775. }
  4776. this[key] = value;
  4777. target[setCallback].apply(this);
  4778. },
  4779. enumerable: true,
  4780. configurable: true
  4781. });
  4782. };
  4783. }
  4784. function expandToProperty(callback, targetKey) {
  4785. return generateExpandMember(callback, targetKey);
  4786. }
  4787. BABYLON.expandToProperty = expandToProperty;
  4788. function serialize(sourceName) {
  4789. return generateSerializableMember(0, sourceName); // value member
  4790. }
  4791. BABYLON.serialize = serialize;
  4792. function serializeAsTexture(sourceName) {
  4793. return generateSerializableMember(1, sourceName); // texture member
  4794. }
  4795. BABYLON.serializeAsTexture = serializeAsTexture;
  4796. function serializeAsColor3(sourceName) {
  4797. return generateSerializableMember(2, sourceName); // color3 member
  4798. }
  4799. BABYLON.serializeAsColor3 = serializeAsColor3;
  4800. function serializeAsFresnelParameters(sourceName) {
  4801. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4802. }
  4803. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4804. function serializeAsVector2(sourceName) {
  4805. return generateSerializableMember(4, sourceName); // vector2 member
  4806. }
  4807. BABYLON.serializeAsVector2 = serializeAsVector2;
  4808. function serializeAsVector3(sourceName) {
  4809. return generateSerializableMember(5, sourceName); // vector3 member
  4810. }
  4811. BABYLON.serializeAsVector3 = serializeAsVector3;
  4812. function serializeAsMeshReference(sourceName) {
  4813. return generateSerializableMember(6, sourceName); // mesh reference member
  4814. }
  4815. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4816. function serializeAsColorCurves(sourceName) {
  4817. return generateSerializableMember(7, sourceName); // color curves
  4818. }
  4819. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4820. function serializeAsColor4(sourceName) {
  4821. return generateSerializableMember(8, sourceName); // color 4
  4822. }
  4823. BABYLON.serializeAsColor4 = serializeAsColor4;
  4824. function serializeAsImageProcessingConfiguration(sourceName) {
  4825. return generateSerializableMember(9, sourceName); // image processing
  4826. }
  4827. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  4828. var SerializationHelper = (function () {
  4829. function SerializationHelper() {
  4830. }
  4831. SerializationHelper.Serialize = function (entity, serializationObject) {
  4832. if (!serializationObject) {
  4833. serializationObject = {};
  4834. }
  4835. // Tags
  4836. if (BABYLON.Tags) {
  4837. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4838. }
  4839. // Properties
  4840. for (var property in entity.__serializableMembers) {
  4841. var propertyDescriptor = entity.__serializableMembers[property];
  4842. var targetPropertyName = propertyDescriptor.sourceName || property;
  4843. var propertyType = propertyDescriptor.type;
  4844. var sourceProperty = entity[property];
  4845. if (sourceProperty !== undefined && sourceProperty !== null) {
  4846. switch (propertyType) {
  4847. case 0:
  4848. serializationObject[targetPropertyName] = sourceProperty;
  4849. break;
  4850. case 1:
  4851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4852. break;
  4853. case 2:
  4854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4855. break;
  4856. case 3:
  4857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4858. break;
  4859. case 4:
  4860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4861. break;
  4862. case 5:
  4863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4864. break;
  4865. case 6:
  4866. serializationObject[targetPropertyName] = sourceProperty.id;
  4867. break;
  4868. case 7:
  4869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4870. break;
  4871. case 8:
  4872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4873. break;
  4874. case 9:
  4875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4876. break;
  4877. }
  4878. }
  4879. }
  4880. return serializationObject;
  4881. };
  4882. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4883. var destination = creationFunction();
  4884. // Tags
  4885. if (BABYLON.Tags) {
  4886. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4887. }
  4888. // Properties
  4889. for (var property in destination.__serializableMembers) {
  4890. var propertyDescriptor = destination.__serializableMembers[property];
  4891. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4892. var propertyType = propertyDescriptor.type;
  4893. if (sourceProperty !== undefined && sourceProperty !== null) {
  4894. switch (propertyType) {
  4895. case 0:
  4896. destination[property] = sourceProperty;
  4897. break;
  4898. case 1:
  4899. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4900. break;
  4901. case 2:
  4902. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4903. break;
  4904. case 3:
  4905. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4906. break;
  4907. case 4:
  4908. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4909. break;
  4910. case 5:
  4911. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4912. break;
  4913. case 6:
  4914. destination[property] = scene.getLastMeshByID(sourceProperty);
  4915. break;
  4916. case 7:
  4917. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4918. break;
  4919. case 8:
  4920. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  4921. break;
  4922. case 9:
  4923. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  4924. break;
  4925. }
  4926. }
  4927. }
  4928. return destination;
  4929. };
  4930. SerializationHelper.Clone = function (creationFunction, source) {
  4931. var destination = creationFunction();
  4932. // Tags
  4933. if (BABYLON.Tags) {
  4934. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4935. }
  4936. // Properties
  4937. for (var property in destination.__serializableMembers) {
  4938. var propertyDescriptor = destination.__serializableMembers[property];
  4939. var sourceProperty = source[property];
  4940. var propertyType = propertyDescriptor.type;
  4941. if (sourceProperty !== undefined && sourceProperty !== null) {
  4942. switch (propertyType) {
  4943. case 0: // Value
  4944. case 6:
  4945. destination[property] = sourceProperty;
  4946. break;
  4947. case 1: // Texture
  4948. case 2: // Color3
  4949. case 3: // FresnelParameters
  4950. case 4: // Vector2
  4951. case 5: // Vector3
  4952. case 7:
  4953. destination[property] = sourceProperty.clone();
  4954. break;
  4955. }
  4956. }
  4957. }
  4958. return destination;
  4959. };
  4960. return SerializationHelper;
  4961. }());
  4962. BABYLON.SerializationHelper = SerializationHelper;
  4963. })(BABYLON || (BABYLON = {}));
  4964. //# sourceMappingURL=babylon.decorators.js.map
  4965. var BABYLON;
  4966. (function (BABYLON) {
  4967. /**
  4968. * A class serves as a medium between the observable and its observers
  4969. */
  4970. var EventState = (function () {
  4971. /**
  4972. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4973. */
  4974. function EventState(mask, skipNextObservers) {
  4975. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4976. this.initalize(mask, skipNextObservers);
  4977. }
  4978. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4979. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4980. this.mask = mask;
  4981. this.skipNextObservers = skipNextObservers;
  4982. return this;
  4983. };
  4984. return EventState;
  4985. }());
  4986. BABYLON.EventState = EventState;
  4987. /**
  4988. * Represent an Observer registered to a given Observable object.
  4989. */
  4990. var Observer = (function () {
  4991. function Observer(callback, mask) {
  4992. this.callback = callback;
  4993. this.mask = mask;
  4994. }
  4995. return Observer;
  4996. }());
  4997. BABYLON.Observer = Observer;
  4998. /**
  4999. * The Observable class is a simple implementation of the Observable pattern.
  5000. * 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.
  5001. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5002. * 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).
  5003. * 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.
  5004. */
  5005. var Observable = (function () {
  5006. function Observable() {
  5007. this._observers = new Array();
  5008. this._eventState = new EventState(0);
  5009. }
  5010. /**
  5011. * Create a new Observer with the specified callback
  5012. * @param callback the callback that will be executed for that Observer
  5013. * @param mask the mask used to filter observers
  5014. * @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.
  5015. */
  5016. Observable.prototype.add = function (callback, mask, insertFirst) {
  5017. if (mask === void 0) { mask = -1; }
  5018. if (insertFirst === void 0) { insertFirst = false; }
  5019. if (!callback) {
  5020. return null;
  5021. }
  5022. var observer = new Observer(callback, mask);
  5023. if (insertFirst) {
  5024. this._observers.unshift(observer);
  5025. }
  5026. else {
  5027. this._observers.push(observer);
  5028. }
  5029. return observer;
  5030. };
  5031. /**
  5032. * Remove an Observer from the Observable object
  5033. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5034. */
  5035. Observable.prototype.remove = function (observer) {
  5036. var index = this._observers.indexOf(observer);
  5037. if (index !== -1) {
  5038. this._observers.splice(index, 1);
  5039. return true;
  5040. }
  5041. return false;
  5042. };
  5043. /**
  5044. * Remove a callback from the Observable object
  5045. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5046. */
  5047. Observable.prototype.removeCallback = function (callback) {
  5048. for (var index = 0; index < this._observers.length; index++) {
  5049. if (this._observers[index].callback === callback) {
  5050. this._observers.splice(index, 1);
  5051. return true;
  5052. }
  5053. }
  5054. return false;
  5055. };
  5056. /**
  5057. * Notify all Observers by calling their respective callback with the given data
  5058. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5059. * @param eventData
  5060. * @param mask
  5061. */
  5062. Observable.prototype.notifyObservers = function (eventData, mask) {
  5063. if (mask === void 0) { mask = -1; }
  5064. var state = this._eventState;
  5065. state.mask = mask;
  5066. state.skipNextObservers = false;
  5067. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5068. var obs = _a[_i];
  5069. if (obs.mask & mask) {
  5070. obs.callback(eventData, state);
  5071. }
  5072. if (state.skipNextObservers) {
  5073. return false;
  5074. }
  5075. }
  5076. return true;
  5077. };
  5078. /**
  5079. * return true is the Observable has at least one Observer registered
  5080. */
  5081. Observable.prototype.hasObservers = function () {
  5082. return this._observers.length > 0;
  5083. };
  5084. /**
  5085. * Clear the list of observers
  5086. */
  5087. Observable.prototype.clear = function () {
  5088. this._observers = new Array();
  5089. };
  5090. /**
  5091. * Clone the current observable
  5092. */
  5093. Observable.prototype.clone = function () {
  5094. var result = new Observable();
  5095. result._observers = this._observers.slice(0);
  5096. return result;
  5097. };
  5098. /**
  5099. * Does this observable handles observer registered with a given mask
  5100. * @param {number} trigger - the mask to be tested
  5101. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5102. **/
  5103. Observable.prototype.hasSpecificMask = function (mask) {
  5104. if (mask === void 0) { mask = -1; }
  5105. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5106. var obs = _a[_i];
  5107. if (obs.mask & mask && obs.mask === mask) {
  5108. return true;
  5109. }
  5110. }
  5111. return false;
  5112. };
  5113. return Observable;
  5114. }());
  5115. BABYLON.Observable = Observable;
  5116. })(BABYLON || (BABYLON = {}));
  5117. //# sourceMappingURL=babylon.observable.js.map
  5118. var BABYLON;
  5119. (function (BABYLON) {
  5120. var SmartArray = (function () {
  5121. function SmartArray(capacity) {
  5122. this.length = 0;
  5123. this._duplicateId = 0;
  5124. this.data = new Array(capacity);
  5125. this._id = SmartArray._GlobalId++;
  5126. }
  5127. SmartArray.prototype.push = function (value) {
  5128. this.data[this.length++] = value;
  5129. if (this.length > this.data.length) {
  5130. this.data.length *= 2;
  5131. }
  5132. if (!value.__smartArrayFlags) {
  5133. value.__smartArrayFlags = {};
  5134. }
  5135. value.__smartArrayFlags[this._id] = this._duplicateId;
  5136. };
  5137. SmartArray.prototype.forEach = function (func) {
  5138. for (var index = 0; index < this.length; index++) {
  5139. func(this.data[index]);
  5140. }
  5141. };
  5142. SmartArray.prototype.pushNoDuplicate = function (value) {
  5143. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5144. return false;
  5145. }
  5146. this.push(value);
  5147. return true;
  5148. };
  5149. SmartArray.prototype.sort = function (compareFn) {
  5150. this.data.sort(compareFn);
  5151. };
  5152. SmartArray.prototype.reset = function () {
  5153. this.length = 0;
  5154. this._duplicateId++;
  5155. };
  5156. SmartArray.prototype.dispose = function () {
  5157. this.reset();
  5158. this.data.length = 0;
  5159. };
  5160. SmartArray.prototype.concat = function (array) {
  5161. if (array.length === 0) {
  5162. return;
  5163. }
  5164. if (this.length + array.length > this.data.length) {
  5165. this.data.length = (this.length + array.length) * 2;
  5166. }
  5167. for (var index = 0; index < array.length; index++) {
  5168. this.data[this.length++] = (array.data || array)[index];
  5169. }
  5170. };
  5171. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5172. if (array.length === 0) {
  5173. return;
  5174. }
  5175. if (this.length + array.length > this.data.length) {
  5176. this.data.length = (this.length + array.length) * 2;
  5177. }
  5178. for (var index = 0; index < array.length; index++) {
  5179. var item = (array.data || array)[index];
  5180. this.pushNoDuplicate(item);
  5181. }
  5182. };
  5183. SmartArray.prototype.indexOf = function (value) {
  5184. var position = this.data.indexOf(value);
  5185. if (position >= this.length) {
  5186. return -1;
  5187. }
  5188. return position;
  5189. };
  5190. SmartArray.prototype.contains = function (value) {
  5191. return this.data.indexOf(value) !== -1;
  5192. };
  5193. return SmartArray;
  5194. }());
  5195. // Statics
  5196. SmartArray._GlobalId = 0;
  5197. BABYLON.SmartArray = SmartArray;
  5198. })(BABYLON || (BABYLON = {}));
  5199. //# sourceMappingURL=babylon.smartArray.js.map
  5200. var BABYLON;
  5201. (function (BABYLON) {
  5202. // Screenshots
  5203. var screenshotCanvas;
  5204. var cloneValue = function (source, destinationObject) {
  5205. if (!source)
  5206. return null;
  5207. if (source instanceof BABYLON.Mesh) {
  5208. return null;
  5209. }
  5210. if (source instanceof BABYLON.SubMesh) {
  5211. return source.clone(destinationObject);
  5212. }
  5213. else if (source.clone) {
  5214. return source.clone();
  5215. }
  5216. return null;
  5217. };
  5218. var Tools = (function () {
  5219. function Tools() {
  5220. }
  5221. ;
  5222. /**
  5223. * Interpolates between a and b via alpha
  5224. * @param a The lower value (returned when alpha = 0)
  5225. * @param b The upper value (returned when alpha = 1)
  5226. * @param alpha The interpolation-factor
  5227. * @return The mixed value
  5228. */
  5229. Tools.Mix = function (a, b, alpha) {
  5230. return a * (1 - alpha) + b * alpha;
  5231. };
  5232. Tools.Instantiate = function (className) {
  5233. var arr = className.split(".");
  5234. var fn = (window || this);
  5235. for (var i = 0, len = arr.length; i < len; i++) {
  5236. fn = fn[arr[i]];
  5237. }
  5238. if (typeof fn !== "function") {
  5239. return null;
  5240. }
  5241. return fn;
  5242. };
  5243. Tools.SetImmediate = function (action) {
  5244. if (window.setImmediate) {
  5245. window.setImmediate(action);
  5246. }
  5247. else {
  5248. setTimeout(action, 1);
  5249. }
  5250. };
  5251. Tools.IsExponentOfTwo = function (value) {
  5252. var count = 1;
  5253. do {
  5254. count *= 2;
  5255. } while (count < value);
  5256. return count === value;
  5257. };
  5258. /**
  5259. * Find the next highest power of two.
  5260. * @param x Number to start search from.
  5261. * @return Next highest power of two.
  5262. */
  5263. Tools.CeilingPOT = function (x) {
  5264. x--;
  5265. x |= x >> 1;
  5266. x |= x >> 2;
  5267. x |= x >> 4;
  5268. x |= x >> 8;
  5269. x |= x >> 16;
  5270. x++;
  5271. return x;
  5272. };
  5273. /**
  5274. * Find the next lowest power of two.
  5275. * @param x Number to start search from.
  5276. * @return Next lowest power of two.
  5277. */
  5278. Tools.FloorPOT = function (x) {
  5279. x = x | (x >> 1);
  5280. x = x | (x >> 2);
  5281. x = x | (x >> 4);
  5282. x = x | (x >> 8);
  5283. x = x | (x >> 16);
  5284. return x - (x >> 1);
  5285. };
  5286. /**
  5287. * Find the nearest power of two.
  5288. * @param x Number to start search from.
  5289. * @return Next nearest power of two.
  5290. */
  5291. Tools.NearestPOT = function (x) {
  5292. var c = Tools.CeilingPOT(x);
  5293. var f = Tools.FloorPOT(x);
  5294. return (c - x) > (x - f) ? f : c;
  5295. };
  5296. Tools.GetExponentOfTwo = function (value, max, mode) {
  5297. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5298. var pot;
  5299. switch (mode) {
  5300. case BABYLON.Engine.SCALEMODE_FLOOR:
  5301. pot = Tools.FloorPOT(value);
  5302. break;
  5303. case BABYLON.Engine.SCALEMODE_NEAREST:
  5304. pot = Tools.NearestPOT(value);
  5305. break;
  5306. case BABYLON.Engine.SCALEMODE_CEILING:
  5307. pot = Tools.CeilingPOT(value);
  5308. break;
  5309. }
  5310. return Math.min(pot, max);
  5311. };
  5312. Tools.GetFilename = function (path) {
  5313. var index = path.lastIndexOf("/");
  5314. if (index < 0)
  5315. return path;
  5316. return path.substring(index + 1);
  5317. };
  5318. Tools.GetDOMTextContent = function (element) {
  5319. var result = "";
  5320. var child = element.firstChild;
  5321. while (child) {
  5322. if (child.nodeType === 3) {
  5323. result += child.textContent;
  5324. }
  5325. child = child.nextSibling;
  5326. }
  5327. return result;
  5328. };
  5329. Tools.ToDegrees = function (angle) {
  5330. return angle * 180 / Math.PI;
  5331. };
  5332. Tools.ToRadians = function (angle) {
  5333. return angle * Math.PI / 180;
  5334. };
  5335. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5336. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5337. var output = "";
  5338. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5339. var i = 0;
  5340. var bytes = new Uint8Array(buffer);
  5341. while (i < bytes.length) {
  5342. chr1 = bytes[i++];
  5343. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5344. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5345. enc1 = chr1 >> 2;
  5346. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5347. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5348. enc4 = chr3 & 63;
  5349. if (isNaN(chr2)) {
  5350. enc3 = enc4 = 64;
  5351. }
  5352. else if (isNaN(chr3)) {
  5353. enc4 = 64;
  5354. }
  5355. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5356. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5357. }
  5358. return "data:image/png;base64," + output;
  5359. };
  5360. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5361. if (bias === void 0) { bias = null; }
  5362. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5363. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5364. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5365. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5366. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5367. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5368. }
  5369. if (bias) {
  5370. minimum.x -= minimum.x * bias.x + bias.y;
  5371. minimum.y -= minimum.y * bias.x + bias.y;
  5372. minimum.z -= minimum.z * bias.x + bias.y;
  5373. maximum.x += maximum.x * bias.x + bias.y;
  5374. maximum.y += maximum.y * bias.x + bias.y;
  5375. maximum.z += maximum.z * bias.x + bias.y;
  5376. }
  5377. return {
  5378. minimum: minimum,
  5379. maximum: maximum
  5380. };
  5381. };
  5382. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5383. if (bias === void 0) { bias = null; }
  5384. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5385. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5386. if (!stride) {
  5387. stride = 3;
  5388. }
  5389. for (var index = start; index < start + count; index++) {
  5390. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5391. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5392. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5393. }
  5394. if (bias) {
  5395. minimum.x -= minimum.x * bias.x + bias.y;
  5396. minimum.y -= minimum.y * bias.x + bias.y;
  5397. minimum.z -= minimum.z * bias.x + bias.y;
  5398. maximum.x += maximum.x * bias.x + bias.y;
  5399. maximum.y += maximum.y * bias.x + bias.y;
  5400. maximum.z += maximum.z * bias.x + bias.y;
  5401. }
  5402. return {
  5403. minimum: minimum,
  5404. maximum: maximum
  5405. };
  5406. };
  5407. Tools.Vector2ArrayFeeder = function (array) {
  5408. return function (index) {
  5409. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5410. var length = isFloatArray ? array.length / 2 : array.length;
  5411. if (index >= length) {
  5412. return null;
  5413. }
  5414. if (isFloatArray) {
  5415. var fa = array;
  5416. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5417. }
  5418. var a = array;
  5419. return a[index];
  5420. };
  5421. };
  5422. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5423. if (bias === void 0) { bias = null; }
  5424. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5425. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5426. var i = 0;
  5427. var cur = feeder(i++);
  5428. while (cur) {
  5429. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5430. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5431. cur = feeder(i++);
  5432. }
  5433. if (bias) {
  5434. minimum.x -= minimum.x * bias.x + bias.y;
  5435. minimum.y -= minimum.y * bias.x + bias.y;
  5436. maximum.x += maximum.x * bias.x + bias.y;
  5437. maximum.y += maximum.y * bias.x + bias.y;
  5438. }
  5439. return {
  5440. minimum: minimum,
  5441. maximum: maximum
  5442. };
  5443. };
  5444. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5445. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5446. return undefined;
  5447. return Array.isArray(obj) ? obj : [obj];
  5448. };
  5449. // Misc.
  5450. Tools.GetPointerPrefix = function () {
  5451. var eventPrefix = "pointer";
  5452. // Check if pointer events are supported
  5453. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5454. eventPrefix = "mouse";
  5455. }
  5456. return eventPrefix;
  5457. };
  5458. /**
  5459. * @param func - the function to be called
  5460. * @param requester - the object that will request the next frame. Falls back to window.
  5461. */
  5462. Tools.QueueNewFrame = function (func, requester) {
  5463. if (requester === void 0) { requester = window; }
  5464. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5465. /*if(requester.isPresenting) {
  5466. return;
  5467. } else*/ if (requester.requestAnimationFrame)
  5468. requester.requestAnimationFrame(func);
  5469. else if (requester.msRequestAnimationFrame)
  5470. requester.msRequestAnimationFrame(func);
  5471. else if (requester.webkitRequestAnimationFrame)
  5472. requester.webkitRequestAnimationFrame(func);
  5473. else if (requester.mozRequestAnimationFrame)
  5474. requester.mozRequestAnimationFrame(func);
  5475. else if (requester.oRequestAnimationFrame)
  5476. requester.oRequestAnimationFrame(func);
  5477. else {
  5478. window.setTimeout(func, 16);
  5479. }
  5480. };
  5481. Tools.RequestFullscreen = function (element) {
  5482. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5483. if (!requestFunction)
  5484. return;
  5485. requestFunction.call(element);
  5486. };
  5487. Tools.ExitFullscreen = function () {
  5488. if (document.exitFullscreen) {
  5489. document.exitFullscreen();
  5490. }
  5491. else if (document.mozCancelFullScreen) {
  5492. document.mozCancelFullScreen();
  5493. }
  5494. else if (document.webkitCancelFullScreen) {
  5495. document.webkitCancelFullScreen();
  5496. }
  5497. else if (document.msCancelFullScreen) {
  5498. document.msCancelFullScreen();
  5499. }
  5500. };
  5501. Tools.SetCorsBehavior = function (url, img) {
  5502. if (Tools.CorsBehavior) {
  5503. switch (typeof (Tools.CorsBehavior)) {
  5504. case "function":
  5505. var result = Tools.CorsBehavior(url);
  5506. if (result) {
  5507. img.crossOrigin = result;
  5508. }
  5509. break;
  5510. case "string":
  5511. default:
  5512. img.crossOrigin = Tools.CorsBehavior;
  5513. break;
  5514. }
  5515. }
  5516. };
  5517. // External files
  5518. Tools.CleanUrl = function (url) {
  5519. url = url.replace(/#/mg, "%23");
  5520. return url;
  5521. };
  5522. Tools.LoadImage = function (url, onload, onerror, database) {
  5523. if (url instanceof ArrayBuffer) {
  5524. url = Tools.EncodeArrayBufferTobase64(url);
  5525. }
  5526. url = Tools.CleanUrl(url);
  5527. var img = new Image();
  5528. if (url.substr(0, 5) !== "data:") {
  5529. Tools.SetCorsBehavior(url, img);
  5530. }
  5531. img.onload = function () {
  5532. onload(img);
  5533. };
  5534. img.onerror = function (err) {
  5535. Tools.Error("Error while trying to load image: " + url);
  5536. if (Tools.UseFallbackTexture) {
  5537. img.src = Tools.fallbackTexture;
  5538. onload(img);
  5539. }
  5540. else {
  5541. onerror();
  5542. }
  5543. };
  5544. var noIndexedDB = function () {
  5545. img.src = url;
  5546. };
  5547. var loadFromIndexedDB = function () {
  5548. database.loadImageFromDB(url, img);
  5549. };
  5550. //ANY database to do!
  5551. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5552. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5553. }
  5554. else {
  5555. if (url.indexOf("file:") !== 0) {
  5556. noIndexedDB();
  5557. }
  5558. else {
  5559. var textureName = url.substring(5).toLowerCase();
  5560. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5561. try {
  5562. var blobURL;
  5563. try {
  5564. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5565. }
  5566. catch (ex) {
  5567. // Chrome doesn't support oneTimeOnly parameter
  5568. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5569. }
  5570. img.src = blobURL;
  5571. }
  5572. catch (e) {
  5573. img.src = null;
  5574. }
  5575. }
  5576. else {
  5577. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5578. img.src = Tools.fallbackTexture;
  5579. }
  5580. }
  5581. }
  5582. return img;
  5583. };
  5584. //ANY
  5585. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5586. url = Tools.CleanUrl(url);
  5587. var noIndexedDB = function () {
  5588. var request = new XMLHttpRequest();
  5589. var loadUrl = Tools.BaseUrl + url;
  5590. request.open('GET', loadUrl, true);
  5591. if (useArrayBuffer) {
  5592. request.responseType = "arraybuffer";
  5593. }
  5594. request.onprogress = progressCallBack;
  5595. request.onreadystatechange = function () {
  5596. // In case of undefined state in some browsers.
  5597. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5598. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5599. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5600. callback(!useArrayBuffer ? request.responseText : request.response);
  5601. }
  5602. else {
  5603. if (onError) {
  5604. onError(request);
  5605. }
  5606. else {
  5607. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5608. }
  5609. }
  5610. }
  5611. };
  5612. request.send(null);
  5613. };
  5614. var loadFromIndexedDB = function () {
  5615. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5616. };
  5617. if (url.indexOf("file:") !== -1) {
  5618. var fileName = url.substring(5).toLowerCase();
  5619. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5620. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5621. }
  5622. else {
  5623. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5624. }
  5625. }
  5626. else {
  5627. // Caching all files
  5628. if (database && database.enableSceneOffline) {
  5629. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5630. }
  5631. else {
  5632. noIndexedDB();
  5633. }
  5634. }
  5635. };
  5636. /**
  5637. * Load a script (identified by an url). When the url returns, the
  5638. * content of this file is added into a new script element, attached to the DOM (body element)
  5639. */
  5640. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5641. var head = document.getElementsByTagName('head')[0];
  5642. var script = document.createElement('script');
  5643. script.type = 'text/javascript';
  5644. script.src = scriptUrl;
  5645. var self = this;
  5646. script.onload = function () {
  5647. if (onSuccess) {
  5648. onSuccess();
  5649. }
  5650. };
  5651. script.onerror = function () {
  5652. if (onError) {
  5653. onError();
  5654. }
  5655. };
  5656. head.appendChild(script);
  5657. };
  5658. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5659. var reader = new FileReader();
  5660. reader.onload = function (e) {
  5661. //target doesn't have result from ts 1.3
  5662. callback(e.target['result']);
  5663. };
  5664. reader.onprogress = progressCallback;
  5665. reader.readAsDataURL(fileToLoad);
  5666. };
  5667. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5668. var reader = new FileReader();
  5669. reader.onerror = function (e) {
  5670. Tools.Log("Error while reading file: " + fileToLoad.name);
  5671. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5672. };
  5673. reader.onload = function (e) {
  5674. //target doesn't have result from ts 1.3
  5675. callback(e.target['result']);
  5676. };
  5677. reader.onprogress = progressCallBack;
  5678. if (!useArrayBuffer) {
  5679. // Asynchronous read
  5680. reader.readAsText(fileToLoad);
  5681. }
  5682. else {
  5683. reader.readAsArrayBuffer(fileToLoad);
  5684. }
  5685. };
  5686. //returns a downloadable url to a file content.
  5687. Tools.FileAsURL = function (content) {
  5688. var fileBlob = new Blob([content]);
  5689. var url = window.URL || window.webkitURL;
  5690. var link = url.createObjectURL(fileBlob);
  5691. return link;
  5692. };
  5693. // Misc.
  5694. Tools.Format = function (value, decimals) {
  5695. if (decimals === void 0) { decimals = 2; }
  5696. return value.toFixed(decimals);
  5697. };
  5698. Tools.CheckExtends = function (v, min, max) {
  5699. if (v.x < min.x)
  5700. min.x = v.x;
  5701. if (v.y < min.y)
  5702. min.y = v.y;
  5703. if (v.z < min.z)
  5704. min.z = v.z;
  5705. if (v.x > max.x)
  5706. max.x = v.x;
  5707. if (v.y > max.y)
  5708. max.y = v.y;
  5709. if (v.z > max.z)
  5710. max.z = v.z;
  5711. };
  5712. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5713. for (var prop in source) {
  5714. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5715. continue;
  5716. }
  5717. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5718. continue;
  5719. }
  5720. var sourceValue = source[prop];
  5721. var typeOfSourceValue = typeof sourceValue;
  5722. if (typeOfSourceValue === "function") {
  5723. continue;
  5724. }
  5725. if (typeOfSourceValue === "object") {
  5726. if (sourceValue instanceof Array) {
  5727. destination[prop] = [];
  5728. if (sourceValue.length > 0) {
  5729. if (typeof sourceValue[0] == "object") {
  5730. for (var index = 0; index < sourceValue.length; index++) {
  5731. var clonedValue = cloneValue(sourceValue[index], destination);
  5732. if (destination[prop].indexOf(clonedValue) === -1) {
  5733. destination[prop].push(clonedValue);
  5734. }
  5735. }
  5736. }
  5737. else {
  5738. destination[prop] = sourceValue.slice(0);
  5739. }
  5740. }
  5741. }
  5742. else {
  5743. destination[prop] = cloneValue(sourceValue, destination);
  5744. }
  5745. }
  5746. else {
  5747. destination[prop] = sourceValue;
  5748. }
  5749. }
  5750. };
  5751. Tools.IsEmpty = function (obj) {
  5752. for (var i in obj) {
  5753. return false;
  5754. }
  5755. return true;
  5756. };
  5757. Tools.RegisterTopRootEvents = function (events) {
  5758. for (var index = 0; index < events.length; index++) {
  5759. var event = events[index];
  5760. window.addEventListener(event.name, event.handler, false);
  5761. try {
  5762. if (window.parent) {
  5763. window.parent.addEventListener(event.name, event.handler, false);
  5764. }
  5765. }
  5766. catch (e) {
  5767. // Silently fails...
  5768. }
  5769. }
  5770. };
  5771. Tools.UnregisterTopRootEvents = function (events) {
  5772. for (var index = 0; index < events.length; index++) {
  5773. var event = events[index];
  5774. window.removeEventListener(event.name, event.handler);
  5775. try {
  5776. if (window.parent) {
  5777. window.parent.removeEventListener(event.name, event.handler);
  5778. }
  5779. }
  5780. catch (e) {
  5781. // Silently fails...
  5782. }
  5783. }
  5784. };
  5785. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5786. if (mimeType === void 0) { mimeType = "image/png"; }
  5787. // Read the contents of the framebuffer
  5788. var numberOfChannelsByLine = width * 4;
  5789. var halfHeight = height / 2;
  5790. //Reading datas from WebGL
  5791. var data = engine.readPixels(0, 0, width, height);
  5792. //To flip image on Y axis.
  5793. for (var i = 0; i < halfHeight; i++) {
  5794. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5795. var currentCell = j + i * numberOfChannelsByLine;
  5796. var targetLine = height - i - 1;
  5797. var targetCell = j + targetLine * numberOfChannelsByLine;
  5798. var temp = data[currentCell];
  5799. data[currentCell] = data[targetCell];
  5800. data[targetCell] = temp;
  5801. }
  5802. }
  5803. // Create a 2D canvas to store the result
  5804. if (!screenshotCanvas) {
  5805. screenshotCanvas = document.createElement('canvas');
  5806. }
  5807. screenshotCanvas.width = width;
  5808. screenshotCanvas.height = height;
  5809. var context = screenshotCanvas.getContext('2d');
  5810. // Copy the pixels to a 2D canvas
  5811. var imageData = context.createImageData(width, height);
  5812. var castData = (imageData.data);
  5813. castData.set(data);
  5814. context.putImageData(imageData, 0, 0);
  5815. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5816. };
  5817. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5818. if (mimeType === void 0) { mimeType = "image/png"; }
  5819. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5820. if (successCallback) {
  5821. successCallback(base64Image);
  5822. }
  5823. else {
  5824. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5825. if (("download" in document.createElement("a"))) {
  5826. var a = window.document.createElement("a");
  5827. a.href = base64Image;
  5828. var date = new Date();
  5829. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5830. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5831. window.document.body.appendChild(a);
  5832. a.addEventListener("click", function () {
  5833. a.parentElement.removeChild(a);
  5834. });
  5835. a.click();
  5836. //Or opening a new tab with the image if it is not possible to automatically start download.
  5837. }
  5838. else {
  5839. var newWindow = window.open("");
  5840. var img = newWindow.document.createElement("img");
  5841. img.src = base64Image;
  5842. newWindow.document.body.appendChild(img);
  5843. }
  5844. }
  5845. };
  5846. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5847. if (mimeType === void 0) { mimeType = "image/png"; }
  5848. var width;
  5849. var height;
  5850. // If a precision value is specified
  5851. if (size.precision) {
  5852. width = Math.round(engine.getRenderWidth() * size.precision);
  5853. height = Math.round(width / engine.getAspectRatio(camera));
  5854. }
  5855. else if (size.width && size.height) {
  5856. width = size.width;
  5857. height = size.height;
  5858. }
  5859. else if (size.width && !size.height) {
  5860. width = size.width;
  5861. height = Math.round(width / engine.getAspectRatio(camera));
  5862. }
  5863. else if (size.height && !size.width) {
  5864. height = size.height;
  5865. width = Math.round(height * engine.getAspectRatio(camera));
  5866. }
  5867. else if (!isNaN(size)) {
  5868. height = size;
  5869. width = size;
  5870. }
  5871. else {
  5872. Tools.Error("Invalid 'size' parameter !");
  5873. return;
  5874. }
  5875. if (!screenshotCanvas) {
  5876. screenshotCanvas = document.createElement('canvas');
  5877. }
  5878. screenshotCanvas.width = width;
  5879. screenshotCanvas.height = height;
  5880. var renderContext = screenshotCanvas.getContext("2d");
  5881. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5882. var newWidth = width;
  5883. var newHeight = newWidth / ratio;
  5884. if (newHeight > height) {
  5885. newHeight = height;
  5886. newWidth = newHeight * ratio;
  5887. }
  5888. var offsetX = Math.max(0, width - newWidth) / 2;
  5889. var offsetY = Math.max(0, height - newHeight) / 2;
  5890. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5891. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5892. };
  5893. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5894. if (mimeType === void 0) { mimeType = "image/png"; }
  5895. if (samples === void 0) { samples = 1; }
  5896. var width;
  5897. var height;
  5898. //If a precision value is specified
  5899. if (size.precision) {
  5900. width = Math.round(engine.getRenderWidth() * size.precision);
  5901. height = Math.round(width / engine.getAspectRatio(camera));
  5902. size = { width: width, height: height };
  5903. }
  5904. else if (size.width && size.height) {
  5905. width = size.width;
  5906. height = size.height;
  5907. }
  5908. else if (size.width && !size.height) {
  5909. width = size.width;
  5910. height = Math.round(width / engine.getAspectRatio(camera));
  5911. size = { width: width, height: height };
  5912. }
  5913. else if (size.height && !size.width) {
  5914. height = size.height;
  5915. width = Math.round(height * engine.getAspectRatio(camera));
  5916. size = { width: width, height: height };
  5917. }
  5918. else if (!isNaN(size)) {
  5919. height = size;
  5920. width = size;
  5921. }
  5922. else {
  5923. Tools.Error("Invalid 'size' parameter !");
  5924. return;
  5925. }
  5926. var scene = camera.getScene();
  5927. var previousCamera = null;
  5928. if (scene.activeCamera !== camera) {
  5929. previousCamera = scene.activeCamera;
  5930. scene.activeCamera = camera;
  5931. }
  5932. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5933. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5934. texture.renderList = scene.meshes;
  5935. texture.samples = samples;
  5936. texture.onAfterRenderObservable.add(function () {
  5937. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5938. });
  5939. scene.incrementRenderId();
  5940. scene.resetCachedMaterial();
  5941. texture.render(true);
  5942. texture.dispose();
  5943. if (previousCamera) {
  5944. scene.activeCamera = previousCamera;
  5945. }
  5946. camera.getProjectionMatrix(true); // Force cache refresh;
  5947. };
  5948. // XHR response validator for local file scenario
  5949. Tools.ValidateXHRData = function (xhr, dataType) {
  5950. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5951. if (dataType === void 0) { dataType = 7; }
  5952. try {
  5953. if (dataType & 1) {
  5954. if (xhr.responseText && xhr.responseText.length > 0) {
  5955. return true;
  5956. }
  5957. else if (dataType === 1) {
  5958. return false;
  5959. }
  5960. }
  5961. if (dataType & 2) {
  5962. // Check header width and height since there is no "TGA" magic number
  5963. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5964. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5965. return true;
  5966. }
  5967. else if (dataType === 2) {
  5968. return false;
  5969. }
  5970. }
  5971. if (dataType & 4) {
  5972. // Check for the "DDS" magic number
  5973. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5974. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5975. return true;
  5976. }
  5977. else {
  5978. return false;
  5979. }
  5980. }
  5981. }
  5982. catch (e) {
  5983. // Global protection
  5984. }
  5985. return false;
  5986. };
  5987. /**
  5988. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5989. * Be aware Math.random() could cause collisions, but:
  5990. * "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"
  5991. */
  5992. Tools.RandomId = function () {
  5993. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5994. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5995. return v.toString(16);
  5996. });
  5997. };
  5998. Object.defineProperty(Tools, "NoneLogLevel", {
  5999. get: function () {
  6000. return Tools._NoneLogLevel;
  6001. },
  6002. enumerable: true,
  6003. configurable: true
  6004. });
  6005. Object.defineProperty(Tools, "MessageLogLevel", {
  6006. get: function () {
  6007. return Tools._MessageLogLevel;
  6008. },
  6009. enumerable: true,
  6010. configurable: true
  6011. });
  6012. Object.defineProperty(Tools, "WarningLogLevel", {
  6013. get: function () {
  6014. return Tools._WarningLogLevel;
  6015. },
  6016. enumerable: true,
  6017. configurable: true
  6018. });
  6019. Object.defineProperty(Tools, "ErrorLogLevel", {
  6020. get: function () {
  6021. return Tools._ErrorLogLevel;
  6022. },
  6023. enumerable: true,
  6024. configurable: true
  6025. });
  6026. Object.defineProperty(Tools, "AllLogLevel", {
  6027. get: function () {
  6028. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6029. },
  6030. enumerable: true,
  6031. configurable: true
  6032. });
  6033. Tools._AddLogEntry = function (entry) {
  6034. Tools._LogCache = entry + Tools._LogCache;
  6035. if (Tools.OnNewCacheEntry) {
  6036. Tools.OnNewCacheEntry(entry);
  6037. }
  6038. };
  6039. Tools._FormatMessage = function (message) {
  6040. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6041. var date = new Date();
  6042. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6043. };
  6044. Tools._LogDisabled = function (message) {
  6045. // nothing to do
  6046. };
  6047. Tools._LogEnabled = function (message) {
  6048. var formattedMessage = Tools._FormatMessage(message);
  6049. console.log("BJS - " + formattedMessage);
  6050. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6051. Tools._AddLogEntry(entry);
  6052. };
  6053. Tools._WarnDisabled = function (message) {
  6054. // nothing to do
  6055. };
  6056. Tools._WarnEnabled = function (message) {
  6057. var formattedMessage = Tools._FormatMessage(message);
  6058. console.warn("BJS - " + formattedMessage);
  6059. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6060. Tools._AddLogEntry(entry);
  6061. };
  6062. Tools._ErrorDisabled = function (message) {
  6063. // nothing to do
  6064. };
  6065. Tools._ErrorEnabled = function (message) {
  6066. Tools.errorsCount++;
  6067. var formattedMessage = Tools._FormatMessage(message);
  6068. console.error("BJS - " + formattedMessage);
  6069. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6070. Tools._AddLogEntry(entry);
  6071. };
  6072. Object.defineProperty(Tools, "LogCache", {
  6073. get: function () {
  6074. return Tools._LogCache;
  6075. },
  6076. enumerable: true,
  6077. configurable: true
  6078. });
  6079. Tools.ClearLogCache = function () {
  6080. Tools._LogCache = "";
  6081. Tools.errorsCount = 0;
  6082. };
  6083. Object.defineProperty(Tools, "LogLevels", {
  6084. set: function (level) {
  6085. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6086. Tools.Log = Tools._LogEnabled;
  6087. }
  6088. else {
  6089. Tools.Log = Tools._LogDisabled;
  6090. }
  6091. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6092. Tools.Warn = Tools._WarnEnabled;
  6093. }
  6094. else {
  6095. Tools.Warn = Tools._WarnDisabled;
  6096. }
  6097. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6098. Tools.Error = Tools._ErrorEnabled;
  6099. }
  6100. else {
  6101. Tools.Error = Tools._ErrorDisabled;
  6102. }
  6103. },
  6104. enumerable: true,
  6105. configurable: true
  6106. });
  6107. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6108. get: function () {
  6109. return Tools._PerformanceNoneLogLevel;
  6110. },
  6111. enumerable: true,
  6112. configurable: true
  6113. });
  6114. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6115. get: function () {
  6116. return Tools._PerformanceUserMarkLogLevel;
  6117. },
  6118. enumerable: true,
  6119. configurable: true
  6120. });
  6121. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6122. get: function () {
  6123. return Tools._PerformanceConsoleLogLevel;
  6124. },
  6125. enumerable: true,
  6126. configurable: true
  6127. });
  6128. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6129. set: function (level) {
  6130. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6131. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6132. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6133. return;
  6134. }
  6135. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6136. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6137. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6138. return;
  6139. }
  6140. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6141. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6142. },
  6143. enumerable: true,
  6144. configurable: true
  6145. });
  6146. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6147. };
  6148. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6149. };
  6150. Tools._StartUserMark = function (counterName, condition) {
  6151. if (condition === void 0) { condition = true; }
  6152. if (!condition || !Tools._performance.mark) {
  6153. return;
  6154. }
  6155. Tools._performance.mark(counterName + "-Begin");
  6156. };
  6157. Tools._EndUserMark = function (counterName, condition) {
  6158. if (condition === void 0) { condition = true; }
  6159. if (!condition || !Tools._performance.mark) {
  6160. return;
  6161. }
  6162. Tools._performance.mark(counterName + "-End");
  6163. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6164. };
  6165. Tools._StartPerformanceConsole = function (counterName, condition) {
  6166. if (condition === void 0) { condition = true; }
  6167. if (!condition) {
  6168. return;
  6169. }
  6170. Tools._StartUserMark(counterName, condition);
  6171. if (console.time) {
  6172. console.time(counterName);
  6173. }
  6174. };
  6175. Tools._EndPerformanceConsole = function (counterName, condition) {
  6176. if (condition === void 0) { condition = true; }
  6177. if (!condition) {
  6178. return;
  6179. }
  6180. Tools._EndUserMark(counterName, condition);
  6181. if (console.time) {
  6182. console.timeEnd(counterName);
  6183. }
  6184. };
  6185. Object.defineProperty(Tools, "Now", {
  6186. get: function () {
  6187. if (window.performance && window.performance.now) {
  6188. return window.performance.now();
  6189. }
  6190. return new Date().getTime();
  6191. },
  6192. enumerable: true,
  6193. configurable: true
  6194. });
  6195. /**
  6196. * This method will return the name of the class used to create the instance of the given object.
  6197. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6198. * @param object the object to get the class name from
  6199. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6200. */
  6201. Tools.getClassName = function (object, isType) {
  6202. if (isType === void 0) { isType = false; }
  6203. var name = null;
  6204. if (!isType && object.getClassName) {
  6205. name = object.getClassName();
  6206. }
  6207. else {
  6208. if (object instanceof Object) {
  6209. var classObj = isType ? object : Object.getPrototypeOf(object);
  6210. name = classObj.constructor["__bjsclassName__"];
  6211. }
  6212. if (!name) {
  6213. name = typeof object;
  6214. }
  6215. }
  6216. return name;
  6217. };
  6218. Tools.first = function (array, predicate) {
  6219. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6220. var el = array_1[_i];
  6221. if (predicate(el)) {
  6222. return el;
  6223. }
  6224. }
  6225. };
  6226. /**
  6227. * This method will return the name of the full name of the class, including its owning module (if any).
  6228. * 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).
  6229. * @param object the object to get the class name from
  6230. * @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.
  6231. */
  6232. Tools.getFullClassName = function (object, isType) {
  6233. if (isType === void 0) { isType = false; }
  6234. var className = null;
  6235. var moduleName = null;
  6236. if (!isType && object.getClassName) {
  6237. className = object.getClassName();
  6238. }
  6239. else {
  6240. if (object instanceof Object) {
  6241. var classObj = isType ? object : Object.getPrototypeOf(object);
  6242. className = classObj.constructor["__bjsclassName__"];
  6243. moduleName = classObj.constructor["__bjsmoduleName__"];
  6244. }
  6245. if (!className) {
  6246. className = typeof object;
  6247. }
  6248. }
  6249. if (!className) {
  6250. return null;
  6251. }
  6252. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6253. };
  6254. /**
  6255. * 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.
  6256. * @param array
  6257. */
  6258. Tools.arrayOrStringFeeder = function (array) {
  6259. return function (index) {
  6260. if (index >= array.length) {
  6261. return null;
  6262. }
  6263. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6264. if (val && val.getHashCode) {
  6265. val = val.getHashCode();
  6266. }
  6267. if (typeof val === "string") {
  6268. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6269. }
  6270. return val;
  6271. };
  6272. };
  6273. /**
  6274. * Compute the hashCode of a stream of number
  6275. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6276. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6277. * @return the hash code computed
  6278. */
  6279. Tools.hashCodeFromStream = function (feeder) {
  6280. // Based from here: http://stackoverflow.com/a/7616484/802124
  6281. var hash = 0;
  6282. var index = 0;
  6283. var chr = feeder(index++);
  6284. while (chr != null) {
  6285. hash = ((hash << 5) - hash) + chr;
  6286. hash |= 0; // Convert to 32bit integer
  6287. chr = feeder(index++);
  6288. }
  6289. return hash;
  6290. };
  6291. return Tools;
  6292. }());
  6293. Tools.BaseUrl = "";
  6294. Tools.CorsBehavior = "anonymous";
  6295. Tools.UseFallbackTexture = true;
  6296. // Used in case of a texture loading problem
  6297. 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";
  6298. // Logs
  6299. Tools._NoneLogLevel = 0;
  6300. Tools._MessageLogLevel = 1;
  6301. Tools._WarningLogLevel = 2;
  6302. Tools._ErrorLogLevel = 4;
  6303. Tools._LogCache = "";
  6304. Tools.errorsCount = 0;
  6305. Tools.Log = Tools._LogEnabled;
  6306. Tools.Warn = Tools._WarnEnabled;
  6307. Tools.Error = Tools._ErrorEnabled;
  6308. // Performances
  6309. Tools._PerformanceNoneLogLevel = 0;
  6310. Tools._PerformanceUserMarkLogLevel = 1;
  6311. Tools._PerformanceConsoleLogLevel = 2;
  6312. Tools._performance = window.performance;
  6313. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6314. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6315. BABYLON.Tools = Tools;
  6316. /**
  6317. * This class is used to track a performance counter which is number based.
  6318. * The user has access to many properties which give statistics of different nature
  6319. *
  6320. * The implementer can track two kinds of Performance Counter: time and count
  6321. * 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.
  6322. * 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.
  6323. */
  6324. var PerfCounter = (function () {
  6325. function PerfCounter() {
  6326. this._startMonitoringTime = 0;
  6327. this._min = 0;
  6328. this._max = 0;
  6329. this._average = 0;
  6330. this._lastSecAverage = 0;
  6331. this._current = 0;
  6332. this._totalValueCount = 0;
  6333. this._totalAccumulated = 0;
  6334. this._lastSecAccumulated = 0;
  6335. this._lastSecTime = 0;
  6336. this._lastSecValueCount = 0;
  6337. }
  6338. Object.defineProperty(PerfCounter.prototype, "min", {
  6339. /**
  6340. * Returns the smallest value ever
  6341. */
  6342. get: function () {
  6343. return this._min;
  6344. },
  6345. enumerable: true,
  6346. configurable: true
  6347. });
  6348. Object.defineProperty(PerfCounter.prototype, "max", {
  6349. /**
  6350. * Returns the biggest value ever
  6351. */
  6352. get: function () {
  6353. return this._max;
  6354. },
  6355. enumerable: true,
  6356. configurable: true
  6357. });
  6358. Object.defineProperty(PerfCounter.prototype, "average", {
  6359. /**
  6360. * Returns the average value since the performance counter is running
  6361. */
  6362. get: function () {
  6363. return this._average;
  6364. },
  6365. enumerable: true,
  6366. configurable: true
  6367. });
  6368. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6369. /**
  6370. * Returns the average value of the last second the counter was monitored
  6371. */
  6372. get: function () {
  6373. return this._lastSecAverage;
  6374. },
  6375. enumerable: true,
  6376. configurable: true
  6377. });
  6378. Object.defineProperty(PerfCounter.prototype, "current", {
  6379. /**
  6380. * Returns the current value
  6381. */
  6382. get: function () {
  6383. return this._current;
  6384. },
  6385. enumerable: true,
  6386. configurable: true
  6387. });
  6388. Object.defineProperty(PerfCounter.prototype, "total", {
  6389. get: function () {
  6390. return this._totalAccumulated;
  6391. },
  6392. enumerable: true,
  6393. configurable: true
  6394. });
  6395. /**
  6396. * Call this method to start monitoring a new frame.
  6397. * 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.
  6398. */
  6399. PerfCounter.prototype.fetchNewFrame = function () {
  6400. this._totalValueCount++;
  6401. this._current = 0;
  6402. this._lastSecValueCount++;
  6403. };
  6404. /**
  6405. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6406. * @param newCount the count value to add to the monitored count
  6407. * @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.
  6408. */
  6409. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6410. if (!PerfCounter.Enabled) {
  6411. return;
  6412. }
  6413. this._current += newCount;
  6414. if (fetchResult) {
  6415. this._fetchResult();
  6416. }
  6417. };
  6418. /**
  6419. * Start monitoring this performance counter
  6420. */
  6421. PerfCounter.prototype.beginMonitoring = function () {
  6422. if (!PerfCounter.Enabled) {
  6423. return;
  6424. }
  6425. this._startMonitoringTime = Tools.Now;
  6426. };
  6427. /**
  6428. * Compute the time lapsed since the previous beginMonitoring() call.
  6429. * @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
  6430. */
  6431. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6432. if (newFrame === void 0) { newFrame = true; }
  6433. if (!PerfCounter.Enabled) {
  6434. return;
  6435. }
  6436. if (newFrame) {
  6437. this.fetchNewFrame();
  6438. }
  6439. var currentTime = Tools.Now;
  6440. this._current = currentTime - this._startMonitoringTime;
  6441. if (newFrame) {
  6442. this._fetchResult();
  6443. }
  6444. };
  6445. PerfCounter.prototype._fetchResult = function () {
  6446. this._totalAccumulated += this._current;
  6447. this._lastSecAccumulated += this._current;
  6448. // Min/Max update
  6449. this._min = Math.min(this._min, this._current);
  6450. this._max = Math.max(this._max, this._current);
  6451. this._average = this._totalAccumulated / this._totalValueCount;
  6452. // Reset last sec?
  6453. var now = Tools.Now;
  6454. if ((now - this._lastSecTime) > 1000) {
  6455. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6456. this._lastSecTime = now;
  6457. this._lastSecAccumulated = 0;
  6458. this._lastSecValueCount = 0;
  6459. }
  6460. };
  6461. return PerfCounter;
  6462. }());
  6463. PerfCounter.Enabled = true;
  6464. BABYLON.PerfCounter = PerfCounter;
  6465. /**
  6466. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6467. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6468. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6469. * @param name The name of the class, case should be preserved
  6470. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6471. */
  6472. function className(name, module) {
  6473. return function (target) {
  6474. target["__bjsclassName__"] = name;
  6475. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6476. };
  6477. }
  6478. BABYLON.className = className;
  6479. /**
  6480. * An implementation of a loop for asynchronous functions.
  6481. */
  6482. var AsyncLoop = (function () {
  6483. /**
  6484. * Constroctor.
  6485. * @param iterations the number of iterations.
  6486. * @param _fn the function to run each iteration
  6487. * @param _successCallback the callback that will be called upon succesful execution
  6488. * @param offset starting offset.
  6489. */
  6490. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6491. if (offset === void 0) { offset = 0; }
  6492. this.iterations = iterations;
  6493. this._fn = _fn;
  6494. this._successCallback = _successCallback;
  6495. this.index = offset - 1;
  6496. this._done = false;
  6497. }
  6498. /**
  6499. * Execute the next iteration. Must be called after the last iteration was finished.
  6500. */
  6501. AsyncLoop.prototype.executeNext = function () {
  6502. if (!this._done) {
  6503. if (this.index + 1 < this.iterations) {
  6504. ++this.index;
  6505. this._fn(this);
  6506. }
  6507. else {
  6508. this.breakLoop();
  6509. }
  6510. }
  6511. };
  6512. /**
  6513. * Break the loop and run the success callback.
  6514. */
  6515. AsyncLoop.prototype.breakLoop = function () {
  6516. this._done = true;
  6517. this._successCallback();
  6518. };
  6519. /**
  6520. * Helper function
  6521. */
  6522. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6523. if (offset === void 0) { offset = 0; }
  6524. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6525. loop.executeNext();
  6526. return loop;
  6527. };
  6528. /**
  6529. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6530. * @param iterations total number of iterations
  6531. * @param syncedIterations number of synchronous iterations in each async iteration.
  6532. * @param fn the function to call each iteration.
  6533. * @param callback a success call back that will be called when iterating stops.
  6534. * @param breakFunction a break condition (optional)
  6535. * @param timeout timeout settings for the setTimeout function. default - 0.
  6536. * @constructor
  6537. */
  6538. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6539. if (timeout === void 0) { timeout = 0; }
  6540. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6541. if (breakFunction && breakFunction())
  6542. loop.breakLoop();
  6543. else {
  6544. setTimeout(function () {
  6545. for (var i = 0; i < syncedIterations; ++i) {
  6546. var iteration = (loop.index * syncedIterations) + i;
  6547. if (iteration >= iterations)
  6548. break;
  6549. fn(iteration);
  6550. if (breakFunction && breakFunction()) {
  6551. loop.breakLoop();
  6552. break;
  6553. }
  6554. }
  6555. loop.executeNext();
  6556. }, timeout);
  6557. }
  6558. }, callback);
  6559. };
  6560. return AsyncLoop;
  6561. }());
  6562. BABYLON.AsyncLoop = AsyncLoop;
  6563. })(BABYLON || (BABYLON = {}));
  6564. //# sourceMappingURL=babylon.tools.js.map
  6565. var BABYLON;
  6566. (function (BABYLON) {
  6567. var Internals;
  6568. (function (Internals) {
  6569. var _AlphaState = (function () {
  6570. /**
  6571. * Initializes the state.
  6572. */
  6573. function _AlphaState() {
  6574. this._isAlphaBlendDirty = false;
  6575. this._isBlendFunctionParametersDirty = false;
  6576. this._isBlendEquationParametersDirty = false;
  6577. this._isBlendConstantsDirty = false;
  6578. this._alphaBlend = false;
  6579. this._blendFunctionParameters = new Array(4);
  6580. this._blendEquationParameters = new Array(2);
  6581. this._blendConstants = new Array(4);
  6582. this.reset();
  6583. }
  6584. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6585. get: function () {
  6586. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6587. },
  6588. enumerable: true,
  6589. configurable: true
  6590. });
  6591. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6592. get: function () {
  6593. return this._alphaBlend;
  6594. },
  6595. set: function (value) {
  6596. if (this._alphaBlend === value) {
  6597. return;
  6598. }
  6599. this._alphaBlend = value;
  6600. this._isAlphaBlendDirty = true;
  6601. },
  6602. enumerable: true,
  6603. configurable: true
  6604. });
  6605. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6606. if (this._blendConstants[0] === r &&
  6607. this._blendConstants[1] === g &&
  6608. this._blendConstants[2] === b &&
  6609. this._blendConstants[3] === a) {
  6610. return;
  6611. }
  6612. this._blendConstants[0] = r;
  6613. this._blendConstants[1] = g;
  6614. this._blendConstants[2] = b;
  6615. this._blendConstants[3] = a;
  6616. this._isBlendConstantsDirty = true;
  6617. };
  6618. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6619. if (this._blendFunctionParameters[0] === value0 &&
  6620. this._blendFunctionParameters[1] === value1 &&
  6621. this._blendFunctionParameters[2] === value2 &&
  6622. this._blendFunctionParameters[3] === value3) {
  6623. return;
  6624. }
  6625. this._blendFunctionParameters[0] = value0;
  6626. this._blendFunctionParameters[1] = value1;
  6627. this._blendFunctionParameters[2] = value2;
  6628. this._blendFunctionParameters[3] = value3;
  6629. this._isBlendFunctionParametersDirty = true;
  6630. };
  6631. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6632. if (this._blendEquationParameters[0] === rgb &&
  6633. this._blendEquationParameters[1] === alpha) {
  6634. return;
  6635. }
  6636. this._blendEquationParameters[0] = rgb;
  6637. this._blendEquationParameters[1] = alpha;
  6638. this._isBlendEquationParametersDirty = true;
  6639. };
  6640. _AlphaState.prototype.reset = function () {
  6641. this._alphaBlend = false;
  6642. this._blendFunctionParameters[0] = null;
  6643. this._blendFunctionParameters[1] = null;
  6644. this._blendFunctionParameters[2] = null;
  6645. this._blendFunctionParameters[3] = null;
  6646. this._blendEquationParameters[0] = null;
  6647. this._blendEquationParameters[1] = null;
  6648. this._blendConstants[0] = null;
  6649. this._blendConstants[1] = null;
  6650. this._blendConstants[2] = null;
  6651. this._blendConstants[3] = null;
  6652. this._isAlphaBlendDirty = true;
  6653. this._isBlendFunctionParametersDirty = false;
  6654. this._isBlendEquationParametersDirty = false;
  6655. this._isBlendConstantsDirty = false;
  6656. };
  6657. _AlphaState.prototype.apply = function (gl) {
  6658. if (!this.isDirty) {
  6659. return;
  6660. }
  6661. // Alpha blend
  6662. if (this._isAlphaBlendDirty) {
  6663. if (this._alphaBlend) {
  6664. gl.enable(gl.BLEND);
  6665. }
  6666. else {
  6667. gl.disable(gl.BLEND);
  6668. }
  6669. this._isAlphaBlendDirty = false;
  6670. }
  6671. // Alpha function
  6672. if (this._isBlendFunctionParametersDirty) {
  6673. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6674. this._isBlendFunctionParametersDirty = false;
  6675. }
  6676. // Alpha equation
  6677. if (this._isBlendEquationParametersDirty) {
  6678. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6679. this._isBlendEquationParametersDirty = false;
  6680. }
  6681. // Constants
  6682. if (this._isBlendConstantsDirty) {
  6683. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6684. this._isBlendConstantsDirty = false;
  6685. }
  6686. };
  6687. return _AlphaState;
  6688. }());
  6689. Internals._AlphaState = _AlphaState;
  6690. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6691. })(BABYLON || (BABYLON = {}));
  6692. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6693. var BABYLON;
  6694. (function (BABYLON) {
  6695. var Internals;
  6696. (function (Internals) {
  6697. var _DepthCullingState = (function () {
  6698. /**
  6699. * Initializes the state.
  6700. */
  6701. function _DepthCullingState() {
  6702. this._isDepthTestDirty = false;
  6703. this._isDepthMaskDirty = false;
  6704. this._isDepthFuncDirty = false;
  6705. this._isCullFaceDirty = false;
  6706. this._isCullDirty = false;
  6707. this._isZOffsetDirty = false;
  6708. this.reset();
  6709. }
  6710. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6711. get: function () {
  6712. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6718. get: function () {
  6719. return this._zOffset;
  6720. },
  6721. set: function (value) {
  6722. if (this._zOffset === value) {
  6723. return;
  6724. }
  6725. this._zOffset = value;
  6726. this._isZOffsetDirty = true;
  6727. },
  6728. enumerable: true,
  6729. configurable: true
  6730. });
  6731. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6732. get: function () {
  6733. return this._cullFace;
  6734. },
  6735. set: function (value) {
  6736. if (this._cullFace === value) {
  6737. return;
  6738. }
  6739. this._cullFace = value;
  6740. this._isCullFaceDirty = true;
  6741. },
  6742. enumerable: true,
  6743. configurable: true
  6744. });
  6745. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6746. get: function () {
  6747. return this._cull;
  6748. },
  6749. set: function (value) {
  6750. if (this._cull === value) {
  6751. return;
  6752. }
  6753. this._cull = value;
  6754. this._isCullDirty = true;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6760. get: function () {
  6761. return this._depthFunc;
  6762. },
  6763. set: function (value) {
  6764. if (this._depthFunc === value) {
  6765. return;
  6766. }
  6767. this._depthFunc = value;
  6768. this._isDepthFuncDirty = true;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6774. get: function () {
  6775. return this._depthMask;
  6776. },
  6777. set: function (value) {
  6778. if (this._depthMask === value) {
  6779. return;
  6780. }
  6781. this._depthMask = value;
  6782. this._isDepthMaskDirty = true;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6788. get: function () {
  6789. return this._depthTest;
  6790. },
  6791. set: function (value) {
  6792. if (this._depthTest === value) {
  6793. return;
  6794. }
  6795. this._depthTest = value;
  6796. this._isDepthTestDirty = true;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. _DepthCullingState.prototype.reset = function () {
  6802. this._depthMask = true;
  6803. this._depthTest = true;
  6804. this._depthFunc = null;
  6805. this._cullFace = null;
  6806. this._cull = null;
  6807. this._zOffset = 0;
  6808. this._isDepthTestDirty = true;
  6809. this._isDepthMaskDirty = true;
  6810. this._isDepthFuncDirty = false;
  6811. this._isCullFaceDirty = false;
  6812. this._isCullDirty = false;
  6813. this._isZOffsetDirty = false;
  6814. };
  6815. _DepthCullingState.prototype.apply = function (gl) {
  6816. if (!this.isDirty) {
  6817. return;
  6818. }
  6819. // Cull
  6820. if (this._isCullDirty) {
  6821. if (this.cull) {
  6822. gl.enable(gl.CULL_FACE);
  6823. }
  6824. else {
  6825. gl.disable(gl.CULL_FACE);
  6826. }
  6827. this._isCullDirty = false;
  6828. }
  6829. // Cull face
  6830. if (this._isCullFaceDirty) {
  6831. gl.cullFace(this.cullFace);
  6832. this._isCullFaceDirty = false;
  6833. }
  6834. // Depth mask
  6835. if (this._isDepthMaskDirty) {
  6836. gl.depthMask(this.depthMask);
  6837. this._isDepthMaskDirty = false;
  6838. }
  6839. // Depth test
  6840. if (this._isDepthTestDirty) {
  6841. if (this.depthTest) {
  6842. gl.enable(gl.DEPTH_TEST);
  6843. }
  6844. else {
  6845. gl.disable(gl.DEPTH_TEST);
  6846. }
  6847. this._isDepthTestDirty = false;
  6848. }
  6849. // Depth func
  6850. if (this._isDepthFuncDirty) {
  6851. gl.depthFunc(this.depthFunc);
  6852. this._isDepthFuncDirty = false;
  6853. }
  6854. // zOffset
  6855. if (this._isZOffsetDirty) {
  6856. if (this.zOffset) {
  6857. gl.enable(gl.POLYGON_OFFSET_FILL);
  6858. gl.polygonOffset(this.zOffset, 0);
  6859. }
  6860. else {
  6861. gl.disable(gl.POLYGON_OFFSET_FILL);
  6862. }
  6863. this._isZOffsetDirty = false;
  6864. }
  6865. };
  6866. return _DepthCullingState;
  6867. }());
  6868. Internals._DepthCullingState = _DepthCullingState;
  6869. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6870. })(BABYLON || (BABYLON = {}));
  6871. //# sourceMappingURL=babylon.depthCullingState.js.map
  6872. var BABYLON;
  6873. (function (BABYLON) {
  6874. var Internals;
  6875. (function (Internals) {
  6876. var _StencilState = (function () {
  6877. function _StencilState() {
  6878. this._isStencilTestDirty = false;
  6879. this._isStencilMaskDirty = false;
  6880. this._isStencilFuncDirty = false;
  6881. this._isStencilOpDirty = false;
  6882. this.reset();
  6883. }
  6884. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6885. get: function () {
  6886. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6887. },
  6888. enumerable: true,
  6889. configurable: true
  6890. });
  6891. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6892. get: function () {
  6893. return this._stencilFunc;
  6894. },
  6895. set: function (value) {
  6896. if (this._stencilFunc === value) {
  6897. return;
  6898. }
  6899. this._stencilFunc = value;
  6900. this._isStencilFuncDirty = true;
  6901. },
  6902. enumerable: true,
  6903. configurable: true
  6904. });
  6905. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6906. get: function () {
  6907. return this._stencilFuncRef;
  6908. },
  6909. set: function (value) {
  6910. if (this._stencilFuncRef === value) {
  6911. return;
  6912. }
  6913. this._stencilFuncRef = value;
  6914. this._isStencilFuncDirty = true;
  6915. },
  6916. enumerable: true,
  6917. configurable: true
  6918. });
  6919. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6920. get: function () {
  6921. return this._stencilFuncMask;
  6922. },
  6923. set: function (value) {
  6924. if (this._stencilFuncMask === value) {
  6925. return;
  6926. }
  6927. this._stencilFuncMask = value;
  6928. this._isStencilFuncDirty = true;
  6929. },
  6930. enumerable: true,
  6931. configurable: true
  6932. });
  6933. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6934. get: function () {
  6935. return this._stencilOpStencilFail;
  6936. },
  6937. set: function (value) {
  6938. if (this._stencilOpStencilFail === value) {
  6939. return;
  6940. }
  6941. this._stencilOpStencilFail = value;
  6942. this._isStencilOpDirty = true;
  6943. },
  6944. enumerable: true,
  6945. configurable: true
  6946. });
  6947. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6948. get: function () {
  6949. return this._stencilOpDepthFail;
  6950. },
  6951. set: function (value) {
  6952. if (this._stencilOpDepthFail === value) {
  6953. return;
  6954. }
  6955. this._stencilOpDepthFail = value;
  6956. this._isStencilOpDirty = true;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6962. get: function () {
  6963. return this._stencilOpStencilDepthPass;
  6964. },
  6965. set: function (value) {
  6966. if (this._stencilOpStencilDepthPass === value) {
  6967. return;
  6968. }
  6969. this._stencilOpStencilDepthPass = value;
  6970. this._isStencilOpDirty = true;
  6971. },
  6972. enumerable: true,
  6973. configurable: true
  6974. });
  6975. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6976. get: function () {
  6977. return this._stencilMask;
  6978. },
  6979. set: function (value) {
  6980. if (this._stencilMask === value) {
  6981. return;
  6982. }
  6983. this._stencilMask = value;
  6984. this._isStencilMaskDirty = true;
  6985. },
  6986. enumerable: true,
  6987. configurable: true
  6988. });
  6989. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6990. get: function () {
  6991. return this._stencilTest;
  6992. },
  6993. set: function (value) {
  6994. if (this._stencilTest === value) {
  6995. return;
  6996. }
  6997. this._stencilTest = value;
  6998. this._isStencilTestDirty = true;
  6999. },
  7000. enumerable: true,
  7001. configurable: true
  7002. });
  7003. _StencilState.prototype.reset = function () {
  7004. this._stencilTest = false;
  7005. this._stencilMask = 0xFF;
  7006. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7007. this._stencilFuncRef = 1;
  7008. this._stencilFuncMask = 0xFF;
  7009. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7010. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7011. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7012. this._isStencilTestDirty = true;
  7013. this._isStencilMaskDirty = true;
  7014. this._isStencilFuncDirty = true;
  7015. this._isStencilOpDirty = true;
  7016. };
  7017. _StencilState.prototype.apply = function (gl) {
  7018. if (!this.isDirty) {
  7019. return;
  7020. }
  7021. // Stencil test
  7022. if (this._isStencilTestDirty) {
  7023. if (this.stencilTest) {
  7024. gl.enable(gl.STENCIL_TEST);
  7025. }
  7026. else {
  7027. gl.disable(gl.STENCIL_TEST);
  7028. }
  7029. this._isStencilTestDirty = false;
  7030. }
  7031. // Stencil mask
  7032. if (this._isStencilMaskDirty) {
  7033. gl.stencilMask(this.stencilMask);
  7034. this._isStencilMaskDirty = false;
  7035. }
  7036. // Stencil func
  7037. if (this._isStencilFuncDirty) {
  7038. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7039. this._isStencilFuncDirty = false;
  7040. }
  7041. // Stencil op
  7042. if (this._isStencilOpDirty) {
  7043. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7044. this._isStencilOpDirty = false;
  7045. }
  7046. };
  7047. return _StencilState;
  7048. }());
  7049. Internals._StencilState = _StencilState;
  7050. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7051. })(BABYLON || (BABYLON = {}));
  7052. //# sourceMappingURL=babylon.stencilState.js.map
  7053. var BABYLON;
  7054. (function (BABYLON) {
  7055. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7056. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7057. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7058. gl.compileShader(shader);
  7059. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7060. throw new Error(gl.getShaderInfoLog(shader));
  7061. }
  7062. return shader;
  7063. };
  7064. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7065. var magFilter = gl.NEAREST;
  7066. var minFilter = gl.NEAREST;
  7067. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7068. magFilter = gl.LINEAR;
  7069. if (generateMipMaps) {
  7070. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7071. }
  7072. else {
  7073. minFilter = gl.LINEAR;
  7074. }
  7075. }
  7076. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7077. magFilter = gl.LINEAR;
  7078. if (generateMipMaps) {
  7079. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7080. }
  7081. else {
  7082. minFilter = gl.LINEAR;
  7083. }
  7084. }
  7085. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7086. magFilter = gl.NEAREST;
  7087. if (generateMipMaps) {
  7088. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7089. }
  7090. else {
  7091. minFilter = gl.NEAREST;
  7092. }
  7093. }
  7094. return {
  7095. min: minFilter,
  7096. mag: magFilter
  7097. };
  7098. };
  7099. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7101. var engine = scene.getEngine();
  7102. if (!engine) {
  7103. return;
  7104. }
  7105. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7106. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7107. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7108. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7109. texture._baseWidth = width;
  7110. texture._baseHeight = height;
  7111. texture._width = potWidth;
  7112. texture._height = potHeight;
  7113. texture.isReady = true;
  7114. processFunction(potWidth, potHeight);
  7115. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7116. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7117. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7118. if (!noMipmap && !isCompressed) {
  7119. gl.generateMipmap(gl.TEXTURE_2D);
  7120. }
  7121. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7122. engine.resetTextureCache();
  7123. scene._removePendingData(texture);
  7124. texture.onLoadedCallbacks.forEach(function (callback) {
  7125. callback();
  7126. });
  7127. texture.onLoadedCallbacks = [];
  7128. };
  7129. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7130. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7131. var img;
  7132. var onload = function () {
  7133. loadedImages[index] = img;
  7134. loadedImages._internalCount++;
  7135. scene._removePendingData(img);
  7136. if (loadedImages._internalCount === 6) {
  7137. onfinish(loadedImages);
  7138. }
  7139. };
  7140. var onerror = function () {
  7141. scene._removePendingData(img);
  7142. if (onErrorCallBack) {
  7143. onErrorCallBack();
  7144. }
  7145. };
  7146. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7147. scene._addPendingData(img);
  7148. };
  7149. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7150. if (onError === void 0) { onError = null; }
  7151. var loadedImages = [];
  7152. loadedImages._internalCount = 0;
  7153. for (var index = 0; index < 6; index++) {
  7154. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7155. }
  7156. };
  7157. var InstancingAttributeInfo = (function () {
  7158. function InstancingAttributeInfo() {
  7159. }
  7160. return InstancingAttributeInfo;
  7161. }());
  7162. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7163. var EngineCapabilities = (function () {
  7164. function EngineCapabilities() {
  7165. }
  7166. return EngineCapabilities;
  7167. }());
  7168. BABYLON.EngineCapabilities = EngineCapabilities;
  7169. /**
  7170. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7171. */
  7172. var Engine = (function () {
  7173. /**
  7174. * @constructor
  7175. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7176. * @param {boolean} [antialias] - enable antialias
  7177. * @param options - further options to be sent to the getContext function
  7178. */
  7179. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7180. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7181. var _this = this;
  7182. // Public members
  7183. this.isFullscreen = false;
  7184. this.isPointerLock = false;
  7185. this.cullBackFaces = true;
  7186. this.renderEvenInBackground = true;
  7187. this.preventCacheWipeBetweenFrames = false;
  7188. // To enable/disable IDB support and avoid XHR on .manifest
  7189. this.enableOfflineSupport = BABYLON.Database;
  7190. this.scenes = new Array();
  7191. // Observables
  7192. /**
  7193. * Observable event triggered each time the rendering canvas is resized
  7194. */
  7195. this.onResizeObservable = new BABYLON.Observable();
  7196. /**
  7197. * Observable event triggered each time the canvas lost focus
  7198. */
  7199. this.onCanvasBlurObservable = new BABYLON.Observable();
  7200. this._windowIsBackground = false;
  7201. this._webGLVersion = 1.0;
  7202. this._badOS = false;
  7203. this._drawCalls = new BABYLON.PerfCounter();
  7204. this._renderingQueueLaunched = false;
  7205. this._activeRenderLoops = [];
  7206. // FPS
  7207. this.fpsRange = 60;
  7208. this.previousFramesDuration = [];
  7209. this.fps = 60;
  7210. this.deltaTime = 0;
  7211. // States
  7212. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7213. this._stencilState = new BABYLON.Internals._StencilState();
  7214. this._alphaState = new BABYLON.Internals._AlphaState();
  7215. this._alphaMode = Engine.ALPHA_DISABLE;
  7216. // Cache
  7217. this._loadedTexturesCache = new Array();
  7218. this._maxTextureChannels = 16;
  7219. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7220. this._compiledEffects = {};
  7221. this._vertexAttribArraysEnabled = [];
  7222. this._uintIndicesCurrentlySet = false;
  7223. this._currentBoundBuffer = new Array();
  7224. this._currentBufferPointers = [];
  7225. this._currentInstanceLocations = new Array();
  7226. this._currentInstanceBuffers = new Array();
  7227. this._vaoRecordInProgress = false;
  7228. this._mustWipeVertexAttributes = false;
  7229. // Hardware supported Compressed Textures
  7230. this._texturesSupported = new Array();
  7231. this._onVRFullScreenTriggered = function () {
  7232. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7233. //get the old size before we change
  7234. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7235. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7236. //get the width and height, change the render size
  7237. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7238. var width, height;
  7239. _this.setHardwareScalingLevel(1);
  7240. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7241. }
  7242. else {
  7243. //When the specs are implemented, need to uncomment this.
  7244. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7245. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7246. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7247. _this._vrDisplayEnabled = undefined;
  7248. }
  7249. };
  7250. this._renderingCanvas = canvas;
  7251. Engine.Instances.push(this);
  7252. options = options || {};
  7253. if (antialias != null) {
  7254. options.antialias = antialias;
  7255. }
  7256. if (options.preserveDrawingBuffer === undefined) {
  7257. options.preserveDrawingBuffer = false;
  7258. }
  7259. if (options.audioEngine === undefined) {
  7260. options.audioEngine = true;
  7261. }
  7262. if (options.stencil === undefined) {
  7263. options.stencil = true;
  7264. }
  7265. // GL
  7266. if (!options.disableWebGL2Support) {
  7267. try {
  7268. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7269. if (this._gl) {
  7270. this._webGLVersion = 2.0;
  7271. }
  7272. }
  7273. catch (e) {
  7274. // Do nothing
  7275. }
  7276. }
  7277. if (!this._gl) {
  7278. if (!canvas) {
  7279. throw new Error("The provided canvas is null or undefined.");
  7280. }
  7281. try {
  7282. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7283. }
  7284. catch (e) {
  7285. throw new Error("WebGL not supported");
  7286. }
  7287. }
  7288. if (!this._gl) {
  7289. throw new Error("WebGL not supported");
  7290. }
  7291. this._onBlur = function () {
  7292. _this._windowIsBackground = true;
  7293. };
  7294. this._onFocus = function () {
  7295. _this._windowIsBackground = false;
  7296. };
  7297. this._onCanvasBlur = function () {
  7298. _this.onCanvasBlurObservable.notifyObservers(_this);
  7299. };
  7300. window.addEventListener("blur", this._onBlur);
  7301. window.addEventListener("focus", this._onFocus);
  7302. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7303. // Viewport
  7304. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7305. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7306. this.resize();
  7307. // Caps
  7308. this._isStencilEnable = options.stencil;
  7309. this._caps = new EngineCapabilities();
  7310. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7311. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7312. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7313. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7314. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7315. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7316. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7317. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7318. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7319. // Infos
  7320. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7321. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7322. if (rendererInfo != null) {
  7323. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7324. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7325. }
  7326. if (!this._glVendor) {
  7327. this._glVendor = "Unknown vendor";
  7328. }
  7329. if (!this._glRenderer) {
  7330. this._glRenderer = "Unknown renderer";
  7331. }
  7332. // Constants
  7333. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  7334. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  7335. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  7336. // Extensions
  7337. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7338. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7339. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7340. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7341. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7342. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7343. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7344. 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');
  7345. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7346. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7347. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7348. this._caps.highPrecisionShaderSupported = true;
  7349. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7350. // Checks if some of the format renders first to allow the use of webgl inspector.
  7351. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7352. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7353. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7354. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7355. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7356. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7357. if (this._webGLVersion > 1) {
  7358. this._gl.HALF_FLOAT_OES = 0x140B;
  7359. }
  7360. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7361. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7362. // Vertex array object
  7363. if (this._webGLVersion > 1) {
  7364. this._caps.vertexArrayObject = true;
  7365. }
  7366. else {
  7367. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7368. if (vertexArrayObjectExtension != null) {
  7369. this._caps.vertexArrayObject = true;
  7370. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7371. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7372. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7373. }
  7374. else {
  7375. this._caps.vertexArrayObject = false;
  7376. }
  7377. }
  7378. // Instances count
  7379. if (this._webGLVersion > 1) {
  7380. this._caps.instancedArrays = true;
  7381. }
  7382. else {
  7383. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7384. if (instanceExtension != null) {
  7385. this._caps.instancedArrays = true;
  7386. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7387. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7388. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7389. }
  7390. else {
  7391. this._caps.instancedArrays = false;
  7392. }
  7393. }
  7394. // Intelligently add supported compressed formats in order to check for.
  7395. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7396. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7397. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7398. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7399. if (this._caps.astc)
  7400. this.texturesSupported.push('-astc.ktx');
  7401. if (this._caps.s3tc)
  7402. this.texturesSupported.push('-dxt.ktx');
  7403. if (this._caps.pvrtc)
  7404. this.texturesSupported.push('-pvrtc.ktx');
  7405. if (this._caps.etc2)
  7406. this.texturesSupported.push('-etc2.ktx');
  7407. if (this._caps.etc1)
  7408. this.texturesSupported.push('-etc1.ktx');
  7409. if (this._gl.getShaderPrecisionFormat) {
  7410. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7411. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7412. }
  7413. // Depth buffer
  7414. this.setDepthBuffer(true);
  7415. this.setDepthFunctionToLessOrEqual();
  7416. this.setDepthWrite(true);
  7417. // Fullscreen
  7418. this._onFullscreenChange = function () {
  7419. if (document.fullscreen !== undefined) {
  7420. _this.isFullscreen = document.fullscreen;
  7421. }
  7422. else if (document.mozFullScreen !== undefined) {
  7423. _this.isFullscreen = document.mozFullScreen;
  7424. }
  7425. else if (document.webkitIsFullScreen !== undefined) {
  7426. _this.isFullscreen = document.webkitIsFullScreen;
  7427. }
  7428. else if (document.msIsFullScreen !== undefined) {
  7429. _this.isFullscreen = document.msIsFullScreen;
  7430. }
  7431. // Pointer lock
  7432. if (_this.isFullscreen && _this._pointerLockRequested) {
  7433. canvas.requestPointerLock = canvas.requestPointerLock ||
  7434. canvas.msRequestPointerLock ||
  7435. canvas.mozRequestPointerLock ||
  7436. canvas.webkitRequestPointerLock;
  7437. if (canvas.requestPointerLock) {
  7438. canvas.requestPointerLock();
  7439. }
  7440. }
  7441. };
  7442. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7443. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7444. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7445. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7446. // Pointer lock
  7447. this._onPointerLockChange = function () {
  7448. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7449. document.webkitPointerLockElement === canvas ||
  7450. document.msPointerLockElement === canvas ||
  7451. document.pointerLockElement === canvas);
  7452. };
  7453. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7454. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7455. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7456. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7457. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7458. Engine.audioEngine = new BABYLON.AudioEngine();
  7459. }
  7460. //Load WebVR Devices
  7461. if (options.autoEnableWebVR) {
  7462. this.initWebVR();
  7463. }
  7464. //Detect if we are running on a faulty buggy OS.
  7465. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7466. //ua sniffing is the tool of the devil.
  7467. this._badOS = regexp.test(navigator.userAgent);
  7468. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7469. }
  7470. Object.defineProperty(Engine, "LastCreatedEngine", {
  7471. get: function () {
  7472. if (Engine.Instances.length === 0) {
  7473. return null;
  7474. }
  7475. return Engine.Instances[Engine.Instances.length - 1];
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(Engine, "LastCreatedScene", {
  7481. get: function () {
  7482. var lastCreatedEngine = Engine.LastCreatedEngine;
  7483. if (!lastCreatedEngine) {
  7484. return null;
  7485. }
  7486. if (lastCreatedEngine.scenes.length === 0) {
  7487. return null;
  7488. }
  7489. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. /**
  7495. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7496. */
  7497. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7498. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7499. var engine = Engine.Instances[engineIndex];
  7500. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7501. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7502. }
  7503. }
  7504. };
  7505. Object.defineProperty(Engine, "NEVER", {
  7506. get: function () {
  7507. return Engine._NEVER;
  7508. },
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512. Object.defineProperty(Engine, "ALWAYS", {
  7513. get: function () {
  7514. return Engine._ALWAYS;
  7515. },
  7516. enumerable: true,
  7517. configurable: true
  7518. });
  7519. Object.defineProperty(Engine, "LESS", {
  7520. get: function () {
  7521. return Engine._LESS;
  7522. },
  7523. enumerable: true,
  7524. configurable: true
  7525. });
  7526. Object.defineProperty(Engine, "EQUAL", {
  7527. get: function () {
  7528. return Engine._EQUAL;
  7529. },
  7530. enumerable: true,
  7531. configurable: true
  7532. });
  7533. Object.defineProperty(Engine, "LEQUAL", {
  7534. get: function () {
  7535. return Engine._LEQUAL;
  7536. },
  7537. enumerable: true,
  7538. configurable: true
  7539. });
  7540. Object.defineProperty(Engine, "GREATER", {
  7541. get: function () {
  7542. return Engine._GREATER;
  7543. },
  7544. enumerable: true,
  7545. configurable: true
  7546. });
  7547. Object.defineProperty(Engine, "GEQUAL", {
  7548. get: function () {
  7549. return Engine._GEQUAL;
  7550. },
  7551. enumerable: true,
  7552. configurable: true
  7553. });
  7554. Object.defineProperty(Engine, "NOTEQUAL", {
  7555. get: function () {
  7556. return Engine._NOTEQUAL;
  7557. },
  7558. enumerable: true,
  7559. configurable: true
  7560. });
  7561. Object.defineProperty(Engine, "KEEP", {
  7562. get: function () {
  7563. return Engine._KEEP;
  7564. },
  7565. enumerable: true,
  7566. configurable: true
  7567. });
  7568. Object.defineProperty(Engine, "REPLACE", {
  7569. get: function () {
  7570. return Engine._REPLACE;
  7571. },
  7572. enumerable: true,
  7573. configurable: true
  7574. });
  7575. Object.defineProperty(Engine, "INCR", {
  7576. get: function () {
  7577. return Engine._INCR;
  7578. },
  7579. enumerable: true,
  7580. configurable: true
  7581. });
  7582. Object.defineProperty(Engine, "DECR", {
  7583. get: function () {
  7584. return Engine._DECR;
  7585. },
  7586. enumerable: true,
  7587. configurable: true
  7588. });
  7589. Object.defineProperty(Engine, "INVERT", {
  7590. get: function () {
  7591. return Engine._INVERT;
  7592. },
  7593. enumerable: true,
  7594. configurable: true
  7595. });
  7596. Object.defineProperty(Engine, "INCR_WRAP", {
  7597. get: function () {
  7598. return Engine._INCR_WRAP;
  7599. },
  7600. enumerable: true,
  7601. configurable: true
  7602. });
  7603. Object.defineProperty(Engine, "DECR_WRAP", {
  7604. get: function () {
  7605. return Engine._DECR_WRAP;
  7606. },
  7607. enumerable: true,
  7608. configurable: true
  7609. });
  7610. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7611. get: function () {
  7612. return Engine._ALPHA_DISABLE;
  7613. },
  7614. enumerable: true,
  7615. configurable: true
  7616. });
  7617. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7618. get: function () {
  7619. return Engine._ALPHA_ONEONE;
  7620. },
  7621. enumerable: true,
  7622. configurable: true
  7623. });
  7624. Object.defineProperty(Engine, "ALPHA_ADD", {
  7625. get: function () {
  7626. return Engine._ALPHA_ADD;
  7627. },
  7628. enumerable: true,
  7629. configurable: true
  7630. });
  7631. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7632. get: function () {
  7633. return Engine._ALPHA_COMBINE;
  7634. },
  7635. enumerable: true,
  7636. configurable: true
  7637. });
  7638. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7639. get: function () {
  7640. return Engine._ALPHA_SUBTRACT;
  7641. },
  7642. enumerable: true,
  7643. configurable: true
  7644. });
  7645. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7646. get: function () {
  7647. return Engine._ALPHA_MULTIPLY;
  7648. },
  7649. enumerable: true,
  7650. configurable: true
  7651. });
  7652. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7653. get: function () {
  7654. return Engine._ALPHA_MAXIMIZED;
  7655. },
  7656. enumerable: true,
  7657. configurable: true
  7658. });
  7659. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7660. get: function () {
  7661. return Engine._ALPHA_PREMULTIPLIED;
  7662. },
  7663. enumerable: true,
  7664. configurable: true
  7665. });
  7666. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7667. get: function () {
  7668. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7669. },
  7670. enumerable: true,
  7671. configurable: true
  7672. });
  7673. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7674. get: function () {
  7675. return Engine._ALPHA_INTERPOLATE;
  7676. },
  7677. enumerable: true,
  7678. configurable: true
  7679. });
  7680. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7681. get: function () {
  7682. return Engine._ALPHA_SCREENMODE;
  7683. },
  7684. enumerable: true,
  7685. configurable: true
  7686. });
  7687. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7688. get: function () {
  7689. return Engine._DELAYLOADSTATE_NONE;
  7690. },
  7691. enumerable: true,
  7692. configurable: true
  7693. });
  7694. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7695. get: function () {
  7696. return Engine._DELAYLOADSTATE_LOADED;
  7697. },
  7698. enumerable: true,
  7699. configurable: true
  7700. });
  7701. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7702. get: function () {
  7703. return Engine._DELAYLOADSTATE_LOADING;
  7704. },
  7705. enumerable: true,
  7706. configurable: true
  7707. });
  7708. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7709. get: function () {
  7710. return Engine._DELAYLOADSTATE_NOTLOADED;
  7711. },
  7712. enumerable: true,
  7713. configurable: true
  7714. });
  7715. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7716. get: function () {
  7717. return Engine._TEXTUREFORMAT_ALPHA;
  7718. },
  7719. enumerable: true,
  7720. configurable: true
  7721. });
  7722. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7723. get: function () {
  7724. return Engine._TEXTUREFORMAT_LUMINANCE;
  7725. },
  7726. enumerable: true,
  7727. configurable: true
  7728. });
  7729. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7730. get: function () {
  7731. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7732. },
  7733. enumerable: true,
  7734. configurable: true
  7735. });
  7736. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7737. get: function () {
  7738. return Engine._TEXTUREFORMAT_RGB;
  7739. },
  7740. enumerable: true,
  7741. configurable: true
  7742. });
  7743. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7744. get: function () {
  7745. return Engine._TEXTUREFORMAT_RGBA;
  7746. },
  7747. enumerable: true,
  7748. configurable: true
  7749. });
  7750. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7751. get: function () {
  7752. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7753. },
  7754. enumerable: true,
  7755. configurable: true
  7756. });
  7757. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7758. get: function () {
  7759. return Engine._TEXTURETYPE_FLOAT;
  7760. },
  7761. enumerable: true,
  7762. configurable: true
  7763. });
  7764. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7765. get: function () {
  7766. return Engine._TEXTURETYPE_HALF_FLOAT;
  7767. },
  7768. enumerable: true,
  7769. configurable: true
  7770. });
  7771. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7772. get: function () {
  7773. return Engine._SCALEMODE_FLOOR;
  7774. },
  7775. enumerable: true,
  7776. configurable: true
  7777. });
  7778. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7779. get: function () {
  7780. return Engine._SCALEMODE_NEAREST;
  7781. },
  7782. enumerable: true,
  7783. configurable: true
  7784. });
  7785. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7786. get: function () {
  7787. return Engine._SCALEMODE_CEILING;
  7788. },
  7789. enumerable: true,
  7790. configurable: true
  7791. });
  7792. Object.defineProperty(Engine, "Version", {
  7793. get: function () {
  7794. return "3.0-rc";
  7795. },
  7796. enumerable: true,
  7797. configurable: true
  7798. });
  7799. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7800. get: function () {
  7801. return this._texturesSupported;
  7802. },
  7803. enumerable: true,
  7804. configurable: true
  7805. });
  7806. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7807. get: function () {
  7808. return this._textureFormatInUse;
  7809. },
  7810. enumerable: true,
  7811. configurable: true
  7812. });
  7813. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7814. // Empty texture
  7815. get: function () {
  7816. if (!this._emptyTexture) {
  7817. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7818. }
  7819. return this._emptyTexture;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7825. get: function () {
  7826. if (!this._emptyCubeTexture) {
  7827. var faceData = new Uint8Array(4);
  7828. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7829. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7830. }
  7831. return this._emptyCubeTexture;
  7832. },
  7833. enumerable: true,
  7834. configurable: true
  7835. });
  7836. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7837. get: function () {
  7838. return this._webGLVersion;
  7839. },
  7840. enumerable: true,
  7841. configurable: true
  7842. });
  7843. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7844. /**
  7845. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7846. */
  7847. get: function () {
  7848. return this._isStencilEnable;
  7849. },
  7850. enumerable: true,
  7851. configurable: true
  7852. });
  7853. Engine.prototype._prepareWorkingCanvas = function () {
  7854. if (this._workingCanvas) {
  7855. return;
  7856. }
  7857. this._workingCanvas = document.createElement("canvas");
  7858. this._workingContext = this._workingCanvas.getContext("2d");
  7859. };
  7860. Engine.prototype.resetTextureCache = function () {
  7861. for (var index = 0; index < this._maxTextureChannels; index++) {
  7862. this._activeTexturesCache[index] = null;
  7863. }
  7864. };
  7865. Engine.prototype.getGlInfo = function () {
  7866. return {
  7867. vendor: this._glVendor,
  7868. renderer: this._glRenderer,
  7869. version: this._glVersion
  7870. };
  7871. };
  7872. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7873. if (useScreen === void 0) { useScreen = false; }
  7874. var viewport = camera.viewport;
  7875. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7876. };
  7877. Engine.prototype.getRenderWidth = function (useScreen) {
  7878. if (useScreen === void 0) { useScreen = false; }
  7879. if (!useScreen && this._currentRenderTarget) {
  7880. return this._currentRenderTarget._width;
  7881. }
  7882. return this._renderingCanvas.width;
  7883. };
  7884. Engine.prototype.getRenderHeight = function (useScreen) {
  7885. if (useScreen === void 0) { useScreen = false; }
  7886. if (!useScreen && this._currentRenderTarget) {
  7887. return this._currentRenderTarget._height;
  7888. }
  7889. return this._renderingCanvas.height;
  7890. };
  7891. Engine.prototype.getRenderingCanvas = function () {
  7892. return this._renderingCanvas;
  7893. };
  7894. Engine.prototype.getRenderingCanvasClientRect = function () {
  7895. return this._renderingCanvas.getBoundingClientRect();
  7896. };
  7897. Engine.prototype.setHardwareScalingLevel = function (level) {
  7898. this._hardwareScalingLevel = level;
  7899. this.resize();
  7900. };
  7901. Engine.prototype.getHardwareScalingLevel = function () {
  7902. return this._hardwareScalingLevel;
  7903. };
  7904. Engine.prototype.getLoadedTexturesCache = function () {
  7905. return this._loadedTexturesCache;
  7906. };
  7907. Engine.prototype.getCaps = function () {
  7908. return this._caps;
  7909. };
  7910. Object.defineProperty(Engine.prototype, "drawCalls", {
  7911. get: function () {
  7912. return this._drawCalls.current;
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7918. get: function () {
  7919. return this._drawCalls;
  7920. },
  7921. enumerable: true,
  7922. configurable: true
  7923. });
  7924. Engine.prototype.getDepthFunction = function () {
  7925. return this._depthCullingState.depthFunc;
  7926. };
  7927. Engine.prototype.setDepthFunction = function (depthFunc) {
  7928. this._depthCullingState.depthFunc = depthFunc;
  7929. };
  7930. Engine.prototype.setDepthFunctionToGreater = function () {
  7931. this._depthCullingState.depthFunc = this._gl.GREATER;
  7932. };
  7933. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7934. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7935. };
  7936. Engine.prototype.setDepthFunctionToLess = function () {
  7937. this._depthCullingState.depthFunc = this._gl.LESS;
  7938. };
  7939. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7940. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7941. };
  7942. Engine.prototype.getStencilBuffer = function () {
  7943. return this._stencilState.stencilTest;
  7944. };
  7945. Engine.prototype.setStencilBuffer = function (enable) {
  7946. this._stencilState.stencilTest = enable;
  7947. };
  7948. Engine.prototype.getStencilMask = function () {
  7949. return this._stencilState.stencilMask;
  7950. };
  7951. Engine.prototype.setStencilMask = function (mask) {
  7952. this._stencilState.stencilMask = mask;
  7953. };
  7954. Engine.prototype.getStencilFunction = function () {
  7955. return this._stencilState.stencilFunc;
  7956. };
  7957. Engine.prototype.getStencilFunctionReference = function () {
  7958. return this._stencilState.stencilFuncRef;
  7959. };
  7960. Engine.prototype.getStencilFunctionMask = function () {
  7961. return this._stencilState.stencilFuncMask;
  7962. };
  7963. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7964. this._stencilState.stencilFunc = stencilFunc;
  7965. };
  7966. Engine.prototype.setStencilFunctionReference = function (reference) {
  7967. this._stencilState.stencilFuncRef = reference;
  7968. };
  7969. Engine.prototype.setStencilFunctionMask = function (mask) {
  7970. this._stencilState.stencilFuncMask = mask;
  7971. };
  7972. Engine.prototype.getStencilOperationFail = function () {
  7973. return this._stencilState.stencilOpStencilFail;
  7974. };
  7975. Engine.prototype.getStencilOperationDepthFail = function () {
  7976. return this._stencilState.stencilOpDepthFail;
  7977. };
  7978. Engine.prototype.getStencilOperationPass = function () {
  7979. return this._stencilState.stencilOpStencilDepthPass;
  7980. };
  7981. Engine.prototype.setStencilOperationFail = function (operation) {
  7982. this._stencilState.stencilOpStencilFail = operation;
  7983. };
  7984. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7985. this._stencilState.stencilOpDepthFail = operation;
  7986. };
  7987. Engine.prototype.setStencilOperationPass = function (operation) {
  7988. this._stencilState.stencilOpStencilDepthPass = operation;
  7989. };
  7990. Engine.prototype.setDitheringState = function (value) {
  7991. if (value) {
  7992. this._gl.enable(this._gl.DITHER);
  7993. }
  7994. else {
  7995. this._gl.disable(this._gl.DITHER);
  7996. }
  7997. };
  7998. /**
  7999. * stop executing a render loop function and remove it from the execution array
  8000. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8001. */
  8002. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8003. if (!renderFunction) {
  8004. this._activeRenderLoops = [];
  8005. return;
  8006. }
  8007. var index = this._activeRenderLoops.indexOf(renderFunction);
  8008. if (index >= 0) {
  8009. this._activeRenderLoops.splice(index, 1);
  8010. }
  8011. };
  8012. Engine.prototype._renderLoop = function () {
  8013. var shouldRender = true;
  8014. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8015. shouldRender = false;
  8016. }
  8017. if (shouldRender) {
  8018. // Start new frame
  8019. this.beginFrame();
  8020. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8021. var renderFunction = this._activeRenderLoops[index];
  8022. renderFunction();
  8023. }
  8024. // Present
  8025. this.endFrame();
  8026. }
  8027. if (this._activeRenderLoops.length > 0) {
  8028. // Register new frame
  8029. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8030. }
  8031. else {
  8032. this._renderingQueueLaunched = false;
  8033. }
  8034. };
  8035. /**
  8036. * Register and execute a render loop. The engine can have more than one render function.
  8037. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8038. * @example
  8039. * engine.runRenderLoop(function () {
  8040. * scene.render()
  8041. * })
  8042. */
  8043. Engine.prototype.runRenderLoop = function (renderFunction) {
  8044. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8045. return;
  8046. }
  8047. this._activeRenderLoops.push(renderFunction);
  8048. if (!this._renderingQueueLaunched) {
  8049. this._renderingQueueLaunched = true;
  8050. this._bindedRenderFunction = this._renderLoop.bind(this);
  8051. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8052. }
  8053. };
  8054. /**
  8055. * Toggle full screen mode.
  8056. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8057. * @param {any} options - an options object to be sent to the requestFullscreen function
  8058. */
  8059. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8060. if (this.isFullscreen) {
  8061. BABYLON.Tools.ExitFullscreen();
  8062. }
  8063. else {
  8064. this._pointerLockRequested = requestPointerLock;
  8065. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8066. }
  8067. };
  8068. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8069. if (stencil === void 0) { stencil = false; }
  8070. this.applyStates();
  8071. var mode = 0;
  8072. if (backBuffer && color) {
  8073. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8074. mode |= this._gl.COLOR_BUFFER_BIT;
  8075. }
  8076. if (depth) {
  8077. this._gl.clearDepth(1.0);
  8078. mode |= this._gl.DEPTH_BUFFER_BIT;
  8079. }
  8080. if (stencil) {
  8081. this._gl.clearStencil(0);
  8082. mode |= this._gl.STENCIL_BUFFER_BIT;
  8083. }
  8084. this._gl.clear(mode);
  8085. };
  8086. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8087. var gl = this._gl;
  8088. // Save state
  8089. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8090. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8091. // Change state
  8092. gl.enable(gl.SCISSOR_TEST);
  8093. gl.scissor(x, y, width, height);
  8094. // Clear
  8095. this.clear(clearColor, true, true, true);
  8096. // Restore state
  8097. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8098. if (curScissor === true) {
  8099. gl.enable(gl.SCISSOR_TEST);
  8100. }
  8101. else {
  8102. gl.disable(gl.SCISSOR_TEST);
  8103. }
  8104. };
  8105. /**
  8106. * Set the WebGL's viewport
  8107. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8108. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8109. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8110. */
  8111. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8112. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8113. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8114. var x = viewport.x || 0;
  8115. var y = viewport.y || 0;
  8116. this._cachedViewport = viewport;
  8117. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8118. };
  8119. /**
  8120. * Directly set the WebGL Viewport
  8121. * The x, y, width & height are directly passed to the WebGL call
  8122. * @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.
  8123. */
  8124. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8125. var currentViewport = this._cachedViewport;
  8126. this._cachedViewport = null;
  8127. this._gl.viewport(x, y, width, height);
  8128. return currentViewport;
  8129. };
  8130. Engine.prototype.beginFrame = function () {
  8131. this._measureFps();
  8132. };
  8133. Engine.prototype.endFrame = function () {
  8134. //force a flush in case we are using a bad OS.
  8135. if (this._badOS) {
  8136. this.flushFramebuffer();
  8137. }
  8138. //submit frame to the vr device, if enabled
  8139. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8140. this._vrDisplayEnabled.submitFrame();
  8141. }
  8142. };
  8143. /**
  8144. * resize the view according to the canvas' size.
  8145. * @example
  8146. * window.addEventListener("resize", function () {
  8147. * engine.resize();
  8148. * });
  8149. */
  8150. Engine.prototype.resize = function () {
  8151. // We're not resizing the size of the canvas while in VR mode & presenting
  8152. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8153. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8154. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8155. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8156. }
  8157. };
  8158. /**
  8159. * force a specific size of the canvas
  8160. * @param {number} width - the new canvas' width
  8161. * @param {number} height - the new canvas' height
  8162. */
  8163. Engine.prototype.setSize = function (width, height) {
  8164. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8165. return;
  8166. }
  8167. this._renderingCanvas.width = width;
  8168. this._renderingCanvas.height = height;
  8169. for (var index = 0; index < this.scenes.length; index++) {
  8170. var scene = this.scenes[index];
  8171. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8172. var cam = scene.cameras[camIndex];
  8173. cam._currentRenderId = 0;
  8174. }
  8175. }
  8176. if (this.onResizeObservable.hasObservers) {
  8177. this.onResizeObservable.notifyObservers(this);
  8178. }
  8179. };
  8180. //WebVR functions
  8181. Engine.prototype.isVRDevicePresent = function (callback) {
  8182. this.getVRDevice(null, function (device) {
  8183. callback(device !== null);
  8184. });
  8185. };
  8186. Engine.prototype.getVRDevice = function (name, callback) {
  8187. if (!this.vrDisplaysPromise) {
  8188. callback(null);
  8189. return;
  8190. }
  8191. this.vrDisplaysPromise.then(function (devices) {
  8192. if (devices.length > 0) {
  8193. if (name) {
  8194. var found = devices.some(function (device) {
  8195. if (device.displayName === name) {
  8196. callback(device);
  8197. return true;
  8198. }
  8199. else {
  8200. return false;
  8201. }
  8202. });
  8203. if (!found) {
  8204. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8205. callback(devices[0]);
  8206. }
  8207. }
  8208. else {
  8209. //choose the first one
  8210. callback(devices[0]);
  8211. }
  8212. }
  8213. else {
  8214. BABYLON.Tools.Error("No WebVR devices found!");
  8215. callback(null);
  8216. }
  8217. });
  8218. };
  8219. Engine.prototype.initWebVR = function () {
  8220. if (!this.vrDisplaysPromise) {
  8221. this._getVRDisplays();
  8222. }
  8223. };
  8224. Engine.prototype.enableVR = function (vrDevice) {
  8225. this._vrDisplayEnabled = vrDevice;
  8226. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8227. };
  8228. Engine.prototype.disableVR = function () {
  8229. if (this._vrDisplayEnabled) {
  8230. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8231. }
  8232. };
  8233. Engine.prototype._getVRDisplays = function () {
  8234. var _this = this;
  8235. var getWebVRDevices = function (devices) {
  8236. var size = devices.length;
  8237. var i = 0;
  8238. _this._vrDisplays = devices.filter(function (device) {
  8239. return devices[i] instanceof VRDisplay;
  8240. });
  8241. return _this._vrDisplays;
  8242. };
  8243. //using a key due to typescript
  8244. if (navigator.getVRDisplays) {
  8245. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8246. }
  8247. };
  8248. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8249. this._currentRenderTarget = texture;
  8250. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8251. var gl = this._gl;
  8252. if (texture.isCube) {
  8253. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8254. }
  8255. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8256. this.wipeCaches();
  8257. };
  8258. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8259. if (this._currentFramebuffer !== framebuffer) {
  8260. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8261. this._currentFramebuffer = framebuffer;
  8262. }
  8263. };
  8264. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8265. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8266. this._currentRenderTarget = null;
  8267. // If MSAA, we need to bitblt back to main texture
  8268. var gl = this._gl;
  8269. if (texture._MSAAFramebuffer) {
  8270. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8271. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8272. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8273. }
  8274. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8275. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8276. gl.generateMipmap(gl.TEXTURE_2D);
  8277. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8278. }
  8279. if (onBeforeUnbind) {
  8280. if (texture._MSAAFramebuffer) {
  8281. // Bind the correct framebuffer
  8282. this.bindUnboundFramebuffer(texture._framebuffer);
  8283. }
  8284. onBeforeUnbind();
  8285. }
  8286. this.bindUnboundFramebuffer(null);
  8287. };
  8288. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8289. if (texture.generateMipMaps) {
  8290. var gl = this._gl;
  8291. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8292. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8293. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8294. }
  8295. };
  8296. Engine.prototype.flushFramebuffer = function () {
  8297. this._gl.flush();
  8298. };
  8299. Engine.prototype.restoreDefaultFramebuffer = function () {
  8300. this._currentRenderTarget = null;
  8301. this.bindUnboundFramebuffer(null);
  8302. if (this._cachedViewport) {
  8303. this.setViewport(this._cachedViewport);
  8304. }
  8305. this.wipeCaches();
  8306. };
  8307. // UBOs
  8308. Engine.prototype.createUniformBuffer = function (elements) {
  8309. var ubo = this._gl.createBuffer();
  8310. this.bindUniformBuffer(ubo);
  8311. if (elements instanceof Float32Array) {
  8312. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8313. }
  8314. else {
  8315. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8316. }
  8317. this.bindUniformBuffer(null);
  8318. ubo.references = 1;
  8319. return ubo;
  8320. };
  8321. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8322. var ubo = this._gl.createBuffer();
  8323. this.bindUniformBuffer(ubo);
  8324. if (elements instanceof Float32Array) {
  8325. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8326. }
  8327. else {
  8328. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8329. }
  8330. this.bindUniformBuffer(null);
  8331. ubo.references = 1;
  8332. return ubo;
  8333. };
  8334. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8335. this.bindUniformBuffer(uniformBuffer);
  8336. if (offset === undefined) {
  8337. offset = 0;
  8338. }
  8339. if (count === undefined) {
  8340. if (elements instanceof Float32Array) {
  8341. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8342. }
  8343. else {
  8344. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8345. }
  8346. }
  8347. else {
  8348. if (elements instanceof Float32Array) {
  8349. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8350. }
  8351. else {
  8352. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8353. }
  8354. }
  8355. this.bindUniformBuffer(null);
  8356. };
  8357. // VBOs
  8358. Engine.prototype._resetVertexBufferBinding = function () {
  8359. this.bindArrayBuffer(null);
  8360. this._cachedVertexBuffers = null;
  8361. };
  8362. Engine.prototype.createVertexBuffer = function (vertices) {
  8363. var vbo = this._gl.createBuffer();
  8364. this.bindArrayBuffer(vbo);
  8365. if (vertices instanceof Float32Array) {
  8366. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8367. }
  8368. else {
  8369. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8370. }
  8371. this._resetVertexBufferBinding();
  8372. vbo.references = 1;
  8373. return vbo;
  8374. };
  8375. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8376. var vbo = this._gl.createBuffer();
  8377. this.bindArrayBuffer(vbo);
  8378. if (vertices instanceof Float32Array) {
  8379. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8380. }
  8381. else {
  8382. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8383. }
  8384. this._resetVertexBufferBinding();
  8385. vbo.references = 1;
  8386. return vbo;
  8387. };
  8388. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8389. this.bindArrayBuffer(vertexBuffer);
  8390. if (offset === undefined) {
  8391. offset = 0;
  8392. }
  8393. if (count === undefined) {
  8394. if (vertices instanceof Float32Array) {
  8395. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8396. }
  8397. else {
  8398. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8399. }
  8400. }
  8401. else {
  8402. if (vertices instanceof Float32Array) {
  8403. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8404. }
  8405. else {
  8406. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8407. }
  8408. }
  8409. this._resetVertexBufferBinding();
  8410. };
  8411. Engine.prototype._resetIndexBufferBinding = function () {
  8412. this.bindIndexBuffer(null);
  8413. this._cachedIndexBuffer = null;
  8414. };
  8415. Engine.prototype.createIndexBuffer = function (indices) {
  8416. var vbo = this._gl.createBuffer();
  8417. this.bindIndexBuffer(vbo);
  8418. // Check for 32 bits indices
  8419. var arrayBuffer;
  8420. var need32Bits = false;
  8421. if (indices instanceof Uint16Array) {
  8422. arrayBuffer = indices;
  8423. }
  8424. else {
  8425. //check 32 bit support
  8426. if (this._caps.uintIndices) {
  8427. if (indices instanceof Uint32Array) {
  8428. arrayBuffer = indices;
  8429. need32Bits = true;
  8430. }
  8431. else {
  8432. //number[] or Int32Array, check if 32 bit is necessary
  8433. for (var index = 0; index < indices.length; index++) {
  8434. if (indices[index] > 65535) {
  8435. need32Bits = true;
  8436. break;
  8437. }
  8438. }
  8439. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8440. }
  8441. }
  8442. else {
  8443. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8444. arrayBuffer = new Uint16Array(indices);
  8445. }
  8446. }
  8447. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8448. this._resetIndexBufferBinding();
  8449. vbo.references = 1;
  8450. vbo.is32Bits = need32Bits;
  8451. return vbo;
  8452. };
  8453. Engine.prototype.bindArrayBuffer = function (buffer) {
  8454. if (!this._vaoRecordInProgress) {
  8455. this._unBindVertexArrayObject();
  8456. }
  8457. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8458. };
  8459. Engine.prototype.bindUniformBuffer = function (buffer) {
  8460. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8461. };
  8462. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8463. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8464. };
  8465. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8466. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8467. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8468. };
  8469. ;
  8470. Engine.prototype.bindIndexBuffer = function (buffer) {
  8471. if (!this._vaoRecordInProgress) {
  8472. this._unBindVertexArrayObject();
  8473. }
  8474. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8475. };
  8476. Engine.prototype.bindBuffer = function (buffer, target) {
  8477. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8478. this._gl.bindBuffer(target, buffer);
  8479. this._currentBoundBuffer[target] = buffer;
  8480. }
  8481. };
  8482. Engine.prototype.updateArrayBuffer = function (data) {
  8483. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8484. };
  8485. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8486. var pointer = this._currentBufferPointers[indx];
  8487. var changed = false;
  8488. if (!pointer) {
  8489. changed = true;
  8490. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8491. }
  8492. else {
  8493. if (pointer.buffer !== buffer) {
  8494. pointer.buffer = buffer;
  8495. changed = true;
  8496. }
  8497. if (pointer.size !== size) {
  8498. pointer.size = size;
  8499. changed = true;
  8500. }
  8501. if (pointer.type !== type) {
  8502. pointer.type = type;
  8503. changed = true;
  8504. }
  8505. if (pointer.normalized !== normalized) {
  8506. pointer.normalized = normalized;
  8507. changed = true;
  8508. }
  8509. if (pointer.stride !== stride) {
  8510. pointer.stride = stride;
  8511. changed = true;
  8512. }
  8513. if (pointer.offset !== offset) {
  8514. pointer.offset = offset;
  8515. changed = true;
  8516. }
  8517. }
  8518. if (changed || this._vaoRecordInProgress) {
  8519. this.bindArrayBuffer(buffer);
  8520. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8521. }
  8522. };
  8523. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8524. if (indexBuffer == null) {
  8525. return;
  8526. }
  8527. if (this._cachedIndexBuffer !== indexBuffer) {
  8528. this._cachedIndexBuffer = indexBuffer;
  8529. this.bindIndexBuffer(indexBuffer);
  8530. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8531. }
  8532. };
  8533. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8534. var attributes = effect.getAttributesNames();
  8535. if (!this._vaoRecordInProgress) {
  8536. this._unBindVertexArrayObject();
  8537. }
  8538. this.unbindAllAttributes();
  8539. for (var index = 0; index < attributes.length; index++) {
  8540. var order = effect.getAttributeLocation(index);
  8541. if (order >= 0) {
  8542. var vertexBuffer = vertexBuffers[attributes[index]];
  8543. if (!vertexBuffer) {
  8544. continue;
  8545. }
  8546. this._gl.enableVertexAttribArray(order);
  8547. if (!this._vaoRecordInProgress) {
  8548. this._vertexAttribArraysEnabled[order] = true;
  8549. }
  8550. var buffer = vertexBuffer.getBuffer();
  8551. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8552. if (vertexBuffer.getIsInstanced()) {
  8553. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8554. if (!this._vaoRecordInProgress) {
  8555. this._currentInstanceLocations.push(order);
  8556. this._currentInstanceBuffers.push(buffer);
  8557. }
  8558. }
  8559. }
  8560. }
  8561. };
  8562. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8563. var vao = this._gl.createVertexArray();
  8564. this._vaoRecordInProgress = true;
  8565. this._gl.bindVertexArray(vao);
  8566. this._mustWipeVertexAttributes = true;
  8567. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8568. this.bindIndexBuffer(indexBuffer);
  8569. this._vaoRecordInProgress = false;
  8570. this._gl.bindVertexArray(null);
  8571. return vao;
  8572. };
  8573. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8574. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8575. this._cachedVertexArrayObject = vertexArrayObject;
  8576. this._gl.bindVertexArray(vertexArrayObject);
  8577. this._cachedVertexBuffers = null;
  8578. this._cachedIndexBuffer = null;
  8579. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8580. this._mustWipeVertexAttributes = true;
  8581. }
  8582. };
  8583. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8584. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8585. this._cachedVertexBuffers = vertexBuffer;
  8586. this._cachedEffectForVertexBuffers = effect;
  8587. var attributesCount = effect.getAttributesCount();
  8588. this._unBindVertexArrayObject();
  8589. this.unbindAllAttributes();
  8590. var offset = 0;
  8591. for (var index = 0; index < attributesCount; index++) {
  8592. if (index < vertexDeclaration.length) {
  8593. var order = effect.getAttributeLocation(index);
  8594. if (order >= 0) {
  8595. this._gl.enableVertexAttribArray(order);
  8596. this._vertexAttribArraysEnabled[order] = true;
  8597. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8598. }
  8599. offset += vertexDeclaration[index] * 4;
  8600. }
  8601. }
  8602. }
  8603. this._bindIndexBufferWithCache(indexBuffer);
  8604. };
  8605. Engine.prototype._unBindVertexArrayObject = function () {
  8606. if (!this._cachedVertexArrayObject) {
  8607. return;
  8608. }
  8609. this._cachedVertexArrayObject = null;
  8610. this._gl.bindVertexArray(null);
  8611. };
  8612. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8613. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8614. this._cachedVertexBuffers = vertexBuffers;
  8615. this._cachedEffectForVertexBuffers = effect;
  8616. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8617. }
  8618. this._bindIndexBufferWithCache(indexBuffer);
  8619. };
  8620. Engine.prototype.unbindInstanceAttributes = function () {
  8621. var boundBuffer;
  8622. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8623. var instancesBuffer = this._currentInstanceBuffers[i];
  8624. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8625. boundBuffer = instancesBuffer;
  8626. this.bindArrayBuffer(instancesBuffer);
  8627. }
  8628. var offsetLocation = this._currentInstanceLocations[i];
  8629. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8630. }
  8631. this._currentInstanceBuffers.length = 0;
  8632. this._currentInstanceLocations.length = 0;
  8633. };
  8634. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8635. this._gl.deleteVertexArray(vao);
  8636. };
  8637. Engine.prototype._releaseBuffer = function (buffer) {
  8638. buffer.references--;
  8639. if (buffer.references === 0) {
  8640. this._gl.deleteBuffer(buffer);
  8641. return true;
  8642. }
  8643. return false;
  8644. };
  8645. Engine.prototype.createInstancesBuffer = function (capacity) {
  8646. var buffer = this._gl.createBuffer();
  8647. buffer.capacity = capacity;
  8648. this.bindArrayBuffer(buffer);
  8649. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8650. return buffer;
  8651. };
  8652. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8653. this._gl.deleteBuffer(buffer);
  8654. };
  8655. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8656. this.bindArrayBuffer(instancesBuffer);
  8657. if (data) {
  8658. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8659. }
  8660. if (offsetLocations[0].index !== undefined) {
  8661. var stride = 0;
  8662. for (var i = 0; i < offsetLocations.length; i++) {
  8663. var ai = offsetLocations[i];
  8664. stride += ai.attributeSize * 4;
  8665. }
  8666. for (var i = 0; i < offsetLocations.length; i++) {
  8667. var ai = offsetLocations[i];
  8668. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8669. this._gl.enableVertexAttribArray(ai.index);
  8670. this._vertexAttribArraysEnabled[ai.index] = true;
  8671. }
  8672. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8673. this._gl.vertexAttribDivisor(ai.index, 1);
  8674. this._currentInstanceLocations.push(ai.index);
  8675. this._currentInstanceBuffers.push(instancesBuffer);
  8676. }
  8677. }
  8678. else {
  8679. for (var index = 0; index < 4; index++) {
  8680. var offsetLocation = offsetLocations[index];
  8681. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8682. this._gl.enableVertexAttribArray(offsetLocation);
  8683. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8684. }
  8685. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8686. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8687. this._currentInstanceLocations.push(offsetLocation);
  8688. this._currentInstanceBuffers.push(instancesBuffer);
  8689. }
  8690. }
  8691. };
  8692. Engine.prototype.applyStates = function () {
  8693. this._depthCullingState.apply(this._gl);
  8694. this._stencilState.apply(this._gl);
  8695. this._alphaState.apply(this._gl);
  8696. };
  8697. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8698. // Apply states
  8699. this.applyStates();
  8700. this._drawCalls.addCount(1, false);
  8701. // Render
  8702. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8703. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8704. if (instancesCount) {
  8705. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8706. return;
  8707. }
  8708. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8709. };
  8710. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8711. // Apply states
  8712. this.applyStates();
  8713. this._drawCalls.addCount(1, false);
  8714. if (instancesCount) {
  8715. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8716. return;
  8717. }
  8718. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8719. };
  8720. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8721. // Apply states
  8722. this.applyStates();
  8723. this._drawCalls.addCount(1, false);
  8724. if (instancesCount) {
  8725. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8726. return;
  8727. }
  8728. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8729. };
  8730. // Shaders
  8731. Engine.prototype._releaseEffect = function (effect) {
  8732. if (this._compiledEffects[effect._key]) {
  8733. delete this._compiledEffects[effect._key];
  8734. if (effect.getProgram()) {
  8735. this._gl.deleteProgram(effect.getProgram());
  8736. }
  8737. }
  8738. };
  8739. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8740. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8741. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8742. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8743. if (this._compiledEffects[name]) {
  8744. var compiledEffect = this._compiledEffects[name];
  8745. if (onCompiled && compiledEffect.isReady()) {
  8746. onCompiled(compiledEffect);
  8747. }
  8748. return compiledEffect;
  8749. }
  8750. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8751. effect._key = name;
  8752. this._compiledEffects[name] = effect;
  8753. return effect;
  8754. };
  8755. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8756. if (uniformsNames === void 0) { uniformsNames = []; }
  8757. if (samplers === void 0) { samplers = []; }
  8758. if (defines === void 0) { defines = ""; }
  8759. return this.createEffect({
  8760. vertex: "particles",
  8761. fragmentElement: fragmentName
  8762. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8763. };
  8764. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8765. context = context || this._gl;
  8766. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8767. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8768. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8769. var shaderProgram = context.createProgram();
  8770. context.attachShader(shaderProgram, vertexShader);
  8771. context.attachShader(shaderProgram, fragmentShader);
  8772. context.linkProgram(shaderProgram);
  8773. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8774. if (!linked) {
  8775. var error = context.getProgramInfoLog(shaderProgram);
  8776. if (error) {
  8777. throw new Error(error);
  8778. }
  8779. }
  8780. context.deleteShader(vertexShader);
  8781. context.deleteShader(fragmentShader);
  8782. return shaderProgram;
  8783. };
  8784. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8785. var results = [];
  8786. for (var index = 0; index < uniformsNames.length; index++) {
  8787. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8788. }
  8789. return results;
  8790. };
  8791. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8792. var results = [];
  8793. for (var index = 0; index < attributesNames.length; index++) {
  8794. try {
  8795. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8796. }
  8797. catch (e) {
  8798. results.push(-1);
  8799. }
  8800. }
  8801. return results;
  8802. };
  8803. Engine.prototype.enableEffect = function (effect) {
  8804. // Use program
  8805. this.setProgram(effect.getProgram());
  8806. this._currentEffect = effect;
  8807. if (effect.onBind) {
  8808. effect.onBind(effect);
  8809. }
  8810. effect.onBindObservable.notifyObservers(effect);
  8811. };
  8812. Engine.prototype.setIntArray = function (uniform, array) {
  8813. if (!uniform)
  8814. return;
  8815. this._gl.uniform1iv(uniform, array);
  8816. };
  8817. Engine.prototype.setIntArray2 = function (uniform, array) {
  8818. if (!uniform || array.length % 2 !== 0)
  8819. return;
  8820. this._gl.uniform2iv(uniform, array);
  8821. };
  8822. Engine.prototype.setIntArray3 = function (uniform, array) {
  8823. if (!uniform || array.length % 3 !== 0)
  8824. return;
  8825. this._gl.uniform3iv(uniform, array);
  8826. };
  8827. Engine.prototype.setIntArray4 = function (uniform, array) {
  8828. if (!uniform || array.length % 4 !== 0)
  8829. return;
  8830. this._gl.uniform4iv(uniform, array);
  8831. };
  8832. Engine.prototype.setFloatArray = function (uniform, array) {
  8833. if (!uniform)
  8834. return;
  8835. this._gl.uniform1fv(uniform, array);
  8836. };
  8837. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8838. if (!uniform || array.length % 2 !== 0)
  8839. return;
  8840. this._gl.uniform2fv(uniform, array);
  8841. };
  8842. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8843. if (!uniform || array.length % 3 !== 0)
  8844. return;
  8845. this._gl.uniform3fv(uniform, array);
  8846. };
  8847. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8848. if (!uniform || array.length % 4 !== 0)
  8849. return;
  8850. this._gl.uniform4fv(uniform, array);
  8851. };
  8852. Engine.prototype.setArray = function (uniform, array) {
  8853. if (!uniform)
  8854. return;
  8855. this._gl.uniform1fv(uniform, array);
  8856. };
  8857. Engine.prototype.setArray2 = function (uniform, array) {
  8858. if (!uniform || array.length % 2 !== 0)
  8859. return;
  8860. this._gl.uniform2fv(uniform, array);
  8861. };
  8862. Engine.prototype.setArray3 = function (uniform, array) {
  8863. if (!uniform || array.length % 3 !== 0)
  8864. return;
  8865. this._gl.uniform3fv(uniform, array);
  8866. };
  8867. Engine.prototype.setArray4 = function (uniform, array) {
  8868. if (!uniform || array.length % 4 !== 0)
  8869. return;
  8870. this._gl.uniform4fv(uniform, array);
  8871. };
  8872. Engine.prototype.setMatrices = function (uniform, matrices) {
  8873. if (!uniform)
  8874. return;
  8875. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8876. };
  8877. Engine.prototype.setMatrix = function (uniform, matrix) {
  8878. if (!uniform)
  8879. return;
  8880. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8881. };
  8882. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8883. if (!uniform)
  8884. return;
  8885. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8886. };
  8887. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8888. if (!uniform)
  8889. return;
  8890. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8891. };
  8892. Engine.prototype.setFloat = function (uniform, value) {
  8893. if (!uniform)
  8894. return;
  8895. this._gl.uniform1f(uniform, value);
  8896. };
  8897. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8898. if (!uniform)
  8899. return;
  8900. this._gl.uniform2f(uniform, x, y);
  8901. };
  8902. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8903. if (!uniform)
  8904. return;
  8905. this._gl.uniform3f(uniform, x, y, z);
  8906. };
  8907. Engine.prototype.setBool = function (uniform, bool) {
  8908. if (!uniform)
  8909. return;
  8910. this._gl.uniform1i(uniform, bool);
  8911. };
  8912. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8913. if (!uniform)
  8914. return;
  8915. this._gl.uniform4f(uniform, x, y, z, w);
  8916. };
  8917. Engine.prototype.setColor3 = function (uniform, color3) {
  8918. if (!uniform)
  8919. return;
  8920. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8921. };
  8922. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8923. if (!uniform)
  8924. return;
  8925. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8926. };
  8927. // States
  8928. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8929. if (zOffset === void 0) { zOffset = 0; }
  8930. if (reverseSide === void 0) { reverseSide = false; }
  8931. // Culling
  8932. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8933. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8934. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8935. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8936. if (culling) {
  8937. this._depthCullingState.cullFace = cullFace;
  8938. this._depthCullingState.cull = true;
  8939. }
  8940. else {
  8941. this._depthCullingState.cull = false;
  8942. }
  8943. }
  8944. // Z offset
  8945. this.setZOffset(zOffset);
  8946. };
  8947. Engine.prototype.setZOffset = function (value) {
  8948. this._depthCullingState.zOffset = value;
  8949. };
  8950. Engine.prototype.getZOffset = function () {
  8951. return this._depthCullingState.zOffset;
  8952. };
  8953. Engine.prototype.setDepthBuffer = function (enable) {
  8954. this._depthCullingState.depthTest = enable;
  8955. };
  8956. Engine.prototype.getDepthWrite = function () {
  8957. return this._depthCullingState.depthMask;
  8958. };
  8959. Engine.prototype.setDepthWrite = function (enable) {
  8960. this._depthCullingState.depthMask = enable;
  8961. };
  8962. Engine.prototype.setColorWrite = function (enable) {
  8963. this._gl.colorMask(enable, enable, enable, enable);
  8964. };
  8965. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8966. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8967. };
  8968. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8969. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8970. if (this._alphaMode === mode) {
  8971. return;
  8972. }
  8973. switch (mode) {
  8974. case Engine.ALPHA_DISABLE:
  8975. this._alphaState.alphaBlend = false;
  8976. break;
  8977. case Engine.ALPHA_PREMULTIPLIED:
  8978. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8979. this._alphaState.alphaBlend = true;
  8980. break;
  8981. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8982. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8983. this._alphaState.alphaBlend = true;
  8984. break;
  8985. case Engine.ALPHA_COMBINE:
  8986. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8987. this._alphaState.alphaBlend = true;
  8988. break;
  8989. case Engine.ALPHA_ONEONE:
  8990. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8991. this._alphaState.alphaBlend = true;
  8992. break;
  8993. case Engine.ALPHA_ADD:
  8994. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8995. this._alphaState.alphaBlend = true;
  8996. break;
  8997. case Engine.ALPHA_SUBTRACT:
  8998. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8999. this._alphaState.alphaBlend = true;
  9000. break;
  9001. case Engine.ALPHA_MULTIPLY:
  9002. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9003. this._alphaState.alphaBlend = true;
  9004. break;
  9005. case Engine.ALPHA_MAXIMIZED:
  9006. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9007. this._alphaState.alphaBlend = true;
  9008. break;
  9009. case Engine.ALPHA_INTERPOLATE:
  9010. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9011. this._alphaState.alphaBlend = true;
  9012. break;
  9013. case Engine.ALPHA_SCREENMODE:
  9014. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9015. this._alphaState.alphaBlend = true;
  9016. break;
  9017. }
  9018. if (!noDepthWriteChange) {
  9019. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9020. }
  9021. this._alphaMode = mode;
  9022. };
  9023. Engine.prototype.getAlphaMode = function () {
  9024. return this._alphaMode;
  9025. };
  9026. Engine.prototype.setAlphaTesting = function (enable) {
  9027. this._alphaTest = enable;
  9028. };
  9029. Engine.prototype.getAlphaTesting = function () {
  9030. return !!this._alphaTest;
  9031. };
  9032. // Textures
  9033. Engine.prototype.wipeCaches = function (bruteForce) {
  9034. if (this.preventCacheWipeBetweenFrames) {
  9035. return;
  9036. }
  9037. this.resetTextureCache();
  9038. this._currentEffect = null;
  9039. // 6/8/2017: deltakosh: Should not be required anymore.
  9040. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9041. if (bruteForce) {
  9042. this._stencilState.reset();
  9043. this._depthCullingState.reset();
  9044. this.setDepthFunctionToLessOrEqual();
  9045. this._alphaState.reset();
  9046. }
  9047. this._cachedVertexBuffers = null;
  9048. this._cachedIndexBuffer = null;
  9049. this._cachedEffectForVertexBuffers = null;
  9050. this._unBindVertexArrayObject();
  9051. this.bindIndexBuffer(null);
  9052. this.bindArrayBuffer(null);
  9053. };
  9054. /**
  9055. * Set the compressed texture format to use, based on the formats you have, and the formats
  9056. * supported by the hardware / browser.
  9057. *
  9058. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9059. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9060. * to API arguments needed to compressed textures. This puts the burden on the container
  9061. * generator to house the arcane code for determining these for current & future formats.
  9062. *
  9063. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9064. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9065. *
  9066. * Note: The result of this call is not taken into account when a texture is base64.
  9067. *
  9068. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9069. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9070. *
  9071. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9072. * @returns The extension selected.
  9073. */
  9074. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9075. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9076. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9077. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9078. return this._textureFormatInUse = this._texturesSupported[i];
  9079. }
  9080. }
  9081. }
  9082. // actively set format to nothing, to allow this to be called more than once
  9083. // and possibly fail the 2nd time
  9084. return this._textureFormatInUse = null;
  9085. };
  9086. /**
  9087. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9088. * @param {string} urlArg- This contains one of the following:
  9089. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9090. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9091. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9092. *
  9093. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9094. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9095. * @param {Scene} scene- Needed for loading to the correct scene.
  9096. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9097. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9098. * @param {callback} onError- Optional callback to be called upon failure.
  9099. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9100. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9101. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9102. *
  9103. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9104. */
  9105. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9106. var _this = this;
  9107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9108. if (onLoad === void 0) { onLoad = null; }
  9109. if (onError === void 0) { onError = null; }
  9110. if (buffer === void 0) { buffer = null; }
  9111. var texture = fallBack ? fallBack : this._gl.createTexture();
  9112. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9113. var fromData = url.substr(0, 5) === "data:";
  9114. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9115. // establish the file extension, if possible
  9116. var lastDot = url.lastIndexOf('.');
  9117. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9118. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9119. if (isDDS) {
  9120. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9121. }
  9122. var isTGA = (extension === ".tga");
  9123. // determine if a ktx file should be substituted
  9124. var isKTX = false;
  9125. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9126. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9127. isKTX = true;
  9128. }
  9129. scene._addPendingData(texture);
  9130. texture.url = url;
  9131. texture.noMipmap = noMipmap;
  9132. texture.references = 1;
  9133. texture.samplingMode = samplingMode;
  9134. texture.onLoadedCallbacks = [];
  9135. if (onLoad) {
  9136. texture.onLoadedCallbacks.push(onLoad);
  9137. }
  9138. if (!fallBack)
  9139. this._loadedTexturesCache.push(texture);
  9140. var onerror = function () {
  9141. scene._removePendingData(texture);
  9142. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9143. if (isKTX) {
  9144. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9145. }
  9146. else if (onError) {
  9147. onError();
  9148. }
  9149. };
  9150. var callback;
  9151. // processing for non-image formats
  9152. if (isKTX || isTGA || isDDS) {
  9153. if (isKTX) {
  9154. callback = function (data) {
  9155. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9156. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9157. ktx.uploadLevels(_this._gl, !noMipmap);
  9158. }, samplingMode);
  9159. };
  9160. }
  9161. else if (isTGA) {
  9162. callback = function (arrayBuffer) {
  9163. var data = new Uint8Array(arrayBuffer);
  9164. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9165. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9166. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9167. }, samplingMode);
  9168. };
  9169. }
  9170. else if (isDDS) {
  9171. callback = function (data) {
  9172. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9173. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9174. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9175. // Internals.DDSTools.UploadDDSLevels(this, data, info, loadMipmap, 1);
  9176. }, samplingMode);
  9177. };
  9178. }
  9179. if (!buffer) {
  9180. BABYLON.Tools.LoadFile(url, function (data) {
  9181. callback(data);
  9182. }, null, scene.database, true, onerror);
  9183. }
  9184. else {
  9185. callback(buffer);
  9186. }
  9187. // image format processing
  9188. }
  9189. else {
  9190. var onload = function (img) {
  9191. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9192. var isPot = (img.width === potWidth && img.height === potHeight);
  9193. if (!isPot) {
  9194. _this._prepareWorkingCanvas();
  9195. _this._workingCanvas.width = potWidth;
  9196. _this._workingCanvas.height = potHeight;
  9197. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9198. _this._workingContext.imageSmoothingEnabled = false;
  9199. _this._workingContext.mozImageSmoothingEnabled = false;
  9200. _this._workingContext.oImageSmoothingEnabled = false;
  9201. _this._workingContext.webkitImageSmoothingEnabled = false;
  9202. _this._workingContext.msImageSmoothingEnabled = false;
  9203. }
  9204. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9205. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9206. _this._workingContext.imageSmoothingEnabled = true;
  9207. _this._workingContext.mozImageSmoothingEnabled = true;
  9208. _this._workingContext.oImageSmoothingEnabled = true;
  9209. _this._workingContext.webkitImageSmoothingEnabled = true;
  9210. _this._workingContext.msImageSmoothingEnabled = true;
  9211. }
  9212. }
  9213. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9214. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9215. }, samplingMode);
  9216. };
  9217. if (!fromData || isBase64)
  9218. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9219. else if (buffer instanceof Array || typeof buffer === "string")
  9220. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9221. else
  9222. onload(buffer);
  9223. }
  9224. return texture;
  9225. };
  9226. Engine.prototype._getInternalFormat = function (format) {
  9227. var internalFormat = this._gl.RGBA;
  9228. switch (format) {
  9229. case Engine.TEXTUREFORMAT_ALPHA:
  9230. internalFormat = this._gl.ALPHA;
  9231. break;
  9232. case Engine.TEXTUREFORMAT_LUMINANCE:
  9233. internalFormat = this._gl.LUMINANCE;
  9234. break;
  9235. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9236. internalFormat = this._gl.LUMINANCE_ALPHA;
  9237. break;
  9238. case Engine.TEXTUREFORMAT_RGB:
  9239. internalFormat = this._gl.RGB;
  9240. break;
  9241. case Engine.TEXTUREFORMAT_RGBA:
  9242. internalFormat = this._gl.RGBA;
  9243. break;
  9244. }
  9245. return internalFormat;
  9246. };
  9247. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9248. if (compression === void 0) { compression = null; }
  9249. var internalFormat = this._getInternalFormat(format);
  9250. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9251. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9252. if (texture._width % 4 !== 0) {
  9253. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9254. }
  9255. if (compression) {
  9256. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9257. }
  9258. else {
  9259. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9260. }
  9261. if (texture.generateMipMaps) {
  9262. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9263. }
  9264. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9265. this.resetTextureCache();
  9266. texture.isReady = true;
  9267. };
  9268. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9269. if (compression === void 0) { compression = null; }
  9270. var texture = this._gl.createTexture();
  9271. texture._baseWidth = width;
  9272. texture._baseHeight = height;
  9273. texture._width = width;
  9274. texture._height = height;
  9275. texture.references = 1;
  9276. this.updateRawTexture(texture, data, format, invertY, compression);
  9277. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9278. // Filters
  9279. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9280. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9281. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9282. if (generateMipMaps) {
  9283. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9284. }
  9285. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9286. texture.samplingMode = samplingMode;
  9287. this._loadedTexturesCache.push(texture);
  9288. return texture;
  9289. };
  9290. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9291. var texture = this._gl.createTexture();
  9292. texture._baseWidth = width;
  9293. texture._baseHeight = height;
  9294. if (generateMipMaps) {
  9295. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9296. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9297. }
  9298. this.resetTextureCache();
  9299. texture._width = width;
  9300. texture._height = height;
  9301. texture.isReady = false;
  9302. texture.generateMipMaps = generateMipMaps;
  9303. texture.references = 1;
  9304. texture.samplingMode = samplingMode;
  9305. this.updateTextureSamplingMode(samplingMode, texture);
  9306. this._loadedTexturesCache.push(texture);
  9307. return texture;
  9308. };
  9309. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9310. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9311. if (texture.isCube) {
  9312. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9313. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9314. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9315. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9316. }
  9317. else {
  9318. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9319. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9321. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9322. }
  9323. texture.samplingMode = samplingMode;
  9324. };
  9325. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9326. if (premulAlpha === void 0) { premulAlpha = false; }
  9327. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9328. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9329. if (premulAlpha) {
  9330. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9331. }
  9332. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9333. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9334. if (texture.generateMipMaps) {
  9335. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9336. }
  9337. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9338. if (premulAlpha) {
  9339. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9340. }
  9341. this.resetTextureCache();
  9342. texture.isReady = true;
  9343. };
  9344. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9345. if (texture._isDisabled) {
  9346. return;
  9347. }
  9348. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9349. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9350. try {
  9351. // Testing video texture support
  9352. if (this._videoTextureSupported === undefined) {
  9353. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9354. if (this._gl.getError() !== 0) {
  9355. this._videoTextureSupported = false;
  9356. }
  9357. else {
  9358. this._videoTextureSupported = true;
  9359. }
  9360. }
  9361. // Copy video through the current working canvas if video texture is not supported
  9362. if (!this._videoTextureSupported) {
  9363. if (!texture._workingCanvas) {
  9364. texture._workingCanvas = document.createElement("canvas");
  9365. texture._workingContext = texture._workingCanvas.getContext("2d");
  9366. texture._workingCanvas.width = texture._width;
  9367. texture._workingCanvas.height = texture._height;
  9368. }
  9369. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9370. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9371. }
  9372. else {
  9373. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9374. }
  9375. if (texture.generateMipMaps) {
  9376. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9377. }
  9378. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9379. this.resetTextureCache();
  9380. texture.isReady = true;
  9381. }
  9382. catch (ex) {
  9383. // Something unexpected
  9384. // Let's disable the texture
  9385. texture._isDisabled = true;
  9386. }
  9387. };
  9388. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9389. // old version had a "generateMipMaps" arg instead of options.
  9390. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9391. // in the same way, generateDepthBuffer is defaulted to true
  9392. var generateMipMaps = false;
  9393. var generateDepthBuffer = true;
  9394. var generateStencilBuffer = false;
  9395. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9396. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9397. if (options !== undefined) {
  9398. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9399. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9400. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9401. type = options.type === undefined ? type : options.type;
  9402. if (options.samplingMode !== undefined) {
  9403. samplingMode = options.samplingMode;
  9404. }
  9405. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9406. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9407. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9408. }
  9409. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9410. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9411. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9412. }
  9413. }
  9414. var gl = this._gl;
  9415. var texture = gl.createTexture();
  9416. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9417. var width = size.width || size;
  9418. var height = size.height || size;
  9419. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9420. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9421. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9422. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9423. }
  9424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9425. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9426. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9428. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9429. // Create the framebuffer
  9430. var framebuffer = gl.createFramebuffer();
  9431. this.bindUnboundFramebuffer(framebuffer);
  9432. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9433. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9434. if (generateMipMaps) {
  9435. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9436. }
  9437. // Unbind
  9438. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9439. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9440. this.bindUnboundFramebuffer(null);
  9441. texture._framebuffer = framebuffer;
  9442. texture._baseWidth = width;
  9443. texture._baseHeight = height;
  9444. texture._width = width;
  9445. texture._height = height;
  9446. texture.isReady = true;
  9447. texture.samples = 1;
  9448. texture.generateMipMaps = generateMipMaps;
  9449. texture.references = 1;
  9450. texture.samplingMode = samplingMode;
  9451. texture.type = type;
  9452. texture._generateDepthBuffer = generateDepthBuffer;
  9453. texture._generateStencilBuffer = generateStencilBuffer;
  9454. this.resetTextureCache();
  9455. this._loadedTexturesCache.push(texture);
  9456. return texture;
  9457. };
  9458. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9459. var generateMipMaps = false;
  9460. var generateDepthBuffer = true;
  9461. var generateStencilBuffer = false;
  9462. var generateDepthTexture = false;
  9463. var textureCount = 1;
  9464. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9465. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9466. var types = [], samplingModes = [];
  9467. if (options !== undefined) {
  9468. generateMipMaps = options.generateMipMaps;
  9469. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9470. generateStencilBuffer = options.generateStencilBuffer;
  9471. generateDepthTexture = options.generateDepthTexture;
  9472. textureCount = options.textureCount || 1;
  9473. if (options.types) {
  9474. types = options.types;
  9475. }
  9476. if (options.samplingModes) {
  9477. samplingModes = options.samplingModes;
  9478. }
  9479. }
  9480. var gl = this._gl;
  9481. // Create the framebuffer
  9482. var framebuffer = gl.createFramebuffer();
  9483. this.bindUnboundFramebuffer(framebuffer);
  9484. var width = size.width || size;
  9485. var height = size.height || size;
  9486. var textures = [];
  9487. var attachments = [];
  9488. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9489. for (var i = 0; i < textureCount; i++) {
  9490. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9491. var type = types[i] || defaultType;
  9492. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9493. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9494. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9495. }
  9496. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9497. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9498. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9499. }
  9500. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9501. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9502. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9503. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9504. }
  9505. var texture = gl.createTexture();
  9506. var attachment = gl["COLOR_ATTACHMENT" + i];
  9507. textures.push(texture);
  9508. attachments.push(attachment);
  9509. gl.activeTexture(gl["TEXTURE" + i]);
  9510. gl.bindTexture(gl.TEXTURE_2D, texture);
  9511. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9512. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9513. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9514. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9515. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9516. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9517. if (generateMipMaps) {
  9518. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9519. }
  9520. // Unbind
  9521. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9522. texture._framebuffer = framebuffer;
  9523. texture._depthStencilBuffer = depthStencilBuffer;
  9524. texture._baseWidth = width;
  9525. texture._baseHeight = height;
  9526. texture._width = width;
  9527. texture._height = height;
  9528. texture.isReady = true;
  9529. texture.samples = 1;
  9530. texture.generateMipMaps = generateMipMaps;
  9531. texture.references = 1;
  9532. texture.samplingMode = samplingMode;
  9533. texture.type = type;
  9534. texture._generateDepthBuffer = generateDepthBuffer;
  9535. texture._generateStencilBuffer = generateStencilBuffer;
  9536. this._loadedTexturesCache.push(texture);
  9537. }
  9538. if (generateDepthTexture) {
  9539. // Depth texture
  9540. var depthTexture = gl.createTexture();
  9541. gl.activeTexture(gl.TEXTURE0);
  9542. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9543. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9544. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9545. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9547. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9548. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9549. depthTexture._framebuffer = framebuffer;
  9550. depthTexture._baseWidth = width;
  9551. depthTexture._baseHeight = height;
  9552. depthTexture._width = width;
  9553. depthTexture._height = height;
  9554. depthTexture.isReady = true;
  9555. depthTexture.samples = 1;
  9556. depthTexture.generateMipMaps = generateMipMaps;
  9557. depthTexture.references = 1;
  9558. depthTexture.samplingMode = gl.NEAREST;
  9559. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9560. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9561. textures.push(depthTexture);
  9562. this._loadedTexturesCache.push(depthTexture);
  9563. }
  9564. gl.drawBuffers(attachments);
  9565. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9566. this.bindUnboundFramebuffer(null);
  9567. this.resetTextureCache();
  9568. return textures;
  9569. };
  9570. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9571. if (samples === void 0) { samples = 1; }
  9572. var depthStencilBuffer = null;
  9573. var gl = this._gl;
  9574. // Create the depth/stencil buffer
  9575. if (generateStencilBuffer) {
  9576. depthStencilBuffer = gl.createRenderbuffer();
  9577. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9578. if (samples > 1) {
  9579. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9580. }
  9581. else {
  9582. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9583. }
  9584. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9585. }
  9586. else if (generateDepthBuffer) {
  9587. depthStencilBuffer = gl.createRenderbuffer();
  9588. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9589. if (samples > 1) {
  9590. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9591. }
  9592. else {
  9593. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9594. }
  9595. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9596. }
  9597. return depthStencilBuffer;
  9598. };
  9599. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9600. if (this.webGLVersion < 2) {
  9601. return 1;
  9602. }
  9603. if (texture.samples === samples) {
  9604. return samples;
  9605. }
  9606. var gl = this._gl;
  9607. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9608. // Dispose previous render buffers
  9609. if (texture._depthStencilBuffer) {
  9610. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9611. }
  9612. if (texture._MSAAFramebuffer) {
  9613. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9614. }
  9615. if (texture._MSAARenderBuffer) {
  9616. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9617. }
  9618. if (samples > 1) {
  9619. texture._MSAAFramebuffer = gl.createFramebuffer();
  9620. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9621. var colorRenderbuffer = gl.createRenderbuffer();
  9622. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9623. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9624. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9625. texture._MSAARenderBuffer = colorRenderbuffer;
  9626. }
  9627. else {
  9628. this.bindUnboundFramebuffer(texture._framebuffer);
  9629. }
  9630. texture.samples = samples;
  9631. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9632. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9633. this.bindUnboundFramebuffer(null);
  9634. return samples;
  9635. };
  9636. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  9637. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  9638. };
  9639. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  9640. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  9641. };
  9642. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9643. var gl = this._gl;
  9644. var texture = gl.createTexture();
  9645. var generateMipMaps = true;
  9646. var generateDepthBuffer = true;
  9647. var generateStencilBuffer = false;
  9648. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9649. if (options !== undefined) {
  9650. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9651. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9652. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9653. if (options.samplingMode !== undefined) {
  9654. samplingMode = options.samplingMode;
  9655. }
  9656. }
  9657. texture.isCube = true;
  9658. texture.references = 1;
  9659. texture.generateMipMaps = generateMipMaps;
  9660. texture.references = 1;
  9661. texture.samples = 1;
  9662. texture.samplingMode = samplingMode;
  9663. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9664. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9665. for (var face = 0; face < 6; face++) {
  9666. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9667. }
  9668. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9669. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9670. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9672. // Create the framebuffer
  9673. var framebuffer = gl.createFramebuffer();
  9674. this.bindUnboundFramebuffer(framebuffer);
  9675. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9676. // Mipmaps
  9677. if (texture.generateMipMaps) {
  9678. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9679. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9680. }
  9681. // Unbind
  9682. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9683. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9684. this.bindUnboundFramebuffer(null);
  9685. texture._framebuffer = framebuffer;
  9686. texture._width = size;
  9687. texture._height = size;
  9688. texture.isReady = true;
  9689. this.resetTextureCache();
  9690. this._loadedTexturesCache.push(texture);
  9691. return texture;
  9692. };
  9693. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9694. var _this = this;
  9695. if (onLoad === void 0) { onLoad = null; }
  9696. if (onError === void 0) { onError = null; }
  9697. var gl = this._gl;
  9698. var texture = gl.createTexture();
  9699. texture.isCube = true;
  9700. texture.url = rootUrl;
  9701. texture.references = 1;
  9702. texture.onLoadedCallbacks = [];
  9703. var isKTX = false;
  9704. var isDDS = false;
  9705. var lastDot = rootUrl.lastIndexOf('.');
  9706. var extension = rootUrl.substring(lastDot).toLowerCase();
  9707. if (this._textureFormatInUse) {
  9708. extension = this._textureFormatInUse;
  9709. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9710. isKTX = true;
  9711. }
  9712. else {
  9713. isDDS = (extension === ".dds");
  9714. }
  9715. if (isKTX) {
  9716. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9717. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9718. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9719. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9720. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9721. ktx.uploadLevels(_this._gl, !noMipmap);
  9722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9725. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9726. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9727. _this.resetTextureCache();
  9728. texture._width = ktx.pixelWidth;
  9729. texture._height = ktx.pixelHeight;
  9730. texture.isReady = true;
  9731. }, null, null, true, onError);
  9732. }
  9733. else if (isDDS) {
  9734. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9735. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9736. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9737. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9738. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  9739. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 6);
  9740. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9741. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9742. }
  9743. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9744. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9745. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9746. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9747. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9748. _this.resetTextureCache();
  9749. texture._width = info.width;
  9750. texture._height = info.height;
  9751. texture.isReady = true;
  9752. texture.type = info.textureType;
  9753. }, null, null, true, onError);
  9754. }
  9755. else {
  9756. cascadeLoad(rootUrl, scene, function (imgs) {
  9757. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9758. var height = width;
  9759. _this._prepareWorkingCanvas();
  9760. _this._workingCanvas.width = width;
  9761. _this._workingCanvas.height = height;
  9762. var faces = [
  9763. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9764. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9765. ];
  9766. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9767. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9768. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9769. for (var index = 0; index < faces.length; index++) {
  9770. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9771. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9772. }
  9773. if (!noMipmap) {
  9774. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9775. }
  9776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9780. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9781. _this.resetTextureCache();
  9782. texture._width = width;
  9783. texture._height = height;
  9784. texture.isReady = true;
  9785. texture.onLoadedCallbacks.forEach(function (callback) {
  9786. callback();
  9787. });
  9788. if (onLoad) {
  9789. onLoad();
  9790. }
  9791. }, files, onError);
  9792. }
  9793. this._loadedTexturesCache.push(texture);
  9794. return texture;
  9795. };
  9796. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9797. texture._width = width;
  9798. texture._height = height;
  9799. texture._size = width * height;
  9800. texture._baseWidth = width;
  9801. texture._baseHeight = height;
  9802. };
  9803. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9804. if (compression === void 0) { compression = null; }
  9805. if (level === void 0) { level = 0; }
  9806. var gl = this._gl;
  9807. var textureType = this._getWebGLTextureType(type);
  9808. var internalFormat = this._getInternalFormat(format);
  9809. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9810. var needConversion = false;
  9811. if (internalFormat === gl.RGB) {
  9812. internalFormat = gl.RGBA;
  9813. needConversion = true;
  9814. }
  9815. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9816. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9817. if (texture._width % 4 !== 0) {
  9818. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9819. }
  9820. var facesIndex = [
  9821. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9822. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9823. ];
  9824. // Data are known to be in +X +Y +Z -X -Y -Z
  9825. for (var index = 0; index < facesIndex.length; index++) {
  9826. var faceData = data[index];
  9827. if (compression) {
  9828. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9829. }
  9830. else {
  9831. if (needConversion) {
  9832. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9833. }
  9834. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9835. }
  9836. }
  9837. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9838. if (isPot && texture.generateMipMaps && level === 0) {
  9839. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9840. }
  9841. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9842. this.resetTextureCache();
  9843. texture.isReady = true;
  9844. };
  9845. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9846. if (compression === void 0) { compression = null; }
  9847. var gl = this._gl;
  9848. var texture = gl.createTexture();
  9849. texture.isCube = true;
  9850. texture.references = 1;
  9851. var textureType = this._getWebGLTextureType(type);
  9852. var internalFormat = this._getInternalFormat(format);
  9853. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9854. var needConversion = false;
  9855. if (internalFormat === gl.RGB) {
  9856. internalFormat = gl.RGBA;
  9857. needConversion = true;
  9858. }
  9859. var width = size;
  9860. var height = width;
  9861. texture._width = width;
  9862. texture._height = height;
  9863. // Double check on POT to generate Mips.
  9864. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9865. if (!isPot) {
  9866. generateMipMaps = false;
  9867. }
  9868. texture.generateMipMaps = generateMipMaps;
  9869. // Upload data if needed. The texture won t be ready until then.
  9870. if (data) {
  9871. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9872. }
  9873. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9874. // Filters
  9875. if (data && generateMipMaps) {
  9876. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9877. }
  9878. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9881. }
  9882. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9885. }
  9886. else {
  9887. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9888. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9889. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9890. }
  9891. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9893. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9894. this._loadedTexturesCache.push(texture);
  9895. return texture;
  9896. };
  9897. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9898. var _this = this;
  9899. if (onLoad === void 0) { onLoad = null; }
  9900. if (onError === void 0) { onError = null; }
  9901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9902. if (invertY === void 0) { invertY = false; }
  9903. var gl = this._gl;
  9904. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9905. scene._addPendingData(texture);
  9906. texture.url = url;
  9907. var onerror = function () {
  9908. scene._removePendingData(texture);
  9909. if (onError) {
  9910. onError();
  9911. }
  9912. };
  9913. var internalCallback = function (data) {
  9914. var rgbeDataArrays = callback(data);
  9915. var facesIndex = [
  9916. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9917. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9918. ];
  9919. var width = texture._width;
  9920. var height = texture._height;
  9921. if (mipmmapGenerator) {
  9922. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9923. // I ll remove ASAP.
  9924. var textureType = _this._getWebGLTextureType(type);
  9925. var internalFormat = _this._getInternalFormat(format);
  9926. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9927. var needConversion = false;
  9928. if (internalFormat === gl.RGB) {
  9929. internalFormat = gl.RGBA;
  9930. needConversion = true;
  9931. }
  9932. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9933. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9934. var arrayTemp = [];
  9935. // Data are known to be in +X +Y +Z -X -Y -Z
  9936. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9937. arrayTemp.push(rgbeDataArrays[0]); // +X
  9938. arrayTemp.push(rgbeDataArrays[3]); // -X
  9939. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9940. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9941. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9942. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9943. var mipData = mipmmapGenerator(arrayTemp);
  9944. // mipData is order in +X -X +Y -Y +Z -Z
  9945. var mipFaces = [0, 2, 4, 1, 3, 5];
  9946. for (var level = 0; level < mipData.length; level++) {
  9947. var mipSize = width >> level;
  9948. for (var mipIndex in mipFaces) {
  9949. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9950. if (needConversion) {
  9951. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9952. }
  9953. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9954. }
  9955. }
  9956. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9957. }
  9958. else {
  9959. texture.generateMipMaps = !noMipmap;
  9960. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9961. }
  9962. texture.isReady = true;
  9963. _this.resetTextureCache();
  9964. scene._removePendingData(texture);
  9965. if (onLoad) {
  9966. onLoad();
  9967. }
  9968. };
  9969. BABYLON.Tools.LoadFile(url, function (data) {
  9970. internalCallback(data);
  9971. }, onerror, scene.database, true);
  9972. return texture;
  9973. };
  9974. ;
  9975. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9976. // Create new RGBA data container.
  9977. var rgbaData;
  9978. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9979. rgbaData = new Float32Array(width * height * 4);
  9980. }
  9981. else {
  9982. rgbaData = new Uint32Array(width * height * 4);
  9983. }
  9984. // Convert each pixel.
  9985. for (var x = 0; x < width; x++) {
  9986. for (var y = 0; y < height; y++) {
  9987. var index = (y * width + x) * 3;
  9988. var newIndex = (y * width + x) * 4;
  9989. // Map Old Value to new value.
  9990. rgbaData[newIndex + 0] = rgbData[index + 0];
  9991. rgbaData[newIndex + 1] = rgbData[index + 1];
  9992. rgbaData[newIndex + 2] = rgbData[index + 2];
  9993. // Add fully opaque alpha channel.
  9994. rgbaData[newIndex + 3] = 1;
  9995. }
  9996. }
  9997. return rgbaData;
  9998. };
  9999. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10000. var gl = this._gl;
  10001. if (texture._framebuffer) {
  10002. gl.deleteFramebuffer(texture._framebuffer);
  10003. texture._framebuffer = null;
  10004. }
  10005. if (texture._depthStencilBuffer) {
  10006. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10007. texture._depthStencilBuffer = null;
  10008. }
  10009. if (texture._MSAAFramebuffer) {
  10010. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10011. texture._MSAAFramebuffer = null;
  10012. }
  10013. if (texture._MSAARenderBuffer) {
  10014. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10015. texture._MSAARenderBuffer = null;
  10016. }
  10017. };
  10018. Engine.prototype._releaseTexture = function (texture) {
  10019. var gl = this._gl;
  10020. this._releaseFramebufferObjects(texture);
  10021. gl.deleteTexture(texture);
  10022. // Unbind channels
  10023. this.unbindAllTextures();
  10024. var index = this._loadedTexturesCache.indexOf(texture);
  10025. if (index !== -1) {
  10026. this._loadedTexturesCache.splice(index, 1);
  10027. }
  10028. };
  10029. Engine.prototype.setProgram = function (program) {
  10030. if (this._currentProgram !== program) {
  10031. this._gl.useProgram(program);
  10032. this._currentProgram = program;
  10033. }
  10034. };
  10035. Engine.prototype.bindSamplers = function (effect) {
  10036. this.setProgram(effect.getProgram());
  10037. var samplers = effect.getSamplers();
  10038. for (var index = 0; index < samplers.length; index++) {
  10039. var uniform = effect.getUniform(samplers[index]);
  10040. this._gl.uniform1i(uniform, index);
  10041. }
  10042. this._currentEffect = null;
  10043. };
  10044. Engine.prototype.activateTexture = function (texture) {
  10045. if (this._activeTexture !== texture) {
  10046. this._gl.activeTexture(texture);
  10047. this._activeTexture = texture;
  10048. }
  10049. };
  10050. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10051. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10052. this._gl.bindTexture(target, texture);
  10053. this._activeTexturesCache[this._activeTexture] = texture;
  10054. }
  10055. };
  10056. Engine.prototype._bindTexture = function (channel, texture) {
  10057. if (channel < 0) {
  10058. return;
  10059. }
  10060. this.activateTexture(this._gl.TEXTURE0 + channel);
  10061. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10062. };
  10063. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10064. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10065. };
  10066. Engine.prototype.unbindAllTextures = function () {
  10067. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  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. };
  10073. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10074. if (channel < 0) {
  10075. return;
  10076. }
  10077. this._gl.uniform1i(uniform, channel);
  10078. this._setTexture(channel, texture);
  10079. };
  10080. Engine.prototype._setTexture = function (channel, texture) {
  10081. // Not ready?
  10082. if (!texture) {
  10083. if (this._activeTexturesCache[channel] != null) {
  10084. this.activateTexture(this._gl["TEXTURE" + channel]);
  10085. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10086. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10087. }
  10088. return;
  10089. }
  10090. // Video
  10091. var alreadyActivated = false;
  10092. if (texture.video) {
  10093. this.activateTexture(this._gl["TEXTURE" + channel]);
  10094. alreadyActivated = true;
  10095. texture.update();
  10096. }
  10097. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10098. texture.delayLoad();
  10099. return;
  10100. }
  10101. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10102. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10103. if (this._activeTexturesCache[channel] === internalTexture) {
  10104. return;
  10105. }
  10106. if (!alreadyActivated) {
  10107. this.activateTexture(this._gl["TEXTURE" + channel]);
  10108. }
  10109. if (internalTexture.isCube) {
  10110. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10111. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10112. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10113. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10114. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10115. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10116. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10117. }
  10118. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10119. }
  10120. else {
  10121. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10122. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10123. internalTexture._cachedWrapU = texture.wrapU;
  10124. switch (texture.wrapU) {
  10125. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10126. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10127. break;
  10128. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10129. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10130. break;
  10131. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10132. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10133. break;
  10134. }
  10135. }
  10136. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10137. internalTexture._cachedWrapV = texture.wrapV;
  10138. switch (texture.wrapV) {
  10139. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10140. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10141. break;
  10142. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10143. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10144. break;
  10145. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10146. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10147. break;
  10148. }
  10149. }
  10150. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10151. }
  10152. };
  10153. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10154. if (channel < 0) {
  10155. return;
  10156. }
  10157. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10158. this._textureUnits = new Int32Array(textures.length);
  10159. }
  10160. for (var i = 0; i < textures.length; i++) {
  10161. this._textureUnits[i] = channel + i;
  10162. }
  10163. this._gl.uniform1iv(uniform, this._textureUnits);
  10164. for (var index = 0; index < textures.length; index++) {
  10165. this._setTexture(channel + index, textures[index]);
  10166. }
  10167. };
  10168. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10169. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10170. var value = texture.anisotropicFilteringLevel;
  10171. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10172. value = 1;
  10173. }
  10174. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10175. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10176. texture._cachedAnisotropicFilteringLevel = value;
  10177. }
  10178. };
  10179. Engine.prototype.readPixels = function (x, y, width, height) {
  10180. var data = new Uint8Array(height * width * 4);
  10181. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10182. return data;
  10183. };
  10184. /**
  10185. * Add an externaly attached data from its key.
  10186. * This method call will fail and return false, if such key already exists.
  10187. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10188. * @param key the unique key that identifies the data
  10189. * @param data the data object to associate to the key for this Engine instance
  10190. * @return true if no such key were already present and the data was added successfully, false otherwise
  10191. */
  10192. Engine.prototype.addExternalData = function (key, data) {
  10193. if (!this._externalData) {
  10194. this._externalData = new BABYLON.StringDictionary();
  10195. }
  10196. return this._externalData.add(key, data);
  10197. };
  10198. /**
  10199. * Get an externaly attached data from its key
  10200. * @param key the unique key that identifies the data
  10201. * @return the associated data, if present (can be null), or undefined if not present
  10202. */
  10203. Engine.prototype.getExternalData = function (key) {
  10204. if (!this._externalData) {
  10205. this._externalData = new BABYLON.StringDictionary();
  10206. }
  10207. return this._externalData.get(key);
  10208. };
  10209. /**
  10210. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10211. * @param key the unique key that identifies the data
  10212. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10213. * @return the associated data, can be null if the factory returned null.
  10214. */
  10215. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10216. if (!this._externalData) {
  10217. this._externalData = new BABYLON.StringDictionary();
  10218. }
  10219. return this._externalData.getOrAddWithFactory(key, factory);
  10220. };
  10221. /**
  10222. * Remove an externaly attached data from the Engine instance
  10223. * @param key the unique key that identifies the data
  10224. * @return true if the data was successfully removed, false if it doesn't exist
  10225. */
  10226. Engine.prototype.removeExternalData = function (key) {
  10227. if (!this._externalData) {
  10228. this._externalData = new BABYLON.StringDictionary();
  10229. }
  10230. return this._externalData.remove(key);
  10231. };
  10232. Engine.prototype.releaseInternalTexture = function (texture) {
  10233. if (!texture) {
  10234. return;
  10235. }
  10236. texture.references--;
  10237. // Final reference ?
  10238. if (texture.references === 0) {
  10239. var texturesCache = this.getLoadedTexturesCache();
  10240. var index = texturesCache.indexOf(texture);
  10241. if (index > -1) {
  10242. texturesCache.splice(index, 1);
  10243. }
  10244. this._releaseTexture(texture);
  10245. }
  10246. };
  10247. Engine.prototype.unbindAllAttributes = function () {
  10248. if (this._mustWipeVertexAttributes) {
  10249. this._mustWipeVertexAttributes = false;
  10250. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10251. this._gl.disableVertexAttribArray(i);
  10252. this._vertexAttribArraysEnabled[i] = false;
  10253. this._currentBufferPointers[i] = null;
  10254. }
  10255. return;
  10256. }
  10257. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10258. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10259. continue;
  10260. }
  10261. this._gl.disableVertexAttribArray(i);
  10262. this._vertexAttribArraysEnabled[i] = false;
  10263. this._currentBufferPointers[i] = null;
  10264. }
  10265. };
  10266. Engine.prototype.releaseEffects = function () {
  10267. for (var name in this._compiledEffects) {
  10268. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10269. }
  10270. this._compiledEffects = {};
  10271. };
  10272. // Dispose
  10273. Engine.prototype.dispose = function () {
  10274. this.hideLoadingUI();
  10275. this.stopRenderLoop();
  10276. // Empty texture
  10277. if (this._emptyTexture) {
  10278. this._releaseTexture(this._emptyTexture);
  10279. this._emptyTexture = null;
  10280. }
  10281. if (this._emptyCubeTexture) {
  10282. this._releaseTexture(this._emptyCubeTexture);
  10283. this._emptyCubeTexture = null;
  10284. }
  10285. // Release scenes
  10286. while (this.scenes.length) {
  10287. this.scenes[0].dispose();
  10288. }
  10289. // Release audio engine
  10290. if (Engine.audioEngine) {
  10291. Engine.audioEngine.dispose();
  10292. }
  10293. // Release effects
  10294. this.releaseEffects();
  10295. // Unbind
  10296. this.unbindAllAttributes();
  10297. if (this._dummyFramebuffer) {
  10298. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10299. }
  10300. this._gl = null;
  10301. //WebVR
  10302. this.disableVR();
  10303. // Events
  10304. window.removeEventListener("blur", this._onBlur);
  10305. window.removeEventListener("focus", this._onFocus);
  10306. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10307. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10308. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10309. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10310. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10311. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10312. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10313. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10314. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10315. // Remove from Instances
  10316. var index = Engine.Instances.indexOf(this);
  10317. if (index >= 0) {
  10318. Engine.Instances.splice(index, 1);
  10319. }
  10320. };
  10321. // Loading screen
  10322. Engine.prototype.displayLoadingUI = function () {
  10323. var loadingScreen = this.loadingScreen;
  10324. if (loadingScreen) {
  10325. loadingScreen.displayLoadingUI();
  10326. }
  10327. };
  10328. Engine.prototype.hideLoadingUI = function () {
  10329. var loadingScreen = this.loadingScreen;
  10330. if (loadingScreen) {
  10331. loadingScreen.hideLoadingUI();
  10332. }
  10333. };
  10334. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10335. get: function () {
  10336. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10337. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10338. return this._loadingScreen;
  10339. },
  10340. set: function (loadingScreen) {
  10341. this._loadingScreen = loadingScreen;
  10342. },
  10343. enumerable: true,
  10344. configurable: true
  10345. });
  10346. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10347. set: function (text) {
  10348. this.loadingScreen.loadingUIText = text;
  10349. },
  10350. enumerable: true,
  10351. configurable: true
  10352. });
  10353. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10354. set: function (color) {
  10355. this.loadingScreen.loadingUIBackgroundColor = color;
  10356. },
  10357. enumerable: true,
  10358. configurable: true
  10359. });
  10360. Engine.prototype.attachContextLostEvent = function (callback) {
  10361. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10362. };
  10363. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10364. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10365. };
  10366. Engine.prototype.getVertexShaderSource = function (program) {
  10367. var shaders = this._gl.getAttachedShaders(program);
  10368. return this._gl.getShaderSource(shaders[0]);
  10369. };
  10370. Engine.prototype.getFragmentShaderSource = function (program) {
  10371. var shaders = this._gl.getAttachedShaders(program);
  10372. return this._gl.getShaderSource(shaders[1]);
  10373. };
  10374. Engine.prototype.getError = function () {
  10375. return this._gl.getError();
  10376. };
  10377. // FPS
  10378. Engine.prototype.getFps = function () {
  10379. return this.fps;
  10380. };
  10381. Engine.prototype.getDeltaTime = function () {
  10382. return this.deltaTime;
  10383. };
  10384. Engine.prototype._measureFps = function () {
  10385. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10386. var length = this.previousFramesDuration.length;
  10387. if (length >= 2) {
  10388. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10389. }
  10390. if (length >= this.fpsRange) {
  10391. if (length > this.fpsRange) {
  10392. this.previousFramesDuration.splice(0, 1);
  10393. length = this.previousFramesDuration.length;
  10394. }
  10395. var sum = 0;
  10396. for (var id = 0; id < length - 1; id++) {
  10397. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10398. }
  10399. this.fps = 1000.0 / (sum / (length - 1));
  10400. }
  10401. };
  10402. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, lodIndex) {
  10403. if (faceIndex === void 0) { faceIndex = -1; }
  10404. if (lodIndex === void 0) { lodIndex = 0; }
  10405. var gl = this._gl;
  10406. if (!this._dummyFramebuffer) {
  10407. this._dummyFramebuffer = gl.createFramebuffer();
  10408. }
  10409. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10410. if (faceIndex > -1) {
  10411. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, lodIndex);
  10412. }
  10413. else {
  10414. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, lodIndex);
  10415. }
  10416. var readFormat = (texture.type !== undefined) ? this._getRGBABufferInternalSizedFormat(texture.type) : gl.RGBA;
  10417. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10418. var buffer;
  10419. switch (readType) {
  10420. case gl.UNSIGNED_BYTE:
  10421. buffer = new Uint8Array(4 * width * height);
  10422. break;
  10423. case gl.FLOAT:
  10424. buffer = new Float32Array(4 * width * height);
  10425. break;
  10426. case gl.HALF_FLOAT_OES:
  10427. buffer = new Uint16Array(4 * width * height);
  10428. break;
  10429. }
  10430. gl.readPixels(0, 0, width, height, readFormat, readType, buffer);
  10431. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10432. return buffer;
  10433. };
  10434. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10435. if (this._webGLVersion > 1) {
  10436. return this._caps.colorBufferFloat;
  10437. }
  10438. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10439. };
  10440. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10441. if (this._webGLVersion > 1) {
  10442. return this._caps.colorBufferFloat;
  10443. }
  10444. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10445. };
  10446. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10447. Engine.prototype._canRenderToFramebuffer = function (type) {
  10448. var gl = this._gl;
  10449. //clear existing errors
  10450. while (gl.getError() !== gl.NO_ERROR) { }
  10451. var successful = true;
  10452. var texture = gl.createTexture();
  10453. gl.bindTexture(gl.TEXTURE_2D, texture);
  10454. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10455. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10456. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10457. var fb = gl.createFramebuffer();
  10458. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10459. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10460. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10461. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10462. successful = successful && (gl.getError() === gl.NO_ERROR);
  10463. //try render by clearing frame buffer's color buffer
  10464. if (successful) {
  10465. gl.clear(gl.COLOR_BUFFER_BIT);
  10466. successful = successful && (gl.getError() === gl.NO_ERROR);
  10467. }
  10468. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10469. if (successful) {
  10470. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10471. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10472. var readFormat = gl.RGBA;
  10473. var readType = gl.UNSIGNED_BYTE;
  10474. var buffer = new Uint8Array(4);
  10475. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10476. successful = successful && (gl.getError() === gl.NO_ERROR);
  10477. }
  10478. //clean up
  10479. gl.deleteTexture(texture);
  10480. gl.deleteFramebuffer(fb);
  10481. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10482. //clear accumulated errors
  10483. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10484. return successful;
  10485. };
  10486. Engine.prototype._getWebGLTextureType = function (type) {
  10487. if (type === Engine.TEXTURETYPE_FLOAT) {
  10488. return this._gl.FLOAT;
  10489. }
  10490. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10491. // Add Half Float Constant.
  10492. return this._gl.HALF_FLOAT_OES;
  10493. }
  10494. return this._gl.UNSIGNED_BYTE;
  10495. };
  10496. ;
  10497. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10498. if (this._webGLVersion === 1) {
  10499. return this._gl.RGBA;
  10500. }
  10501. if (type === Engine.TEXTURETYPE_FLOAT) {
  10502. return this._gl.RGBA32F;
  10503. }
  10504. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10505. return this._gl.RGBA16F;
  10506. }
  10507. return this._gl.RGBA;
  10508. };
  10509. ;
  10510. // Statics
  10511. Engine.isSupported = function () {
  10512. try {
  10513. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10514. if (navigator.isCocoonJS) {
  10515. return true;
  10516. }
  10517. var tempcanvas = document.createElement("canvas");
  10518. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10519. return gl != null && !!window.WebGLRenderingContext;
  10520. }
  10521. catch (e) {
  10522. return false;
  10523. }
  10524. };
  10525. return Engine;
  10526. }());
  10527. Engine.Instances = new Array();
  10528. // Const statics
  10529. Engine._ALPHA_DISABLE = 0;
  10530. Engine._ALPHA_ADD = 1;
  10531. Engine._ALPHA_COMBINE = 2;
  10532. Engine._ALPHA_SUBTRACT = 3;
  10533. Engine._ALPHA_MULTIPLY = 4;
  10534. Engine._ALPHA_MAXIMIZED = 5;
  10535. Engine._ALPHA_ONEONE = 6;
  10536. Engine._ALPHA_PREMULTIPLIED = 7;
  10537. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10538. Engine._ALPHA_INTERPOLATE = 9;
  10539. Engine._ALPHA_SCREENMODE = 10;
  10540. Engine._DELAYLOADSTATE_NONE = 0;
  10541. Engine._DELAYLOADSTATE_LOADED = 1;
  10542. Engine._DELAYLOADSTATE_LOADING = 2;
  10543. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10544. Engine._TEXTUREFORMAT_ALPHA = 0;
  10545. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10546. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10547. Engine._TEXTUREFORMAT_RGB = 4;
  10548. Engine._TEXTUREFORMAT_RGBA = 5;
  10549. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10550. Engine._TEXTURETYPE_FLOAT = 1;
  10551. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10552. // Depht or Stencil test Constants.
  10553. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10554. 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.
  10555. 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.
  10556. 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.
  10557. 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.
  10558. 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.
  10559. 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.
  10560. 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.
  10561. // Stencil Actions Constants.
  10562. Engine._KEEP = 0x1E00;
  10563. Engine._REPLACE = 0x1E01;
  10564. Engine._INCR = 0x1E02;
  10565. Engine._DECR = 0x1E03;
  10566. Engine._INVERT = 0x150A;
  10567. Engine._INCR_WRAP = 0x8507;
  10568. Engine._DECR_WRAP = 0x8508;
  10569. // Texture rescaling mode
  10570. Engine._SCALEMODE_FLOOR = 1;
  10571. Engine._SCALEMODE_NEAREST = 2;
  10572. Engine._SCALEMODE_CEILING = 3;
  10573. // Updatable statics so stick with vars here
  10574. Engine.CollisionsEpsilon = 0.001;
  10575. Engine.CodeRepository = "src/";
  10576. Engine.ShadersRepository = "src/Shaders/";
  10577. BABYLON.Engine = Engine;
  10578. })(BABYLON || (BABYLON = {}));
  10579. //# sourceMappingURL=babylon.engine.js.map
  10580. /// <reference path="Tools\babylon.decorators.ts" />
  10581. var BABYLON;
  10582. (function (BABYLON) {
  10583. /**
  10584. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10585. */
  10586. var Node = (function () {
  10587. /**
  10588. * @constructor
  10589. * @param {string} name - the name and id to be given to this node
  10590. * @param {BABYLON.Scene} the scene this node will be added to
  10591. */
  10592. function Node(name, scene) {
  10593. this.state = "";
  10594. this.metadata = null;
  10595. this.doNotSerialize = false;
  10596. this.animations = new Array();
  10597. this._ranges = {};
  10598. this._childrenFlag = -1;
  10599. this._isEnabled = true;
  10600. this._isReady = true;
  10601. this._currentRenderId = -1;
  10602. this._parentRenderId = -1;
  10603. /**
  10604. * An event triggered when the mesh is disposed.
  10605. * @type {BABYLON.Observable}
  10606. */
  10607. this.onDisposeObservable = new BABYLON.Observable();
  10608. this.name = name;
  10609. this.id = name;
  10610. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10611. this._initCache();
  10612. }
  10613. Object.defineProperty(Node.prototype, "parent", {
  10614. get: function () {
  10615. return this._parentNode;
  10616. },
  10617. set: function (parent) {
  10618. if (this._parentNode === parent) {
  10619. return;
  10620. }
  10621. if (this._parentNode) {
  10622. var index = this._parentNode._children.indexOf(this);
  10623. if (index !== -1) {
  10624. this._parentNode._children.splice(index, 1);
  10625. }
  10626. }
  10627. this._parentNode = parent;
  10628. if (this._parentNode) {
  10629. if (!this._parentNode._children) {
  10630. this._parentNode._children = new Array();
  10631. }
  10632. this._parentNode._children.push(this);
  10633. }
  10634. },
  10635. enumerable: true,
  10636. configurable: true
  10637. });
  10638. Node.prototype.getClassName = function () {
  10639. return "Node";
  10640. };
  10641. Object.defineProperty(Node.prototype, "onDispose", {
  10642. set: function (callback) {
  10643. if (this._onDisposeObserver) {
  10644. this.onDisposeObservable.remove(this._onDisposeObserver);
  10645. }
  10646. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10647. },
  10648. enumerable: true,
  10649. configurable: true
  10650. });
  10651. Node.prototype.getScene = function () {
  10652. return this._scene;
  10653. };
  10654. Node.prototype.getEngine = function () {
  10655. return this._scene.getEngine();
  10656. };
  10657. // override it in derived class
  10658. Node.prototype.getWorldMatrix = function () {
  10659. return BABYLON.Matrix.Identity();
  10660. };
  10661. // override it in derived class if you add new variables to the cache
  10662. // and call the parent class method
  10663. Node.prototype._initCache = function () {
  10664. this._cache = {};
  10665. this._cache.parent = undefined;
  10666. };
  10667. Node.prototype.updateCache = function (force) {
  10668. if (!force && this.isSynchronized())
  10669. return;
  10670. this._cache.parent = this.parent;
  10671. this._updateCache();
  10672. };
  10673. // override it in derived class if you add new variables to the cache
  10674. // and call the parent class method if !ignoreParentClass
  10675. Node.prototype._updateCache = function (ignoreParentClass) {
  10676. };
  10677. // override it in derived class if you add new variables to the cache
  10678. Node.prototype._isSynchronized = function () {
  10679. return true;
  10680. };
  10681. Node.prototype._markSyncedWithParent = function () {
  10682. this._parentRenderId = this.parent._currentRenderId;
  10683. };
  10684. Node.prototype.isSynchronizedWithParent = function () {
  10685. if (!this.parent) {
  10686. return true;
  10687. }
  10688. if (this._parentRenderId !== this.parent._currentRenderId) {
  10689. return false;
  10690. }
  10691. return this.parent.isSynchronized();
  10692. };
  10693. Node.prototype.isSynchronized = function (updateCache) {
  10694. var check = this.hasNewParent();
  10695. check = check || !this.isSynchronizedWithParent();
  10696. check = check || !this._isSynchronized();
  10697. if (updateCache)
  10698. this.updateCache(true);
  10699. return !check;
  10700. };
  10701. Node.prototype.hasNewParent = function (update) {
  10702. if (this._cache.parent === this.parent)
  10703. return false;
  10704. if (update)
  10705. this._cache.parent = this.parent;
  10706. return true;
  10707. };
  10708. /**
  10709. * Is this node ready to be used/rendered
  10710. * @return {boolean} is it ready
  10711. */
  10712. Node.prototype.isReady = function () {
  10713. return this._isReady;
  10714. };
  10715. /**
  10716. * Is this node enabled.
  10717. * If the node has a parent and is enabled, the parent will be inspected as well.
  10718. * @return {boolean} whether this node (and its parent) is enabled.
  10719. * @see setEnabled
  10720. */
  10721. Node.prototype.isEnabled = function () {
  10722. if (!this._isEnabled) {
  10723. return false;
  10724. }
  10725. if (this.parent) {
  10726. return this.parent.isEnabled();
  10727. }
  10728. return true;
  10729. };
  10730. /**
  10731. * Set the enabled state of this node.
  10732. * @param {boolean} value - the new enabled state
  10733. * @see isEnabled
  10734. */
  10735. Node.prototype.setEnabled = function (value) {
  10736. this._isEnabled = value;
  10737. };
  10738. /**
  10739. * Is this node a descendant of the given node.
  10740. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10741. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10742. * @see parent
  10743. */
  10744. Node.prototype.isDescendantOf = function (ancestor) {
  10745. if (this.parent) {
  10746. if (this.parent === ancestor) {
  10747. return true;
  10748. }
  10749. return this.parent.isDescendantOf(ancestor);
  10750. }
  10751. return false;
  10752. };
  10753. /**
  10754. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10755. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10756. * @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.
  10757. * @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.
  10758. */
  10759. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10760. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10761. if (!this._children) {
  10762. return;
  10763. }
  10764. for (var index = 0; index < this._children.length; index++) {
  10765. var item = this._children[index];
  10766. if (!predicate || predicate(item)) {
  10767. results.push(item);
  10768. }
  10769. if (!directDescendantsOnly) {
  10770. item._getDescendants(results, false, predicate);
  10771. }
  10772. }
  10773. };
  10774. /**
  10775. * Will return all nodes that have this node as ascendant.
  10776. * @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.
  10777. * @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.
  10778. * @return {BABYLON.Node[]} all children nodes of all types.
  10779. */
  10780. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10781. var results = [];
  10782. this._getDescendants(results, directDescendantsOnly, predicate);
  10783. return results;
  10784. };
  10785. /**
  10786. * Get all child-meshes of this node.
  10787. */
  10788. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10789. var results = [];
  10790. this._getDescendants(results, directDecendantsOnly, function (node) {
  10791. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10792. });
  10793. return results;
  10794. };
  10795. /**
  10796. * Get all direct children of this node.
  10797. */
  10798. Node.prototype.getChildren = function (predicate) {
  10799. return this.getDescendants(true, predicate);
  10800. };
  10801. Node.prototype._setReady = function (state) {
  10802. if (state === this._isReady) {
  10803. return;
  10804. }
  10805. if (!state) {
  10806. this._isReady = false;
  10807. return;
  10808. }
  10809. this._isReady = true;
  10810. if (this.onReady) {
  10811. this.onReady(this);
  10812. }
  10813. };
  10814. Node.prototype.getAnimationByName = function (name) {
  10815. for (var i = 0; i < this.animations.length; i++) {
  10816. var animation = this.animations[i];
  10817. if (animation.name === name) {
  10818. return animation;
  10819. }
  10820. }
  10821. return null;
  10822. };
  10823. Node.prototype.createAnimationRange = function (name, from, to) {
  10824. // check name not already in use
  10825. if (!this._ranges[name]) {
  10826. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10827. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10828. if (this.animations[i]) {
  10829. this.animations[i].createRange(name, from, to);
  10830. }
  10831. }
  10832. }
  10833. };
  10834. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10835. if (deleteFrames === void 0) { deleteFrames = true; }
  10836. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10837. if (this.animations[i]) {
  10838. this.animations[i].deleteRange(name, deleteFrames);
  10839. }
  10840. }
  10841. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10842. };
  10843. Node.prototype.getAnimationRange = function (name) {
  10844. return this._ranges[name];
  10845. };
  10846. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10847. var range = this.getAnimationRange(name);
  10848. if (!range) {
  10849. return null;
  10850. }
  10851. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10852. };
  10853. Node.prototype.serializeAnimationRanges = function () {
  10854. var serializationRanges = [];
  10855. for (var name in this._ranges) {
  10856. var range = {};
  10857. range.name = name;
  10858. range.from = this._ranges[name].from;
  10859. range.to = this._ranges[name].to;
  10860. serializationRanges.push(range);
  10861. }
  10862. return serializationRanges;
  10863. };
  10864. Node.prototype.dispose = function () {
  10865. this.parent = null;
  10866. // Callback
  10867. this.onDisposeObservable.notifyObservers(this);
  10868. this.onDisposeObservable.clear();
  10869. };
  10870. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10871. if (parsedNode.ranges) {
  10872. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10873. var data = parsedNode.ranges[index];
  10874. node.createAnimationRange(data.name, data.from, data.to);
  10875. }
  10876. }
  10877. };
  10878. return Node;
  10879. }());
  10880. __decorate([
  10881. BABYLON.serialize()
  10882. ], Node.prototype, "name", void 0);
  10883. __decorate([
  10884. BABYLON.serialize()
  10885. ], Node.prototype, "id", void 0);
  10886. __decorate([
  10887. BABYLON.serialize()
  10888. ], Node.prototype, "uniqueId", void 0);
  10889. __decorate([
  10890. BABYLON.serialize()
  10891. ], Node.prototype, "state", void 0);
  10892. __decorate([
  10893. BABYLON.serialize()
  10894. ], Node.prototype, "metadata", void 0);
  10895. BABYLON.Node = Node;
  10896. })(BABYLON || (BABYLON = {}));
  10897. //# sourceMappingURL=babylon.node.js.map
  10898. var BABYLON;
  10899. (function (BABYLON) {
  10900. var BoundingSphere = (function () {
  10901. function BoundingSphere(minimum, maximum) {
  10902. this.minimum = minimum;
  10903. this.maximum = maximum;
  10904. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10905. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10906. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10907. this.radius = distance * 0.5;
  10908. this.centerWorld = BABYLON.Vector3.Zero();
  10909. this._update(BABYLON.Matrix.Identity());
  10910. }
  10911. // Methods
  10912. BoundingSphere.prototype._update = function (world) {
  10913. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10914. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10915. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10916. };
  10917. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10918. for (var i = 0; i < 6; i++) {
  10919. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10920. return false;
  10921. }
  10922. return true;
  10923. };
  10924. BoundingSphere.prototype.intersectsPoint = function (point) {
  10925. var x = this.centerWorld.x - point.x;
  10926. var y = this.centerWorld.y - point.y;
  10927. var z = this.centerWorld.z - point.z;
  10928. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10929. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10930. return false;
  10931. return true;
  10932. };
  10933. // Statics
  10934. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10935. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10936. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10937. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10938. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10939. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10940. return false;
  10941. return true;
  10942. };
  10943. return BoundingSphere;
  10944. }());
  10945. BABYLON.BoundingSphere = BoundingSphere;
  10946. })(BABYLON || (BABYLON = {}));
  10947. //# sourceMappingURL=babylon.boundingSphere.js.map
  10948. var BABYLON;
  10949. (function (BABYLON) {
  10950. var BoundingBox = (function () {
  10951. function BoundingBox(minimum, maximum) {
  10952. this.minimum = minimum;
  10953. this.maximum = maximum;
  10954. this.vectors = new Array();
  10955. this.vectorsWorld = new Array();
  10956. // Bounding vectors
  10957. this.vectors.push(this.minimum.clone());
  10958. this.vectors.push(this.maximum.clone());
  10959. this.vectors.push(this.minimum.clone());
  10960. this.vectors[2].x = this.maximum.x;
  10961. this.vectors.push(this.minimum.clone());
  10962. this.vectors[3].y = this.maximum.y;
  10963. this.vectors.push(this.minimum.clone());
  10964. this.vectors[4].z = this.maximum.z;
  10965. this.vectors.push(this.maximum.clone());
  10966. this.vectors[5].z = this.minimum.z;
  10967. this.vectors.push(this.maximum.clone());
  10968. this.vectors[6].x = this.minimum.x;
  10969. this.vectors.push(this.maximum.clone());
  10970. this.vectors[7].y = this.minimum.y;
  10971. // OBB
  10972. this.center = this.maximum.add(this.minimum).scale(0.5);
  10973. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10974. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10975. // World
  10976. for (var index = 0; index < this.vectors.length; index++) {
  10977. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10978. }
  10979. this.minimumWorld = BABYLON.Vector3.Zero();
  10980. this.maximumWorld = BABYLON.Vector3.Zero();
  10981. this.centerWorld = BABYLON.Vector3.Zero();
  10982. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10983. this._update(BABYLON.Matrix.Identity());
  10984. }
  10985. // Methods
  10986. BoundingBox.prototype.getWorldMatrix = function () {
  10987. return this._worldMatrix;
  10988. };
  10989. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10990. this._worldMatrix.copyFrom(matrix);
  10991. return this;
  10992. };
  10993. BoundingBox.prototype._update = function (world) {
  10994. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10995. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10996. for (var index = 0; index < this.vectors.length; index++) {
  10997. var v = this.vectorsWorld[index];
  10998. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10999. if (v.x < this.minimumWorld.x)
  11000. this.minimumWorld.x = v.x;
  11001. if (v.y < this.minimumWorld.y)
  11002. this.minimumWorld.y = v.y;
  11003. if (v.z < this.minimumWorld.z)
  11004. this.minimumWorld.z = v.z;
  11005. if (v.x > this.maximumWorld.x)
  11006. this.maximumWorld.x = v.x;
  11007. if (v.y > this.maximumWorld.y)
  11008. this.maximumWorld.y = v.y;
  11009. if (v.z > this.maximumWorld.z)
  11010. this.maximumWorld.z = v.z;
  11011. }
  11012. // Extend
  11013. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11014. this.extendSizeWorld.scaleInPlace(0.5);
  11015. // OBB
  11016. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11017. this.centerWorld.scaleInPlace(0.5);
  11018. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11019. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11020. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11021. this._worldMatrix = world;
  11022. };
  11023. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11024. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11025. };
  11026. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11027. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11028. };
  11029. BoundingBox.prototype.intersectsPoint = function (point) {
  11030. var delta = -BABYLON.Epsilon;
  11031. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11032. return false;
  11033. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11034. return false;
  11035. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11036. return false;
  11037. return true;
  11038. };
  11039. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11040. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11041. };
  11042. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11043. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11044. return false;
  11045. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11046. return false;
  11047. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11048. return false;
  11049. return true;
  11050. };
  11051. // Statics
  11052. BoundingBox.Intersects = function (box0, box1) {
  11053. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11054. return false;
  11055. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11056. return false;
  11057. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11058. return false;
  11059. return true;
  11060. };
  11061. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11062. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11063. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11064. return (num <= (sphereRadius * sphereRadius));
  11065. };
  11066. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11067. for (var p = 0; p < 6; p++) {
  11068. for (var i = 0; i < 8; i++) {
  11069. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11070. return false;
  11071. }
  11072. }
  11073. }
  11074. return true;
  11075. };
  11076. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11077. for (var p = 0; p < 6; p++) {
  11078. var inCount = 8;
  11079. for (var i = 0; i < 8; i++) {
  11080. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11081. --inCount;
  11082. }
  11083. else {
  11084. break;
  11085. }
  11086. }
  11087. if (inCount === 0)
  11088. return false;
  11089. }
  11090. return true;
  11091. };
  11092. return BoundingBox;
  11093. }());
  11094. BABYLON.BoundingBox = BoundingBox;
  11095. })(BABYLON || (BABYLON = {}));
  11096. //# sourceMappingURL=babylon.boundingBox.js.map
  11097. var BABYLON;
  11098. (function (BABYLON) {
  11099. var computeBoxExtents = function (axis, box) {
  11100. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11101. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11102. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11103. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11104. var r = r0 + r1 + r2;
  11105. return {
  11106. min: p - r,
  11107. max: p + r
  11108. };
  11109. };
  11110. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11111. var axisOverlap = function (axis, box0, box1) {
  11112. var result0 = computeBoxExtents(axis, box0);
  11113. var result1 = computeBoxExtents(axis, box1);
  11114. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11115. };
  11116. var BoundingInfo = (function () {
  11117. function BoundingInfo(minimum, maximum) {
  11118. this.minimum = minimum;
  11119. this.maximum = maximum;
  11120. this._isLocked = false;
  11121. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11122. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11123. }
  11124. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11125. get: function () {
  11126. return this._isLocked;
  11127. },
  11128. set: function (value) {
  11129. this._isLocked = value;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. // Methods
  11135. BoundingInfo.prototype.update = function (world) {
  11136. if (this._isLocked) {
  11137. return;
  11138. }
  11139. this.boundingBox._update(world);
  11140. this.boundingSphere._update(world);
  11141. };
  11142. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11143. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11144. return false;
  11145. return this.boundingBox.isInFrustum(frustumPlanes);
  11146. };
  11147. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11148. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11149. };
  11150. BoundingInfo.prototype._checkCollision = function (collider) {
  11151. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11152. };
  11153. BoundingInfo.prototype.intersectsPoint = function (point) {
  11154. if (!this.boundingSphere.centerWorld) {
  11155. return false;
  11156. }
  11157. if (!this.boundingSphere.intersectsPoint(point)) {
  11158. return false;
  11159. }
  11160. if (!this.boundingBox.intersectsPoint(point)) {
  11161. return false;
  11162. }
  11163. return true;
  11164. };
  11165. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11166. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11167. return false;
  11168. }
  11169. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11170. return false;
  11171. }
  11172. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11173. return false;
  11174. }
  11175. if (!precise) {
  11176. return true;
  11177. }
  11178. var box0 = this.boundingBox;
  11179. var box1 = boundingInfo.boundingBox;
  11180. if (!axisOverlap(box0.directions[0], box0, box1))
  11181. return false;
  11182. if (!axisOverlap(box0.directions[1], box0, box1))
  11183. return false;
  11184. if (!axisOverlap(box0.directions[2], box0, box1))
  11185. return false;
  11186. if (!axisOverlap(box1.directions[0], box0, box1))
  11187. return false;
  11188. if (!axisOverlap(box1.directions[1], box0, box1))
  11189. return false;
  11190. if (!axisOverlap(box1.directions[2], box0, box1))
  11191. return false;
  11192. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11193. return false;
  11194. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11195. return false;
  11196. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11197. return false;
  11198. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11199. return false;
  11200. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11201. return false;
  11202. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11203. return false;
  11204. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11205. return false;
  11206. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11207. return false;
  11208. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11209. return false;
  11210. return true;
  11211. };
  11212. return BoundingInfo;
  11213. }());
  11214. BABYLON.BoundingInfo = BoundingInfo;
  11215. })(BABYLON || (BABYLON = {}));
  11216. //# sourceMappingURL=babylon.boundingInfo.js.map
  11217. var BABYLON;
  11218. (function (BABYLON) {
  11219. var AbstractMesh = (function (_super) {
  11220. __extends(AbstractMesh, _super);
  11221. // Constructor
  11222. function AbstractMesh(name, scene) {
  11223. var _this = _super.call(this, name, scene) || this;
  11224. _this._facetNb = 0; // facet number
  11225. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11226. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11227. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11228. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11229. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11230. _this._subDiv = {
  11231. max: 1,
  11232. X: 1,
  11233. Y: 1,
  11234. Z: 1
  11235. };
  11236. // Events
  11237. /**
  11238. * An event triggered when this mesh collides with another one
  11239. * @type {BABYLON.Observable}
  11240. */
  11241. _this.onCollideObservable = new BABYLON.Observable();
  11242. /**
  11243. * An event triggered when the collision's position changes
  11244. * @type {BABYLON.Observable}
  11245. */
  11246. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11247. /**
  11248. * An event triggered after the world matrix is updated
  11249. * @type {BABYLON.Observable}
  11250. */
  11251. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11252. // Properties
  11253. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11254. _this.position = BABYLON.Vector3.Zero();
  11255. _this._rotation = BABYLON.Vector3.Zero();
  11256. _this._scaling = BABYLON.Vector3.One();
  11257. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11258. _this.visibility = 1.0;
  11259. _this.alphaIndex = Number.MAX_VALUE;
  11260. _this.infiniteDistance = false;
  11261. _this.isVisible = true;
  11262. _this.isPickable = true;
  11263. _this.showBoundingBox = false;
  11264. _this.showSubMeshesBoundingBox = false;
  11265. _this.isBlocker = false;
  11266. _this.renderingGroupId = 0;
  11267. _this._receiveShadows = false;
  11268. _this.renderOutline = false;
  11269. _this.outlineColor = BABYLON.Color3.Red();
  11270. _this.outlineWidth = 0.02;
  11271. _this.renderOverlay = false;
  11272. _this.overlayColor = BABYLON.Color3.Red();
  11273. _this.overlayAlpha = 0.5;
  11274. _this._hasVertexAlpha = false;
  11275. _this._useVertexColors = true;
  11276. _this._computeBonesUsingShaders = true;
  11277. _this._numBoneInfluencers = 4;
  11278. _this._applyFog = true;
  11279. _this.scalingDeterminant = 1;
  11280. _this.useOctreeForRenderingSelection = true;
  11281. _this.useOctreeForPicking = true;
  11282. _this.useOctreeForCollisions = true;
  11283. _this.layerMask = 0x0FFFFFFF;
  11284. /**
  11285. * True if the mesh must be rendered in any case.
  11286. */
  11287. _this.alwaysSelectAsActiveMesh = false;
  11288. // Collisions
  11289. _this._checkCollisions = false;
  11290. _this._collisionMask = -1;
  11291. _this._collisionGroup = -1;
  11292. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11293. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11294. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11295. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11296. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11297. // Edges
  11298. _this.edgesWidth = 1;
  11299. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11300. // Cache
  11301. _this._localWorld = BABYLON.Matrix.Zero();
  11302. _this._worldMatrix = BABYLON.Matrix.Zero();
  11303. _this._absolutePosition = BABYLON.Vector3.Zero();
  11304. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11305. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11306. _this._isDirty = false;
  11307. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11308. _this._isDisposed = false;
  11309. _this._renderId = 0;
  11310. _this._intersectionsInProgress = new Array();
  11311. _this._isWorldMatrixFrozen = false;
  11312. _this._unIndexed = false;
  11313. _this._lightSources = new Array();
  11314. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11315. if (collidedMesh === void 0) { collidedMesh = null; }
  11316. //TODO move this to the collision coordinator!
  11317. if (_this.getScene().workerCollisions)
  11318. newPosition.multiplyInPlace(_this._collider.radius);
  11319. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11320. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11321. _this.position.addInPlace(_this._diffPositionForCollisions);
  11322. }
  11323. if (collidedMesh) {
  11324. _this.onCollideObservable.notifyObservers(collidedMesh);
  11325. }
  11326. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11327. };
  11328. _this.getScene().addMesh(_this);
  11329. _this._resyncLightSources();
  11330. return _this;
  11331. }
  11332. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11333. get: function () {
  11334. return AbstractMesh._BILLBOARDMODE_NONE;
  11335. },
  11336. enumerable: true,
  11337. configurable: true
  11338. });
  11339. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11340. get: function () {
  11341. return AbstractMesh._BILLBOARDMODE_X;
  11342. },
  11343. enumerable: true,
  11344. configurable: true
  11345. });
  11346. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11347. get: function () {
  11348. return AbstractMesh._BILLBOARDMODE_Y;
  11349. },
  11350. enumerable: true,
  11351. configurable: true
  11352. });
  11353. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11354. get: function () {
  11355. return AbstractMesh._BILLBOARDMODE_Z;
  11356. },
  11357. enumerable: true,
  11358. configurable: true
  11359. });
  11360. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11361. get: function () {
  11362. return AbstractMesh._BILLBOARDMODE_ALL;
  11363. },
  11364. enumerable: true,
  11365. configurable: true
  11366. });
  11367. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11368. /**
  11369. * Read-only : the number of facets in the mesh
  11370. */
  11371. get: function () {
  11372. return this._facetNb;
  11373. },
  11374. enumerable: true,
  11375. configurable: true
  11376. });
  11377. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11378. /**
  11379. * The number (integer) of subdivisions per axis in the partioning space
  11380. */
  11381. get: function () {
  11382. return this._partitioningSubdivisions;
  11383. },
  11384. set: function (nb) {
  11385. this._partitioningSubdivisions = nb;
  11386. },
  11387. enumerable: true,
  11388. configurable: true
  11389. });
  11390. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11391. /**
  11392. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11393. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11394. */
  11395. get: function () {
  11396. return this._partitioningBBoxRatio;
  11397. },
  11398. set: function (ratio) {
  11399. this._partitioningBBoxRatio = ratio;
  11400. },
  11401. enumerable: true,
  11402. configurable: true
  11403. });
  11404. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11405. /**
  11406. * Read-only boolean : is the feature facetData enabled ?
  11407. */
  11408. get: function () {
  11409. return this._facetDataEnabled;
  11410. },
  11411. enumerable: true,
  11412. configurable: true
  11413. });
  11414. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11415. set: function (callback) {
  11416. if (this._onCollideObserver) {
  11417. this.onCollideObservable.remove(this._onCollideObserver);
  11418. }
  11419. this._onCollideObserver = this.onCollideObservable.add(callback);
  11420. },
  11421. enumerable: true,
  11422. configurable: true
  11423. });
  11424. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11425. set: function (callback) {
  11426. if (this._onCollisionPositionChangeObserver) {
  11427. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11428. }
  11429. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11430. },
  11431. enumerable: true,
  11432. configurable: true
  11433. });
  11434. Object.defineProperty(AbstractMesh.prototype, "material", {
  11435. get: function () {
  11436. return this._material;
  11437. },
  11438. set: function (value) {
  11439. if (this._material === value) {
  11440. return;
  11441. }
  11442. this._material = value;
  11443. if (!this.subMeshes) {
  11444. return;
  11445. }
  11446. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11447. var subMesh = _a[_i];
  11448. subMesh.setEffect(null);
  11449. }
  11450. },
  11451. enumerable: true,
  11452. configurable: true
  11453. });
  11454. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11455. get: function () {
  11456. return this._receiveShadows;
  11457. },
  11458. set: function (value) {
  11459. if (this._receiveShadows === value) {
  11460. return;
  11461. }
  11462. this._receiveShadows = value;
  11463. this._markSubMeshesAsLightDirty();
  11464. },
  11465. enumerable: true,
  11466. configurable: true
  11467. });
  11468. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11469. get: function () {
  11470. return this._hasVertexAlpha;
  11471. },
  11472. set: function (value) {
  11473. if (this._hasVertexAlpha === value) {
  11474. return;
  11475. }
  11476. this._hasVertexAlpha = value;
  11477. this._markSubMeshesAsAttributesDirty();
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11483. get: function () {
  11484. return this._useVertexColors;
  11485. },
  11486. set: function (value) {
  11487. if (this._useVertexColors === value) {
  11488. return;
  11489. }
  11490. this._useVertexColors = value;
  11491. this._markSubMeshesAsAttributesDirty();
  11492. },
  11493. enumerable: true,
  11494. configurable: true
  11495. });
  11496. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11497. get: function () {
  11498. return this._computeBonesUsingShaders;
  11499. },
  11500. set: function (value) {
  11501. if (this._computeBonesUsingShaders === value) {
  11502. return;
  11503. }
  11504. this._computeBonesUsingShaders = value;
  11505. this._markSubMeshesAsAttributesDirty();
  11506. },
  11507. enumerable: true,
  11508. configurable: true
  11509. });
  11510. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11511. get: function () {
  11512. return this._numBoneInfluencers;
  11513. },
  11514. set: function (value) {
  11515. if (this._numBoneInfluencers === value) {
  11516. return;
  11517. }
  11518. this._numBoneInfluencers = value;
  11519. this._markSubMeshesAsAttributesDirty();
  11520. },
  11521. enumerable: true,
  11522. configurable: true
  11523. });
  11524. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11525. get: function () {
  11526. return this._applyFog;
  11527. },
  11528. set: function (value) {
  11529. if (this._applyFog === value) {
  11530. return;
  11531. }
  11532. this._applyFog = value;
  11533. this._markSubMeshesAsMiscDirty();
  11534. },
  11535. enumerable: true,
  11536. configurable: true
  11537. });
  11538. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11539. get: function () {
  11540. return this._collisionMask;
  11541. },
  11542. set: function (mask) {
  11543. this._collisionMask = !isNaN(mask) ? mask : -1;
  11544. },
  11545. enumerable: true,
  11546. configurable: true
  11547. });
  11548. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11549. get: function () {
  11550. return this._collisionGroup;
  11551. },
  11552. set: function (mask) {
  11553. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11554. },
  11555. enumerable: true,
  11556. configurable: true
  11557. });
  11558. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11559. get: function () {
  11560. return null;
  11561. },
  11562. enumerable: true,
  11563. configurable: true
  11564. });
  11565. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11566. get: function () {
  11567. return this._skeleton;
  11568. },
  11569. set: function (value) {
  11570. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11571. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11572. }
  11573. if (value && value.needInitialSkinMatrix) {
  11574. value._registerMeshWithPoseMatrix(this);
  11575. }
  11576. this._skeleton = value;
  11577. if (!this._skeleton) {
  11578. this._bonesTransformMatrices = null;
  11579. }
  11580. this._markSubMeshesAsAttributesDirty();
  11581. },
  11582. enumerable: true,
  11583. configurable: true
  11584. });
  11585. /**
  11586. * Returns the string "AbstractMesh"
  11587. */
  11588. AbstractMesh.prototype.getClassName = function () {
  11589. return "AbstractMesh";
  11590. };
  11591. /**
  11592. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11593. */
  11594. AbstractMesh.prototype.toString = function (fullDetails) {
  11595. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11596. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11597. if (this._skeleton) {
  11598. ret += ", skeleton: " + this._skeleton.name;
  11599. }
  11600. if (fullDetails) {
  11601. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11602. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11603. }
  11604. return ret;
  11605. };
  11606. AbstractMesh.prototype._resyncLightSources = function () {
  11607. this._lightSources.length = 0;
  11608. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11609. var light = _a[_i];
  11610. if (!light.isEnabled()) {
  11611. continue;
  11612. }
  11613. if (light.canAffectMesh(this)) {
  11614. this._lightSources.push(light);
  11615. }
  11616. }
  11617. this._markSubMeshesAsLightDirty();
  11618. };
  11619. AbstractMesh.prototype._resyncLighSource = function (light) {
  11620. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11621. var index = this._lightSources.indexOf(light);
  11622. if (index === -1) {
  11623. if (!isIn) {
  11624. return;
  11625. }
  11626. this._lightSources.push(light);
  11627. }
  11628. else {
  11629. if (isIn) {
  11630. return;
  11631. }
  11632. this._lightSources.splice(index, 1);
  11633. }
  11634. this._markSubMeshesAsLightDirty();
  11635. };
  11636. AbstractMesh.prototype._removeLightSource = function (light) {
  11637. var index = this._lightSources.indexOf(light);
  11638. if (index === -1) {
  11639. return;
  11640. }
  11641. this._lightSources.splice(index, 1);
  11642. };
  11643. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11644. if (!this.subMeshes) {
  11645. return;
  11646. }
  11647. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11648. var subMesh = _a[_i];
  11649. if (subMesh._materialDefines) {
  11650. func(subMesh._materialDefines);
  11651. }
  11652. }
  11653. };
  11654. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11655. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11656. };
  11657. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11658. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11659. };
  11660. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11661. if (!this.subMeshes) {
  11662. return;
  11663. }
  11664. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11665. var subMesh = _a[_i];
  11666. var material = subMesh.getMaterial();
  11667. if (material) {
  11668. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11669. }
  11670. }
  11671. };
  11672. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11673. /**
  11674. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11675. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11676. * Default : (0.0, 0.0, 0.0)
  11677. */
  11678. get: function () {
  11679. return this._rotation;
  11680. },
  11681. set: function (newRotation) {
  11682. this._rotation = newRotation;
  11683. },
  11684. enumerable: true,
  11685. configurable: true
  11686. });
  11687. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11688. /**
  11689. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11690. * Default : (1.0, 1.0, 1.0)
  11691. */
  11692. get: function () {
  11693. return this._scaling;
  11694. },
  11695. set: function (newScaling) {
  11696. this._scaling = newScaling;
  11697. if (this.physicsImpostor) {
  11698. this.physicsImpostor.forceUpdate();
  11699. }
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11705. /**
  11706. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11707. * It's null by default.
  11708. * 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)
  11709. */
  11710. get: function () {
  11711. return this._rotationQuaternion;
  11712. },
  11713. set: function (quaternion) {
  11714. this._rotationQuaternion = quaternion;
  11715. //reset the rotation vector.
  11716. if (quaternion && this.rotation.length()) {
  11717. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11718. }
  11719. },
  11720. enumerable: true,
  11721. configurable: true
  11722. });
  11723. // Methods
  11724. /**
  11725. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11726. * Returns the AbstractMesh.
  11727. */
  11728. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11729. this._poseMatrix.copyFrom(matrix);
  11730. return this;
  11731. };
  11732. /**
  11733. * Returns the mesh Pose matrix.
  11734. * Returned object : Matrix
  11735. */
  11736. AbstractMesh.prototype.getPoseMatrix = function () {
  11737. return this._poseMatrix;
  11738. };
  11739. /**
  11740. * Disables the mesh edger rendering mode.
  11741. * Returns the AbstractMesh.
  11742. */
  11743. AbstractMesh.prototype.disableEdgesRendering = function () {
  11744. if (this._edgesRenderer !== undefined) {
  11745. this._edgesRenderer.dispose();
  11746. this._edgesRenderer = undefined;
  11747. }
  11748. return this;
  11749. };
  11750. /**
  11751. * Enables the edge rendering mode on the mesh.
  11752. * This mode makes the mesh edges visible.
  11753. * Returns the AbstractMesh.
  11754. */
  11755. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11756. if (epsilon === void 0) { epsilon = 0.95; }
  11757. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11758. this.disableEdgesRendering();
  11759. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11760. return this;
  11761. };
  11762. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11763. /**
  11764. * Returns true if the mesh is blocked. Used by the class Mesh.
  11765. * Returns the boolean `false` by default.
  11766. */
  11767. get: function () {
  11768. return false;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. /**
  11774. * Returns the mesh itself by default, used by the class Mesh.
  11775. * Returned type : AbstractMesh
  11776. */
  11777. AbstractMesh.prototype.getLOD = function (camera) {
  11778. return this;
  11779. };
  11780. /**
  11781. * Returns 0 by default, used by the class Mesh.
  11782. * Returns an integer.
  11783. */
  11784. AbstractMesh.prototype.getTotalVertices = function () {
  11785. return 0;
  11786. };
  11787. /**
  11788. * Returns null by default, used by the class Mesh.
  11789. * Returned type : integer array
  11790. */
  11791. AbstractMesh.prototype.getIndices = function () {
  11792. return null;
  11793. };
  11794. /**
  11795. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11796. * Returned type : float array or Float32Array
  11797. */
  11798. AbstractMesh.prototype.getVerticesData = function (kind) {
  11799. return null;
  11800. };
  11801. /**
  11802. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11803. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11804. * The `data` are either a numeric array either a Float32Array.
  11805. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11806. * 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).
  11807. * Note that a new underlying VertexBuffer object is created each call.
  11808. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11809. *
  11810. * Possible `kind` values :
  11811. * - BABYLON.VertexBuffer.PositionKind
  11812. * - BABYLON.VertexBuffer.UVKind
  11813. * - BABYLON.VertexBuffer.UV2Kind
  11814. * - BABYLON.VertexBuffer.UV3Kind
  11815. * - BABYLON.VertexBuffer.UV4Kind
  11816. * - BABYLON.VertexBuffer.UV5Kind
  11817. * - BABYLON.VertexBuffer.UV6Kind
  11818. * - BABYLON.VertexBuffer.ColorKind
  11819. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11820. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11821. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11822. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11823. *
  11824. * Returns the Mesh.
  11825. */
  11826. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11827. return null;
  11828. };
  11829. /**
  11830. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11831. * If the mesh has no geometry, it is simply returned as it is.
  11832. * The `data` are either a numeric array either a Float32Array.
  11833. * No new underlying VertexBuffer object is created.
  11834. * 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.
  11835. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11836. *
  11837. * Possible `kind` values :
  11838. * - BABYLON.VertexBuffer.PositionKind
  11839. * - BABYLON.VertexBuffer.UVKind
  11840. * - BABYLON.VertexBuffer.UV2Kind
  11841. * - BABYLON.VertexBuffer.UV3Kind
  11842. * - BABYLON.VertexBuffer.UV4Kind
  11843. * - BABYLON.VertexBuffer.UV5Kind
  11844. * - BABYLON.VertexBuffer.UV6Kind
  11845. * - BABYLON.VertexBuffer.ColorKind
  11846. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11847. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11848. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11849. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11850. *
  11851. * Returns the Mesh.
  11852. */
  11853. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11854. return null;
  11855. };
  11856. /**
  11857. * Sets the mesh indices.
  11858. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11859. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11860. * This method creates a new index buffer each call.
  11861. * Returns the Mesh.
  11862. */
  11863. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11864. return null;
  11865. };
  11866. /** Returns false by default, used by the class Mesh.
  11867. * Returns a boolean
  11868. */
  11869. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11870. return false;
  11871. };
  11872. /**
  11873. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11874. * Returns a BoundingInfo
  11875. */
  11876. AbstractMesh.prototype.getBoundingInfo = function () {
  11877. if (this._masterMesh) {
  11878. return this._masterMesh.getBoundingInfo();
  11879. }
  11880. if (!this._boundingInfo) {
  11881. this._updateBoundingInfo();
  11882. }
  11883. return this._boundingInfo;
  11884. };
  11885. /**
  11886. * Sets a mesh new object BoundingInfo.
  11887. * Returns the AbstractMesh.
  11888. */
  11889. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11890. this._boundingInfo = boundingInfo;
  11891. return this;
  11892. };
  11893. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11894. get: function () {
  11895. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. AbstractMesh.prototype._preActivate = function () {
  11901. };
  11902. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11903. };
  11904. AbstractMesh.prototype._activate = function (renderId) {
  11905. this._renderId = renderId;
  11906. };
  11907. /**
  11908. * Returns the last update of the World matrix
  11909. * Returns a Matrix.
  11910. */
  11911. AbstractMesh.prototype.getWorldMatrix = function () {
  11912. if (this._masterMesh) {
  11913. return this._masterMesh.getWorldMatrix();
  11914. }
  11915. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11916. this.computeWorldMatrix();
  11917. }
  11918. return this._worldMatrix;
  11919. };
  11920. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11921. /**
  11922. * Returns directly the last state of the mesh World matrix.
  11923. * A Matrix is returned.
  11924. */
  11925. get: function () {
  11926. return this._worldMatrix;
  11927. },
  11928. enumerable: true,
  11929. configurable: true
  11930. });
  11931. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11932. /**
  11933. * Returns the current mesh absolute position.
  11934. * Retuns a Vector3.
  11935. */
  11936. get: function () {
  11937. return this._absolutePosition;
  11938. },
  11939. enumerable: true,
  11940. configurable: true
  11941. });
  11942. /**
  11943. * Prevents the World matrix to be computed any longer.
  11944. * Returns the AbstractMesh.
  11945. */
  11946. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11947. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11948. this.computeWorldMatrix(true);
  11949. this._isWorldMatrixFrozen = true;
  11950. return this;
  11951. };
  11952. /**
  11953. * Allows back the World matrix computation.
  11954. * Returns the AbstractMesh.
  11955. */
  11956. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11957. this._isWorldMatrixFrozen = false;
  11958. this.computeWorldMatrix(true);
  11959. return this;
  11960. };
  11961. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11962. /**
  11963. * True if the World matrix has been frozen.
  11964. * Returns a boolean.
  11965. */
  11966. get: function () {
  11967. return this._isWorldMatrixFrozen;
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. /**
  11973. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11974. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11975. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11976. * The passed axis is also normalized.
  11977. * Returns the AbstractMesh.
  11978. */
  11979. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11980. axis.normalize();
  11981. if (!this.rotationQuaternion) {
  11982. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11983. this.rotation = BABYLON.Vector3.Zero();
  11984. }
  11985. var rotationQuaternion;
  11986. if (!space || space === BABYLON.Space.LOCAL) {
  11987. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11988. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11989. }
  11990. else {
  11991. if (this.parent) {
  11992. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11993. invertParentWorldMatrix.invert();
  11994. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11995. }
  11996. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11997. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11998. }
  11999. return this;
  12000. };
  12001. /**
  12002. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12003. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12004. * The passed axis is also normalized.
  12005. * Returns the AbstractMesh.
  12006. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12007. */
  12008. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12009. axis.normalize();
  12010. if (!this.rotationQuaternion) {
  12011. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12012. this.rotation.copyFromFloats(0, 0, 0);
  12013. }
  12014. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12015. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12016. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12017. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12018. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12019. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12020. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12021. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12022. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  12023. return this;
  12024. };
  12025. /**
  12026. * Translates the mesh along the axis vector for the passed distance in the given space.
  12027. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12028. * Returns the AbstractMesh.
  12029. */
  12030. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12031. var displacementVector = axis.scale(distance);
  12032. if (!space || space === BABYLON.Space.LOCAL) {
  12033. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12034. this.setPositionWithLocalVector(tempV3);
  12035. }
  12036. else {
  12037. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12038. }
  12039. return this;
  12040. };
  12041. /**
  12042. * Adds a rotation step to the mesh current rotation.
  12043. * x, y, z are Euler angles expressed in radians.
  12044. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12045. * This means this rotation is made in the mesh local space only.
  12046. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12047. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12048. * ```javascript
  12049. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12050. * ```
  12051. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12052. * 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.
  12053. * Returns the AbstractMesh.
  12054. */
  12055. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12056. var rotationQuaternion;
  12057. if (this.rotationQuaternion) {
  12058. rotationQuaternion = this.rotationQuaternion;
  12059. }
  12060. else {
  12061. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12062. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12063. }
  12064. var accumulation = BABYLON.Tmp.Quaternion[0];
  12065. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12066. rotationQuaternion.multiplyInPlace(accumulation);
  12067. if (!this.rotationQuaternion) {
  12068. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12069. }
  12070. return this;
  12071. };
  12072. /**
  12073. * Retuns the mesh absolute position in the World.
  12074. * Returns a Vector3.
  12075. */
  12076. AbstractMesh.prototype.getAbsolutePosition = function () {
  12077. this.computeWorldMatrix();
  12078. return this._absolutePosition;
  12079. };
  12080. /**
  12081. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12082. * Returns the AbstractMesh.
  12083. */
  12084. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12085. if (!absolutePosition) {
  12086. return;
  12087. }
  12088. var absolutePositionX;
  12089. var absolutePositionY;
  12090. var absolutePositionZ;
  12091. if (absolutePosition.x === undefined) {
  12092. if (arguments.length < 3) {
  12093. return;
  12094. }
  12095. absolutePositionX = arguments[0];
  12096. absolutePositionY = arguments[1];
  12097. absolutePositionZ = arguments[2];
  12098. }
  12099. else {
  12100. absolutePositionX = absolutePosition.x;
  12101. absolutePositionY = absolutePosition.y;
  12102. absolutePositionZ = absolutePosition.z;
  12103. }
  12104. if (this.parent) {
  12105. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12106. invertParentWorldMatrix.invert();
  12107. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12108. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12109. }
  12110. else {
  12111. this.position.x = absolutePositionX;
  12112. this.position.y = absolutePositionY;
  12113. this.position.z = absolutePositionZ;
  12114. }
  12115. return this;
  12116. };
  12117. // ================================== Point of View Movement =================================
  12118. /**
  12119. * Perform relative position change from the point of view of behind the front of the mesh.
  12120. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12121. * Supports definition of mesh facing forward or backward.
  12122. * @param {number} amountRight
  12123. * @param {number} amountUp
  12124. * @param {number} amountForward
  12125. *
  12126. * Returns the AbstractMesh.
  12127. */
  12128. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12129. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12130. return this;
  12131. };
  12132. /**
  12133. * Calculate relative position change from the point of view of behind the front of the mesh.
  12134. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12135. * Supports definition of mesh facing forward or backward.
  12136. * @param {number} amountRight
  12137. * @param {number} amountUp
  12138. * @param {number} amountForward
  12139. *
  12140. * Returns a new Vector3.
  12141. */
  12142. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12143. var rotMatrix = new BABYLON.Matrix();
  12144. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12145. rotQuaternion.toRotationMatrix(rotMatrix);
  12146. var translationDelta = BABYLON.Vector3.Zero();
  12147. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12148. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12149. return translationDelta;
  12150. };
  12151. // ================================== Point of View Rotation =================================
  12152. /**
  12153. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12154. * Supports definition of mesh facing forward or backward.
  12155. * @param {number} flipBack
  12156. * @param {number} twirlClockwise
  12157. * @param {number} tiltRight
  12158. *
  12159. * Returns the AbstractMesh.
  12160. */
  12161. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12162. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12163. return this;
  12164. };
  12165. /**
  12166. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12167. * Supports definition of mesh facing forward or backward.
  12168. * @param {number} flipBack
  12169. * @param {number} twirlClockwise
  12170. * @param {number} tiltRight
  12171. *
  12172. * Returns a new Vector3.
  12173. */
  12174. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12175. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12176. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12177. };
  12178. /**
  12179. * Sets a new pivot matrix to the mesh.
  12180. * Returns the AbstractMesh.
  12181. */
  12182. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12183. this._pivotMatrix = matrix;
  12184. this._cache.pivotMatrixUpdated = true;
  12185. return this;
  12186. };
  12187. /**
  12188. * Returns the mesh pivot matrix.
  12189. * Default : Identity.
  12190. * A Matrix is returned.
  12191. */
  12192. AbstractMesh.prototype.getPivotMatrix = function () {
  12193. return this._pivotMatrix;
  12194. };
  12195. AbstractMesh.prototype._isSynchronized = function () {
  12196. if (this._isDirty) {
  12197. return false;
  12198. }
  12199. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12200. return false;
  12201. if (this._cache.pivotMatrixUpdated) {
  12202. return false;
  12203. }
  12204. if (this.infiniteDistance) {
  12205. return false;
  12206. }
  12207. if (!this._cache.position.equals(this.position))
  12208. return false;
  12209. if (this.rotationQuaternion) {
  12210. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12211. return false;
  12212. }
  12213. if (!this._cache.rotation.equals(this.rotation))
  12214. return false;
  12215. if (!this._cache.scaling.equals(this.scaling))
  12216. return false;
  12217. return true;
  12218. };
  12219. AbstractMesh.prototype._initCache = function () {
  12220. _super.prototype._initCache.call(this);
  12221. this._cache.localMatrixUpdated = false;
  12222. this._cache.position = BABYLON.Vector3.Zero();
  12223. this._cache.scaling = BABYLON.Vector3.Zero();
  12224. this._cache.rotation = BABYLON.Vector3.Zero();
  12225. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12226. this._cache.billboardMode = -1;
  12227. };
  12228. AbstractMesh.prototype.markAsDirty = function (property) {
  12229. if (property === "rotation") {
  12230. this.rotationQuaternion = null;
  12231. }
  12232. this._currentRenderId = Number.MAX_VALUE;
  12233. this._isDirty = true;
  12234. return this;
  12235. };
  12236. /**
  12237. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12238. * Returns the AbstractMesh.
  12239. */
  12240. AbstractMesh.prototype._updateBoundingInfo = function () {
  12241. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12242. this._boundingInfo.update(this.worldMatrixFromCache);
  12243. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12244. return this;
  12245. };
  12246. /**
  12247. * Update a mesh's children BoundingInfo objects only.
  12248. * Returns the AbstractMesh.
  12249. */
  12250. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12251. if (!this.subMeshes) {
  12252. return;
  12253. }
  12254. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12255. var subMesh = this.subMeshes[subIndex];
  12256. if (!subMesh.IsGlobal) {
  12257. subMesh.updateBoundingInfo(matrix);
  12258. }
  12259. }
  12260. return this;
  12261. };
  12262. /**
  12263. * Computes the mesh World matrix and returns it.
  12264. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12265. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12266. * If the parameter `force`is set to `true`, the actual computation is done.
  12267. * Returns the mesh World Matrix.
  12268. */
  12269. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12270. if (this._isWorldMatrixFrozen) {
  12271. return this._worldMatrix;
  12272. }
  12273. if (!force && this.isSynchronized(true)) {
  12274. this._currentRenderId = this.getScene().getRenderId();
  12275. return this._worldMatrix;
  12276. }
  12277. this._cache.position.copyFrom(this.position);
  12278. this._cache.scaling.copyFrom(this.scaling);
  12279. this._cache.pivotMatrixUpdated = false;
  12280. this._cache.billboardMode = this.billboardMode;
  12281. this._currentRenderId = this.getScene().getRenderId();
  12282. this._isDirty = false;
  12283. // Scaling
  12284. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12285. // Rotation
  12286. //rotate, if quaternion is set and rotation was used
  12287. if (this.rotationQuaternion) {
  12288. var len = this.rotation.length();
  12289. if (len) {
  12290. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12291. this.rotation.copyFromFloats(0, 0, 0);
  12292. }
  12293. }
  12294. if (this.rotationQuaternion) {
  12295. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12296. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12297. }
  12298. else {
  12299. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12300. this._cache.rotation.copyFrom(this.rotation);
  12301. }
  12302. // Translation
  12303. if (this.infiniteDistance && !this.parent) {
  12304. var camera = this.getScene().activeCamera;
  12305. if (camera) {
  12306. var cameraWorldMatrix = camera.getWorldMatrix();
  12307. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12308. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12309. }
  12310. }
  12311. else {
  12312. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12313. }
  12314. // Composing transformations
  12315. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12316. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12317. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12318. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12319. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12320. // Need to decompose each rotation here
  12321. var currentPosition = BABYLON.Tmp.Vector3[3];
  12322. if (this.parent && this.parent.getWorldMatrix) {
  12323. if (this._meshToBoneReferal) {
  12324. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12325. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12326. }
  12327. else {
  12328. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12329. }
  12330. }
  12331. else {
  12332. currentPosition.copyFrom(this.position);
  12333. }
  12334. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12335. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12336. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12337. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12338. }
  12339. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12340. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12341. }
  12342. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12343. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12344. }
  12345. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12346. }
  12347. else {
  12348. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12349. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12350. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12351. }
  12352. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12353. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12354. }
  12355. // Local world
  12356. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12357. // Parent
  12358. if (this.parent && this.parent.getWorldMatrix) {
  12359. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12360. if (this._meshToBoneReferal) {
  12361. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12362. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12363. }
  12364. else {
  12365. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12366. }
  12367. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12368. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12369. this._worldMatrix.copyFrom(this._localWorld);
  12370. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12371. }
  12372. else {
  12373. if (this._meshToBoneReferal) {
  12374. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12375. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12376. }
  12377. else {
  12378. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12379. }
  12380. }
  12381. this._markSyncedWithParent();
  12382. }
  12383. else {
  12384. this._worldMatrix.copyFrom(this._localWorld);
  12385. }
  12386. // Bounding info
  12387. this._updateBoundingInfo();
  12388. // Absolute position
  12389. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12390. // Callbacks
  12391. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12392. if (!this._poseMatrix) {
  12393. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12394. }
  12395. return this._worldMatrix;
  12396. };
  12397. /**
  12398. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12399. * @param func: callback function to add
  12400. *
  12401. * Returns the AbstractMesh.
  12402. */
  12403. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12404. this.onAfterWorldMatrixUpdateObservable.add(func);
  12405. return this;
  12406. };
  12407. /**
  12408. * Removes a registered callback function.
  12409. * Returns the AbstractMesh.
  12410. */
  12411. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12412. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12413. return this;
  12414. };
  12415. /**
  12416. * Sets the mesh position in its local space.
  12417. * Returns the AbstractMesh.
  12418. */
  12419. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12420. this.computeWorldMatrix();
  12421. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12422. return this;
  12423. };
  12424. /**
  12425. * Returns the mesh position in the local space from the current World matrix values.
  12426. * Returns a new Vector3.
  12427. */
  12428. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12429. this.computeWorldMatrix();
  12430. var invLocalWorldMatrix = this._localWorld.clone();
  12431. invLocalWorldMatrix.invert();
  12432. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12433. };
  12434. /**
  12435. * Translates the mesh along the passed Vector3 in its local space.
  12436. * Returns the AbstractMesh.
  12437. */
  12438. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12439. this.computeWorldMatrix(true);
  12440. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12441. return this;
  12442. };
  12443. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12444. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12445. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12446. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12447. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12448. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12449. /// <returns>Mesh oriented towards targetMesh</returns>
  12450. if (yawCor === void 0) { yawCor = 0; }
  12451. if (pitchCor === void 0) { pitchCor = 0; }
  12452. if (rollCor === void 0) { rollCor = 0; }
  12453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12454. var dv = AbstractMesh._lookAtVectorCache;
  12455. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12456. targetPoint.subtractToRef(pos, dv);
  12457. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12458. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12459. var pitch = Math.atan2(dv.y, len);
  12460. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12461. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12462. return this;
  12463. };
  12464. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12465. this._meshToBoneReferal = affectedMesh;
  12466. this.parent = bone;
  12467. if (bone.getWorldMatrix().determinant() < 0) {
  12468. this.scalingDeterminant *= -1;
  12469. }
  12470. return this;
  12471. };
  12472. AbstractMesh.prototype.detachFromBone = function () {
  12473. if (this.parent.getWorldMatrix().determinant() < 0) {
  12474. this.scalingDeterminant *= -1;
  12475. }
  12476. this._meshToBoneReferal = null;
  12477. this.parent = null;
  12478. return this;
  12479. };
  12480. /**
  12481. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12482. * A mesh is in the frustum if its bounding box intersects the frustum.
  12483. * Boolean returned.
  12484. */
  12485. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12486. return this._boundingInfo.isInFrustum(frustumPlanes);
  12487. };
  12488. /**
  12489. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12490. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12491. * Boolean returned.
  12492. */
  12493. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12494. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12495. ;
  12496. };
  12497. /**
  12498. * True if the mesh intersects another mesh or a SolidParticle object.
  12499. * 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)
  12500. * Returns a boolean.
  12501. */
  12502. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12503. if (!this._boundingInfo || !mesh._boundingInfo) {
  12504. return false;
  12505. }
  12506. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12507. };
  12508. /**
  12509. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12510. * Returns a boolean.
  12511. */
  12512. AbstractMesh.prototype.intersectsPoint = function (point) {
  12513. if (!this._boundingInfo) {
  12514. return false;
  12515. }
  12516. return this._boundingInfo.intersectsPoint(point);
  12517. };
  12518. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12519. return this.physicsImpostor;
  12520. };
  12521. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12522. if (!camera) {
  12523. camera = this.getScene().activeCamera;
  12524. }
  12525. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12526. };
  12527. /**
  12528. * Returns the distance from the mesh to the active camera.
  12529. * Returns a float.
  12530. */
  12531. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12532. if (!camera) {
  12533. camera = this.getScene().activeCamera;
  12534. }
  12535. return this.absolutePosition.subtract(camera.position).length();
  12536. };
  12537. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12538. if (!this.physicsImpostor) {
  12539. return;
  12540. }
  12541. this.physicsImpostor.applyImpulse(force, contactPoint);
  12542. return this;
  12543. };
  12544. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12545. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12546. return;
  12547. }
  12548. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12549. mainPivot: pivot1,
  12550. connectedPivot: pivot2,
  12551. nativeParams: options
  12552. });
  12553. return this;
  12554. };
  12555. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12556. // Collisions
  12557. /**
  12558. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12559. * Default `false`.
  12560. */
  12561. get: function () {
  12562. return this._checkCollisions;
  12563. },
  12564. set: function (collisionEnabled) {
  12565. this._checkCollisions = collisionEnabled;
  12566. if (this.getScene().workerCollisions) {
  12567. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12568. }
  12569. },
  12570. enumerable: true,
  12571. configurable: true
  12572. });
  12573. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12574. var globalPosition = this.getAbsolutePosition();
  12575. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12576. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12577. if (!this._collider) {
  12578. this._collider = new BABYLON.Collider();
  12579. }
  12580. this._collider.radius = this.ellipsoid;
  12581. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12582. return this;
  12583. };
  12584. // Submeshes octree
  12585. /**
  12586. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12587. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12588. * Returns an Octree of submeshes.
  12589. */
  12590. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12591. if (maxCapacity === void 0) { maxCapacity = 64; }
  12592. if (maxDepth === void 0) { maxDepth = 2; }
  12593. if (!this._submeshesOctree) {
  12594. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12595. }
  12596. this.computeWorldMatrix(true);
  12597. // Update octree
  12598. var bbox = this.getBoundingInfo().boundingBox;
  12599. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12600. return this._submeshesOctree;
  12601. };
  12602. // Collisions
  12603. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12604. this._generatePointsArray();
  12605. // Transformation
  12606. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12607. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12608. subMesh._lastColliderWorldVertices = [];
  12609. subMesh._trianglePlanes = [];
  12610. var start = subMesh.verticesStart;
  12611. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12612. for (var i = start; i < end; i++) {
  12613. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12614. }
  12615. }
  12616. // Collide
  12617. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12618. if (collider.collisionFound) {
  12619. collider.collidedMesh = this;
  12620. }
  12621. return this;
  12622. };
  12623. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12624. var subMeshes;
  12625. var len;
  12626. // Octrees
  12627. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12628. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12629. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12630. len = intersections.length;
  12631. subMeshes = intersections.data;
  12632. }
  12633. else {
  12634. subMeshes = this.subMeshes;
  12635. len = subMeshes.length;
  12636. }
  12637. for (var index = 0; index < len; index++) {
  12638. var subMesh = subMeshes[index];
  12639. // Bounding test
  12640. if (len > 1 && !subMesh._checkCollision(collider))
  12641. continue;
  12642. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12643. }
  12644. return this;
  12645. };
  12646. AbstractMesh.prototype._checkCollision = function (collider) {
  12647. // Bounding box test
  12648. if (!this._boundingInfo._checkCollision(collider))
  12649. return this;
  12650. // Transformation matrix
  12651. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12652. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12653. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12654. return this;
  12655. };
  12656. // Picking
  12657. AbstractMesh.prototype._generatePointsArray = function () {
  12658. return false;
  12659. };
  12660. /**
  12661. * Checks if the passed Ray intersects with the mesh.
  12662. * Returns an object PickingInfo.
  12663. */
  12664. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12665. var pickingInfo = new BABYLON.PickingInfo();
  12666. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12667. return pickingInfo;
  12668. }
  12669. if (!this._generatePointsArray()) {
  12670. return pickingInfo;
  12671. }
  12672. var intersectInfo = null;
  12673. // Octrees
  12674. var subMeshes;
  12675. var len;
  12676. if (this._submeshesOctree && this.useOctreeForPicking) {
  12677. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12678. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12679. len = intersections.length;
  12680. subMeshes = intersections.data;
  12681. }
  12682. else {
  12683. subMeshes = this.subMeshes;
  12684. len = subMeshes.length;
  12685. }
  12686. for (var index = 0; index < len; index++) {
  12687. var subMesh = subMeshes[index];
  12688. // Bounding test
  12689. if (len > 1 && !subMesh.canIntersects(ray))
  12690. continue;
  12691. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12692. if (currentIntersectInfo) {
  12693. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12694. intersectInfo = currentIntersectInfo;
  12695. intersectInfo.subMeshId = index;
  12696. if (fastCheck) {
  12697. break;
  12698. }
  12699. }
  12700. }
  12701. }
  12702. if (intersectInfo) {
  12703. // Get picked point
  12704. var world = this.getWorldMatrix();
  12705. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12706. var direction = ray.direction.clone();
  12707. direction = direction.scale(intersectInfo.distance);
  12708. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12709. var pickedPoint = worldOrigin.add(worldDirection);
  12710. // Return result
  12711. pickingInfo.hit = true;
  12712. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12713. pickingInfo.pickedPoint = pickedPoint;
  12714. pickingInfo.pickedMesh = this;
  12715. pickingInfo.bu = intersectInfo.bu;
  12716. pickingInfo.bv = intersectInfo.bv;
  12717. pickingInfo.faceId = intersectInfo.faceId;
  12718. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12719. return pickingInfo;
  12720. }
  12721. return pickingInfo;
  12722. };
  12723. /**
  12724. * Clones the mesh, used by the class Mesh.
  12725. * Just returns `null` for an AbstractMesh.
  12726. */
  12727. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12728. return null;
  12729. };
  12730. /**
  12731. * Disposes all the mesh submeshes.
  12732. * Returns the AbstractMesh.
  12733. */
  12734. AbstractMesh.prototype.releaseSubMeshes = function () {
  12735. if (this.subMeshes) {
  12736. while (this.subMeshes.length) {
  12737. this.subMeshes[0].dispose();
  12738. }
  12739. }
  12740. else {
  12741. this.subMeshes = new Array();
  12742. }
  12743. return this;
  12744. };
  12745. /**
  12746. * Disposes the AbstractMesh.
  12747. * Some internal references are kept for further use.
  12748. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12749. * Returns nothing.
  12750. */
  12751. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12752. var _this = this;
  12753. var index;
  12754. // Action manager
  12755. if (this.actionManager) {
  12756. this.actionManager.dispose();
  12757. this.actionManager = null;
  12758. }
  12759. // Skeleton
  12760. this.skeleton = null;
  12761. // Animations
  12762. this.getScene().stopAnimation(this);
  12763. // Physics
  12764. if (this.physicsImpostor) {
  12765. this.physicsImpostor.dispose();
  12766. }
  12767. // Intersections in progress
  12768. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12769. var other = this._intersectionsInProgress[index];
  12770. var pos = other._intersectionsInProgress.indexOf(this);
  12771. other._intersectionsInProgress.splice(pos, 1);
  12772. }
  12773. this._intersectionsInProgress = [];
  12774. // Lights
  12775. var lights = this.getScene().lights;
  12776. lights.forEach(function (light) {
  12777. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12778. if (meshIndex !== -1) {
  12779. light.includedOnlyMeshes.splice(meshIndex, 1);
  12780. }
  12781. meshIndex = light.excludedMeshes.indexOf(_this);
  12782. if (meshIndex !== -1) {
  12783. light.excludedMeshes.splice(meshIndex, 1);
  12784. }
  12785. // Shadow generators
  12786. var generator = light.getShadowGenerator();
  12787. if (generator) {
  12788. var shadowMap = generator.getShadowMap();
  12789. meshIndex = shadowMap.renderList.indexOf(_this);
  12790. if (meshIndex !== -1) {
  12791. shadowMap.renderList.splice(meshIndex, 1);
  12792. }
  12793. }
  12794. });
  12795. // Edges
  12796. if (this._edgesRenderer) {
  12797. this._edgesRenderer.dispose();
  12798. this._edgesRenderer = null;
  12799. }
  12800. // SubMeshes
  12801. if (this.getClassName() !== "InstancedMesh") {
  12802. this.releaseSubMeshes();
  12803. }
  12804. // Octree
  12805. var sceneOctree = this.getScene().selectionOctree;
  12806. if (sceneOctree) {
  12807. var index = sceneOctree.dynamicContent.indexOf(this);
  12808. if (index !== -1) {
  12809. sceneOctree.dynamicContent.splice(index, 1);
  12810. }
  12811. }
  12812. // Engine
  12813. this.getScene().getEngine().wipeCaches();
  12814. // Remove from scene
  12815. this.getScene().removeMesh(this);
  12816. if (!doNotRecurse) {
  12817. // Particles
  12818. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12819. if (this.getScene().particleSystems[index].emitter === this) {
  12820. this.getScene().particleSystems[index].dispose();
  12821. index--;
  12822. }
  12823. }
  12824. // Children
  12825. var objects = this.getDescendants(true);
  12826. for (index = 0; index < objects.length; index++) {
  12827. objects[index].dispose();
  12828. }
  12829. }
  12830. else {
  12831. var childMeshes = this.getChildMeshes(true);
  12832. for (index = 0; index < childMeshes.length; index++) {
  12833. var child = childMeshes[index];
  12834. child.parent = null;
  12835. child.computeWorldMatrix(true);
  12836. }
  12837. }
  12838. // facet data
  12839. if (this._facetDataEnabled) {
  12840. this.disableFacetData();
  12841. }
  12842. this.onAfterWorldMatrixUpdateObservable.clear();
  12843. this.onCollideObservable.clear();
  12844. this.onCollisionPositionChangeObservable.clear();
  12845. this._isDisposed = true;
  12846. _super.prototype.dispose.call(this);
  12847. };
  12848. /**
  12849. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12850. * This Vector3 is expressed in the World space.
  12851. */
  12852. AbstractMesh.prototype.getDirection = function (localAxis) {
  12853. var result = BABYLON.Vector3.Zero();
  12854. this.getDirectionToRef(localAxis, result);
  12855. return result;
  12856. };
  12857. /**
  12858. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12859. * localAxis is expressed in the mesh local space.
  12860. * result is computed in the Wordl space from the mesh World matrix.
  12861. * Returns the AbstractMesh.
  12862. */
  12863. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12864. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12865. return this;
  12866. };
  12867. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12868. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12869. if (this.getScene().getRenderId() == 0) {
  12870. this.computeWorldMatrix(true);
  12871. }
  12872. var wm = this.getWorldMatrix();
  12873. if (space == BABYLON.Space.WORLD) {
  12874. var tmat = BABYLON.Tmp.Matrix[0];
  12875. wm.invertToRef(tmat);
  12876. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12877. }
  12878. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12879. this._pivotMatrix.m[12] = -point.x;
  12880. this._pivotMatrix.m[13] = -point.y;
  12881. this._pivotMatrix.m[14] = -point.z;
  12882. this._cache.pivotMatrixUpdated = true;
  12883. return this;
  12884. };
  12885. /**
  12886. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12887. */
  12888. AbstractMesh.prototype.getPivotPoint = function () {
  12889. var point = BABYLON.Vector3.Zero();
  12890. this.getPivotPointToRef(point);
  12891. return point;
  12892. };
  12893. /**
  12894. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12895. * Returns the AbstractMesh.
  12896. */
  12897. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12898. result.x = -this._pivotMatrix.m[12];
  12899. result.y = -this._pivotMatrix.m[13];
  12900. result.z = -this._pivotMatrix.m[14];
  12901. return this;
  12902. };
  12903. /**
  12904. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12905. */
  12906. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12907. var point = BABYLON.Vector3.Zero();
  12908. this.getAbsolutePivotPointToRef(point);
  12909. return point;
  12910. };
  12911. /**
  12912. * Defines the passed mesh as the parent of the current mesh.
  12913. * Returns the AbstractMesh.
  12914. */
  12915. AbstractMesh.prototype.setParent = function (mesh) {
  12916. var child = this;
  12917. var parent = mesh;
  12918. if (mesh == null) {
  12919. var rotation = BABYLON.Tmp.Quaternion[0];
  12920. var position = BABYLON.Tmp.Vector3[0];
  12921. var scale = BABYLON.Tmp.Vector3[1];
  12922. child.getWorldMatrix().decompose(scale, rotation, position);
  12923. if (child.rotationQuaternion) {
  12924. child.rotationQuaternion.copyFrom(rotation);
  12925. }
  12926. else {
  12927. rotation.toEulerAnglesToRef(child.rotation);
  12928. }
  12929. child.position.x = position.x;
  12930. child.position.y = position.y;
  12931. child.position.z = position.z;
  12932. }
  12933. else {
  12934. var rotation = BABYLON.Tmp.Quaternion[0];
  12935. var position = BABYLON.Tmp.Vector3[0];
  12936. var scale = BABYLON.Tmp.Vector3[1];
  12937. var m1 = BABYLON.Tmp.Matrix[0];
  12938. var m2 = BABYLON.Tmp.Matrix[1];
  12939. parent.getWorldMatrix().decompose(scale, rotation, position);
  12940. rotation.toRotationMatrix(m1);
  12941. m2.setTranslation(position);
  12942. m2.multiplyToRef(m1, m1);
  12943. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12944. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12945. m.decompose(scale, rotation, position);
  12946. if (child.rotationQuaternion) {
  12947. child.rotationQuaternion.copyFrom(rotation);
  12948. }
  12949. else {
  12950. rotation.toEulerAnglesToRef(child.rotation);
  12951. }
  12952. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12953. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12954. m.decompose(scale, rotation, position);
  12955. child.position.x = position.x;
  12956. child.position.y = position.y;
  12957. child.position.z = position.z;
  12958. }
  12959. child.parent = parent;
  12960. return this;
  12961. };
  12962. /**
  12963. * Adds the passed mesh as a child to the current mesh.
  12964. * Returns the AbstractMesh.
  12965. */
  12966. AbstractMesh.prototype.addChild = function (mesh) {
  12967. mesh.setParent(this);
  12968. return this;
  12969. };
  12970. /**
  12971. * Removes the passed mesh from the current mesh children list.
  12972. * Returns the AbstractMesh.
  12973. */
  12974. AbstractMesh.prototype.removeChild = function (mesh) {
  12975. mesh.setParent(null);
  12976. return this;
  12977. };
  12978. /**
  12979. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12980. * Returns the AbstractMesh.
  12981. */
  12982. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12983. result.x = this._pivotMatrix.m[12];
  12984. result.y = this._pivotMatrix.m[13];
  12985. result.z = this._pivotMatrix.m[14];
  12986. this.getPivotPointToRef(result);
  12987. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12988. return this;
  12989. };
  12990. // Facet data
  12991. /**
  12992. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12993. * Returns the AbstractMesh.
  12994. */
  12995. AbstractMesh.prototype._initFacetData = function () {
  12996. if (!this._facetNormals) {
  12997. this._facetNormals = new Array();
  12998. }
  12999. if (!this._facetPositions) {
  13000. this._facetPositions = new Array();
  13001. }
  13002. if (!this._facetPartitioning) {
  13003. this._facetPartitioning = new Array();
  13004. }
  13005. this._facetNb = this.getIndices().length / 3;
  13006. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13007. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13008. for (var f = 0; f < this._facetNb; f++) {
  13009. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13010. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13011. }
  13012. this._facetDataEnabled = true;
  13013. return this;
  13014. };
  13015. /**
  13016. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13017. * This method can be called within the render loop.
  13018. * 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.
  13019. * Returns the AbstractMesh.
  13020. */
  13021. AbstractMesh.prototype.updateFacetData = function () {
  13022. if (!this._facetDataEnabled) {
  13023. this._initFacetData();
  13024. }
  13025. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13026. var indices = this.getIndices();
  13027. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13028. var bInfo = this.getBoundingInfo();
  13029. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13030. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13031. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13032. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13033. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13034. this._subDiv.max = this._partitioningSubdivisions;
  13035. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13036. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13037. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13038. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13039. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13040. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13041. // set the parameters for ComputeNormals()
  13042. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13043. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13044. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13045. this._facetParameters.bInfo = bInfo;
  13046. this._facetParameters.bbSize = this._bbSize;
  13047. this._facetParameters.subDiv = this._subDiv;
  13048. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13049. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13050. return this;
  13051. };
  13052. /**
  13053. * Returns the facetLocalNormals array.
  13054. * The normals are expressed in the mesh local space.
  13055. */
  13056. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13057. if (!this._facetNormals) {
  13058. this.updateFacetData();
  13059. }
  13060. return this._facetNormals;
  13061. };
  13062. /**
  13063. * Returns the facetLocalPositions array.
  13064. * The facet positions are expressed in the mesh local space.
  13065. */
  13066. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13067. if (!this._facetPositions) {
  13068. this.updateFacetData();
  13069. }
  13070. return this._facetPositions;
  13071. };
  13072. /**
  13073. * Returns the facetLocalPartioning array.
  13074. */
  13075. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13076. if (!this._facetPartitioning) {
  13077. this.updateFacetData();
  13078. }
  13079. return this._facetPartitioning;
  13080. };
  13081. /**
  13082. * Returns the i-th facet position in the world system.
  13083. * This method allocates a new Vector3 per call.
  13084. */
  13085. AbstractMesh.prototype.getFacetPosition = function (i) {
  13086. var pos = BABYLON.Vector3.Zero();
  13087. this.getFacetPositionToRef(i, pos);
  13088. return pos;
  13089. };
  13090. /**
  13091. * Sets the reference Vector3 with the i-th facet position in the world system.
  13092. * Returns the AbstractMesh.
  13093. */
  13094. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13095. var localPos = (this.getFacetLocalPositions())[i];
  13096. var world = this.getWorldMatrix();
  13097. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13098. return this;
  13099. };
  13100. /**
  13101. * Returns the i-th facet normal in the world system.
  13102. * This method allocates a new Vector3 per call.
  13103. */
  13104. AbstractMesh.prototype.getFacetNormal = function (i) {
  13105. var norm = BABYLON.Vector3.Zero();
  13106. this.getFacetNormalToRef(i, norm);
  13107. return norm;
  13108. };
  13109. /**
  13110. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13111. * Returns the AbstractMesh.
  13112. */
  13113. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13114. var localNorm = (this.getFacetLocalNormals())[i];
  13115. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13116. return this;
  13117. };
  13118. /**
  13119. * 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).
  13120. */
  13121. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13122. var bInfo = this.getBoundingInfo();
  13123. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13124. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13125. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13126. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13127. return null;
  13128. }
  13129. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13130. };
  13131. /**
  13132. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13133. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13134. * 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.
  13135. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13136. * 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.
  13137. */
  13138. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13139. if (checkFace === void 0) { checkFace = false; }
  13140. if (facing === void 0) { facing = true; }
  13141. var world = this.getWorldMatrix();
  13142. var invMat = BABYLON.Tmp.Matrix[5];
  13143. world.invertToRef(invMat);
  13144. var invVect = BABYLON.Tmp.Vector3[8];
  13145. var closest = null;
  13146. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13147. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13148. if (projected) {
  13149. // tranform the local computed projected vector to world coordinates
  13150. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13151. }
  13152. return closest;
  13153. };
  13154. /**
  13155. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13156. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13157. * 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.
  13158. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13159. * 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.
  13160. */
  13161. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13162. if (checkFace === void 0) { checkFace = false; }
  13163. if (facing === void 0) { facing = true; }
  13164. var closest = null;
  13165. var tmpx = 0.0;
  13166. var tmpy = 0.0;
  13167. var tmpz = 0.0;
  13168. var d = 0.0; // tmp dot facet normal * facet position
  13169. var t0 = 0.0;
  13170. var projx = 0.0;
  13171. var projy = 0.0;
  13172. var projz = 0.0;
  13173. // Get all the facets in the same partitioning block than (x, y, z)
  13174. var facetPositions = this.getFacetLocalPositions();
  13175. var facetNormals = this.getFacetLocalNormals();
  13176. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13177. if (!facetsInBlock) {
  13178. return null;
  13179. }
  13180. // Get the closest facet to (x, y, z)
  13181. var shortest = Number.MAX_VALUE; // init distance vars
  13182. var tmpDistance = shortest;
  13183. var fib; // current facet in the block
  13184. var norm; // current facet normal
  13185. var p0; // current facet barycenter position
  13186. // loop on all the facets in the current partitioning block
  13187. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13188. fib = facetsInBlock[idx];
  13189. norm = facetNormals[fib];
  13190. p0 = facetPositions[fib];
  13191. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13192. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13193. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13194. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13195. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13196. projx = x + norm.x * t0;
  13197. projy = y + norm.y * t0;
  13198. projz = z + norm.z * t0;
  13199. tmpx = projx - x;
  13200. tmpy = projy - y;
  13201. tmpz = projz - z;
  13202. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13203. if (tmpDistance < shortest) {
  13204. shortest = tmpDistance;
  13205. closest = fib;
  13206. if (projected) {
  13207. projected.x = projx;
  13208. projected.y = projy;
  13209. projected.z = projz;
  13210. }
  13211. }
  13212. }
  13213. }
  13214. return closest;
  13215. };
  13216. /**
  13217. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13218. */
  13219. AbstractMesh.prototype.getFacetDataParameters = function () {
  13220. return this._facetParameters;
  13221. };
  13222. /**
  13223. * Disables the feature FacetData and frees the related memory.
  13224. * Returns the AbstractMesh.
  13225. */
  13226. AbstractMesh.prototype.disableFacetData = function () {
  13227. if (this._facetDataEnabled) {
  13228. this._facetDataEnabled = false;
  13229. this._facetPositions = null;
  13230. this._facetNormals = null;
  13231. this._facetPartitioning = null;
  13232. this._facetParameters = null;
  13233. }
  13234. return this;
  13235. };
  13236. /**
  13237. * Creates new normals data for the mesh.
  13238. * @param updatable.
  13239. */
  13240. AbstractMesh.prototype.createNormals = function (updatable) {
  13241. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13242. var indices = this.getIndices();
  13243. var normals;
  13244. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13245. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13246. }
  13247. else {
  13248. normals = [];
  13249. }
  13250. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13251. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13252. };
  13253. return AbstractMesh;
  13254. }(BABYLON.Node));
  13255. // Statics
  13256. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13257. AbstractMesh._BILLBOARDMODE_X = 1;
  13258. AbstractMesh._BILLBOARDMODE_Y = 2;
  13259. AbstractMesh._BILLBOARDMODE_Z = 4;
  13260. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13261. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13262. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13263. BABYLON.AbstractMesh = AbstractMesh;
  13264. })(BABYLON || (BABYLON = {}));
  13265. //# sourceMappingURL=babylon.abstractMesh.js.map
  13266. var BABYLON;
  13267. (function (BABYLON) {
  13268. var Light = (function (_super) {
  13269. __extends(Light, _super);
  13270. /**
  13271. * Creates a Light object in the scene.
  13272. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13273. */
  13274. function Light(name, scene) {
  13275. var _this = _super.call(this, name, scene) || this;
  13276. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13277. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13278. _this.intensity = 1.0;
  13279. _this.range = Number.MAX_VALUE;
  13280. /**
  13281. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13282. * of light.
  13283. */
  13284. _this._photometricScale = 1.0;
  13285. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13286. _this._radius = 0.00001;
  13287. _this.renderPriority = 0;
  13288. /**
  13289. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13290. * the current shadow generator.
  13291. */
  13292. _this.shadowEnabled = true;
  13293. _this._excludeWithLayerMask = 0;
  13294. _this._includeOnlyWithLayerMask = 0;
  13295. _this._lightmapMode = 0;
  13296. _this._excludedMeshesIds = new Array();
  13297. _this._includedOnlyMeshesIds = new Array();
  13298. _this.getScene().addLight(_this);
  13299. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13300. _this._buildUniformLayout();
  13301. _this.includedOnlyMeshes = new Array();
  13302. _this.excludedMeshes = new Array();
  13303. _this._resyncMeshes();
  13304. return _this;
  13305. }
  13306. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13307. /**
  13308. * If every light affecting the material is in this lightmapMode,
  13309. * material.lightmapTexture adds or multiplies
  13310. * (depends on material.useLightmapAsShadowmap)
  13311. * after every other light calculations.
  13312. */
  13313. get: function () {
  13314. return Light._LIGHTMAP_DEFAULT;
  13315. },
  13316. enumerable: true,
  13317. configurable: true
  13318. });
  13319. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13320. /**
  13321. * material.lightmapTexture as only diffuse lighting from this light
  13322. * adds pnly specular lighting from this light
  13323. * adds dynamic shadows
  13324. */
  13325. get: function () {
  13326. return Light._LIGHTMAP_SPECULAR;
  13327. },
  13328. enumerable: true,
  13329. configurable: true
  13330. });
  13331. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13332. /**
  13333. * material.lightmapTexture as only lighting
  13334. * no light calculation from this light
  13335. * only adds dynamic shadows from this light
  13336. */
  13337. get: function () {
  13338. return Light._LIGHTMAP_SHADOWSONLY;
  13339. },
  13340. enumerable: true,
  13341. configurable: true
  13342. });
  13343. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13344. /**
  13345. * Each light type uses the default quantity according to its type:
  13346. * point/spot lights use luminous intensity
  13347. * directional lights use illuminance
  13348. */
  13349. get: function () {
  13350. return Light._INTENSITYMODE_AUTOMATIC;
  13351. },
  13352. enumerable: true,
  13353. configurable: true
  13354. });
  13355. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13356. /**
  13357. * lumen (lm)
  13358. */
  13359. get: function () {
  13360. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13361. },
  13362. enumerable: true,
  13363. configurable: true
  13364. });
  13365. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13366. /**
  13367. * candela (lm/sr)
  13368. */
  13369. get: function () {
  13370. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13371. },
  13372. enumerable: true,
  13373. configurable: true
  13374. });
  13375. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13376. /**
  13377. * lux (lm/m^2)
  13378. */
  13379. get: function () {
  13380. return Light._INTENSITYMODE_ILLUMINANCE;
  13381. },
  13382. enumerable: true,
  13383. configurable: true
  13384. });
  13385. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13386. /**
  13387. * nit (cd/m^2)
  13388. */
  13389. get: function () {
  13390. return Light._INTENSITYMODE_LUMINANCE;
  13391. },
  13392. enumerable: true,
  13393. configurable: true
  13394. });
  13395. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13396. /**
  13397. * Light type const id of the point light.
  13398. */
  13399. get: function () {
  13400. return Light._LIGHTTYPEID_POINTLIGHT;
  13401. },
  13402. enumerable: true,
  13403. configurable: true
  13404. });
  13405. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13406. /**
  13407. * Light type const id of the directional light.
  13408. */
  13409. get: function () {
  13410. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13411. },
  13412. enumerable: true,
  13413. configurable: true
  13414. });
  13415. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13416. /**
  13417. * Light type const id of the spot light.
  13418. */
  13419. get: function () {
  13420. return Light._LIGHTTYPEID_SPOTLIGHT;
  13421. },
  13422. enumerable: true,
  13423. configurable: true
  13424. });
  13425. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13426. /**
  13427. * Light type const id of the hemispheric light.
  13428. */
  13429. get: function () {
  13430. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13431. },
  13432. enumerable: true,
  13433. configurable: true
  13434. });
  13435. Object.defineProperty(Light.prototype, "intensityMode", {
  13436. /**
  13437. * Gets the photometric scale used to interpret the intensity.
  13438. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13439. */
  13440. get: function () {
  13441. return this._intensityMode;
  13442. },
  13443. /**
  13444. * Sets the photometric scale used to interpret the intensity.
  13445. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13446. */
  13447. set: function (value) {
  13448. this._intensityMode = value;
  13449. this._computePhotometricScale();
  13450. },
  13451. enumerable: true,
  13452. configurable: true
  13453. });
  13454. ;
  13455. ;
  13456. Object.defineProperty(Light.prototype, "radius", {
  13457. /**
  13458. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13459. */
  13460. get: function () {
  13461. return this._radius;
  13462. },
  13463. /**
  13464. * sets the light radius used by PBR Materials to simulate soft area lights.
  13465. */
  13466. set: function (value) {
  13467. this._radius = value;
  13468. this._computePhotometricScale();
  13469. },
  13470. enumerable: true,
  13471. configurable: true
  13472. });
  13473. ;
  13474. ;
  13475. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13476. get: function () {
  13477. return this._includedOnlyMeshes;
  13478. },
  13479. set: function (value) {
  13480. this._includedOnlyMeshes = value;
  13481. this._hookArrayForIncludedOnly(value);
  13482. },
  13483. enumerable: true,
  13484. configurable: true
  13485. });
  13486. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13487. get: function () {
  13488. return this._excludedMeshes;
  13489. },
  13490. set: function (value) {
  13491. this._excludedMeshes = value;
  13492. this._hookArrayForExcluded(value);
  13493. },
  13494. enumerable: true,
  13495. configurable: true
  13496. });
  13497. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13498. get: function () {
  13499. return this._excludeWithLayerMask;
  13500. },
  13501. set: function (value) {
  13502. this._excludeWithLayerMask = value;
  13503. this._resyncMeshes();
  13504. },
  13505. enumerable: true,
  13506. configurable: true
  13507. });
  13508. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13509. get: function () {
  13510. return this._includeOnlyWithLayerMask;
  13511. },
  13512. set: function (value) {
  13513. this._includeOnlyWithLayerMask = value;
  13514. this._resyncMeshes();
  13515. },
  13516. enumerable: true,
  13517. configurable: true
  13518. });
  13519. Object.defineProperty(Light.prototype, "lightmapMode", {
  13520. get: function () {
  13521. return this._lightmapMode;
  13522. },
  13523. set: function (value) {
  13524. if (this._lightmapMode === value) {
  13525. return;
  13526. }
  13527. this._lightmapMode = value;
  13528. this._markMeshesAsLightDirty();
  13529. },
  13530. enumerable: true,
  13531. configurable: true
  13532. });
  13533. Light.prototype._buildUniformLayout = function () {
  13534. // Overridden
  13535. };
  13536. /**
  13537. * Returns the string "Light".
  13538. */
  13539. Light.prototype.getClassName = function () {
  13540. return "Light";
  13541. };
  13542. /**
  13543. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13544. */
  13545. Light.prototype.toString = function (fullDetails) {
  13546. var ret = "Name: " + this.name;
  13547. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13548. if (this.animations) {
  13549. for (var i = 0; i < this.animations.length; i++) {
  13550. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13551. }
  13552. }
  13553. if (fullDetails) {
  13554. }
  13555. return ret;
  13556. };
  13557. /**
  13558. * Set the enabled state of this node.
  13559. * @param {boolean} value - the new enabled state
  13560. * @see isEnabled
  13561. */
  13562. Light.prototype.setEnabled = function (value) {
  13563. _super.prototype.setEnabled.call(this, value);
  13564. this._resyncMeshes();
  13565. };
  13566. /**
  13567. * Returns the Light associated shadow generator.
  13568. */
  13569. Light.prototype.getShadowGenerator = function () {
  13570. return this._shadowGenerator;
  13571. };
  13572. /**
  13573. * Returns a Vector3, the absolute light position in the World.
  13574. */
  13575. Light.prototype.getAbsolutePosition = function () {
  13576. return BABYLON.Vector3.Zero();
  13577. };
  13578. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13579. };
  13580. Light.prototype._getWorldMatrix = function () {
  13581. return BABYLON.Matrix.Identity();
  13582. };
  13583. /**
  13584. * Boolean : True if the light will affect the passed mesh.
  13585. */
  13586. Light.prototype.canAffectMesh = function (mesh) {
  13587. if (!mesh) {
  13588. return true;
  13589. }
  13590. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13591. return false;
  13592. }
  13593. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13594. return false;
  13595. }
  13596. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13597. return false;
  13598. }
  13599. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13600. return false;
  13601. }
  13602. return true;
  13603. };
  13604. /**
  13605. * Returns the light World matrix.
  13606. */
  13607. Light.prototype.getWorldMatrix = function () {
  13608. this._currentRenderId = this.getScene().getRenderId();
  13609. var worldMatrix = this._getWorldMatrix();
  13610. if (this.parent && this.parent.getWorldMatrix) {
  13611. if (!this._parentedWorldMatrix) {
  13612. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13613. }
  13614. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13615. this._markSyncedWithParent();
  13616. return this._parentedWorldMatrix;
  13617. }
  13618. return worldMatrix;
  13619. };
  13620. /**
  13621. * Sort function to order lights for rendering.
  13622. * @param a First Light object to compare to second.
  13623. * @param b Second Light object to compare first.
  13624. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13625. */
  13626. Light.compareLightsPriority = function (a, b) {
  13627. //shadow-casting lights have priority over non-shadow-casting lights
  13628. //the renderPrioirty is a secondary sort criterion
  13629. if (a.shadowEnabled !== b.shadowEnabled) {
  13630. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13631. }
  13632. return b.renderPriority - a.renderPriority;
  13633. };
  13634. /**
  13635. * Disposes the light.
  13636. */
  13637. Light.prototype.dispose = function () {
  13638. if (this._shadowGenerator) {
  13639. this._shadowGenerator.dispose();
  13640. this._shadowGenerator = null;
  13641. }
  13642. // Animations
  13643. this.getScene().stopAnimation(this);
  13644. // Remove from meshes
  13645. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13646. var mesh = _a[_i];
  13647. mesh._removeLightSource(this);
  13648. }
  13649. this._uniformBuffer.dispose();
  13650. // Remove from scene
  13651. this.getScene().removeLight(this);
  13652. _super.prototype.dispose.call(this);
  13653. };
  13654. /**
  13655. * Returns the light type ID (integer).
  13656. */
  13657. Light.prototype.getTypeID = function () {
  13658. return 0;
  13659. };
  13660. /**
  13661. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13662. */
  13663. Light.prototype.getScaledIntensity = function () {
  13664. return this._photometricScale * this.intensity;
  13665. };
  13666. /**
  13667. * Returns a new Light object, named "name", from the current one.
  13668. */
  13669. Light.prototype.clone = function (name) {
  13670. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13671. };
  13672. /**
  13673. * Serializes the current light into a Serialization object.
  13674. * Returns the serialized object.
  13675. */
  13676. Light.prototype.serialize = function () {
  13677. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13678. // Type
  13679. serializationObject.type = this.getTypeID();
  13680. // Parent
  13681. if (this.parent) {
  13682. serializationObject.parentId = this.parent.id;
  13683. }
  13684. // Inclusion / exclusions
  13685. if (this.excludedMeshes.length > 0) {
  13686. serializationObject.excludedMeshesIds = [];
  13687. this.excludedMeshes.forEach(function (mesh) {
  13688. serializationObject.excludedMeshesIds.push(mesh.id);
  13689. });
  13690. }
  13691. if (this.includedOnlyMeshes.length > 0) {
  13692. serializationObject.includedOnlyMeshesIds = [];
  13693. this.includedOnlyMeshes.forEach(function (mesh) {
  13694. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13695. });
  13696. }
  13697. // Animations
  13698. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13699. serializationObject.ranges = this.serializeAnimationRanges();
  13700. return serializationObject;
  13701. };
  13702. /**
  13703. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13704. * This new light is named "name" and added to the passed scene.
  13705. */
  13706. Light.GetConstructorFromName = function (type, name, scene) {
  13707. switch (type) {
  13708. case 0:
  13709. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13710. case 1:
  13711. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13712. case 2:
  13713. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13714. case 3:
  13715. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13716. }
  13717. };
  13718. /**
  13719. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13720. */
  13721. Light.Parse = function (parsedLight, scene) {
  13722. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13723. // Inclusion / exclusions
  13724. if (parsedLight.excludedMeshesIds) {
  13725. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13726. }
  13727. if (parsedLight.includedOnlyMeshesIds) {
  13728. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13729. }
  13730. // Parent
  13731. if (parsedLight.parentId) {
  13732. light._waitingParentId = parsedLight.parentId;
  13733. }
  13734. // Animations
  13735. if (parsedLight.animations) {
  13736. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13737. var parsedAnimation = parsedLight.animations[animationIndex];
  13738. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13739. }
  13740. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13741. }
  13742. if (parsedLight.autoAnimate) {
  13743. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13744. }
  13745. return light;
  13746. };
  13747. Light.prototype._hookArrayForExcluded = function (array) {
  13748. var _this = this;
  13749. var oldPush = array.push;
  13750. array.push = function () {
  13751. var items = [];
  13752. for (var _i = 0; _i < arguments.length; _i++) {
  13753. items[_i] = arguments[_i];
  13754. }
  13755. var result = oldPush.apply(array, items);
  13756. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13757. var item = items_1[_a];
  13758. item._resyncLighSource(_this);
  13759. }
  13760. return result;
  13761. };
  13762. var oldSplice = array.splice;
  13763. array.splice = function (index, deleteCount) {
  13764. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13765. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13766. var item = deleted_1[_i];
  13767. item._resyncLighSource(_this);
  13768. }
  13769. return deleted;
  13770. };
  13771. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13772. var item = array_1[_i];
  13773. item._resyncLighSource(this);
  13774. }
  13775. };
  13776. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13777. var _this = this;
  13778. var oldPush = array.push;
  13779. array.push = function () {
  13780. var items = [];
  13781. for (var _i = 0; _i < arguments.length; _i++) {
  13782. items[_i] = arguments[_i];
  13783. }
  13784. var result = oldPush.apply(array, items);
  13785. _this._resyncMeshes();
  13786. return result;
  13787. };
  13788. var oldSplice = array.splice;
  13789. array.splice = function (index, deleteCount) {
  13790. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13791. _this._resyncMeshes();
  13792. return deleted;
  13793. };
  13794. this._resyncMeshes();
  13795. };
  13796. Light.prototype._resyncMeshes = function () {
  13797. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13798. var mesh = _a[_i];
  13799. mesh._resyncLighSource(this);
  13800. }
  13801. };
  13802. Light.prototype._markMeshesAsLightDirty = function () {
  13803. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13804. var mesh = _a[_i];
  13805. if (mesh._lightSources.indexOf(this) !== -1) {
  13806. mesh._markSubMeshesAsLightDirty();
  13807. }
  13808. }
  13809. };
  13810. /**
  13811. * Recomputes the cached photometric scale if needed.
  13812. */
  13813. Light.prototype._computePhotometricScale = function () {
  13814. this._photometricScale = this._getPhotometricScale();
  13815. this.getScene().resetCachedMaterial();
  13816. };
  13817. /**
  13818. * Returns the Photometric Scale according to the light type and intensity mode.
  13819. */
  13820. Light.prototype._getPhotometricScale = function () {
  13821. var photometricScale = 0.0;
  13822. var lightTypeID = this.getTypeID();
  13823. //get photometric mode
  13824. var photometricMode = this.intensityMode;
  13825. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13826. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13827. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13828. }
  13829. else {
  13830. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13831. }
  13832. }
  13833. //compute photometric scale
  13834. switch (lightTypeID) {
  13835. case Light.LIGHTTYPEID_POINTLIGHT:
  13836. case Light.LIGHTTYPEID_SPOTLIGHT:
  13837. switch (photometricMode) {
  13838. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13839. photometricScale = 1.0 / (4.0 * Math.PI);
  13840. break;
  13841. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13842. photometricScale = 1.0;
  13843. break;
  13844. case Light.INTENSITYMODE_LUMINANCE:
  13845. photometricScale = this.radius * this.radius;
  13846. break;
  13847. }
  13848. break;
  13849. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13850. switch (photometricMode) {
  13851. case Light.INTENSITYMODE_ILLUMINANCE:
  13852. photometricScale = 1.0;
  13853. break;
  13854. case Light.INTENSITYMODE_LUMINANCE:
  13855. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13856. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13857. var apexAngleRadians = this.radius;
  13858. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13859. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13860. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13861. photometricScale = solidAngle;
  13862. break;
  13863. }
  13864. break;
  13865. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13866. // No fall off in hemisperic light.
  13867. photometricScale = 1.0;
  13868. break;
  13869. }
  13870. return photometricScale;
  13871. };
  13872. Light.prototype._reorderLightsInScene = function () {
  13873. var scene = this.getScene();
  13874. if (this.renderPriority != 0) {
  13875. scene.requireLightSorting = true;
  13876. }
  13877. this.getScene().sortLightsByPriority();
  13878. };
  13879. return Light;
  13880. }(BABYLON.Node));
  13881. //lightmapMode Consts
  13882. Light._LIGHTMAP_DEFAULT = 0;
  13883. Light._LIGHTMAP_SPECULAR = 1;
  13884. Light._LIGHTMAP_SHADOWSONLY = 2;
  13885. // Intensity Mode Consts
  13886. Light._INTENSITYMODE_AUTOMATIC = 0;
  13887. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13888. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13889. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13890. Light._INTENSITYMODE_LUMINANCE = 4;
  13891. // Light types ids const.
  13892. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13893. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13894. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13895. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13896. __decorate([
  13897. BABYLON.serializeAsColor3()
  13898. ], Light.prototype, "diffuse", void 0);
  13899. __decorate([
  13900. BABYLON.serializeAsColor3()
  13901. ], Light.prototype, "specular", void 0);
  13902. __decorate([
  13903. BABYLON.serialize()
  13904. ], Light.prototype, "intensity", void 0);
  13905. __decorate([
  13906. BABYLON.serialize()
  13907. ], Light.prototype, "range", void 0);
  13908. __decorate([
  13909. BABYLON.serialize()
  13910. ], Light.prototype, "intensityMode", null);
  13911. __decorate([
  13912. BABYLON.serialize()
  13913. ], Light.prototype, "radius", null);
  13914. __decorate([
  13915. BABYLON.serialize()
  13916. ], Light.prototype, "_renderPriority", void 0);
  13917. __decorate([
  13918. BABYLON.expandToProperty("_reorderLightsInScene")
  13919. ], Light.prototype, "renderPriority", void 0);
  13920. __decorate([
  13921. BABYLON.serialize()
  13922. ], Light.prototype, "shadowEnabled", void 0);
  13923. __decorate([
  13924. BABYLON.serialize("excludeWithLayerMask")
  13925. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13926. __decorate([
  13927. BABYLON.serialize("includeOnlyWithLayerMask")
  13928. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13929. __decorate([
  13930. BABYLON.serialize("lightmapMode")
  13931. ], Light.prototype, "_lightmapMode", void 0);
  13932. BABYLON.Light = Light;
  13933. })(BABYLON || (BABYLON = {}));
  13934. //# sourceMappingURL=babylon.light.js.map
  13935. var BABYLON;
  13936. (function (BABYLON) {
  13937. var Camera = (function (_super) {
  13938. __extends(Camera, _super);
  13939. function Camera(name, position, scene) {
  13940. var _this = _super.call(this, name, scene) || this;
  13941. _this.upVector = BABYLON.Vector3.Up();
  13942. _this.orthoLeft = null;
  13943. _this.orthoRight = null;
  13944. _this.orthoBottom = null;
  13945. _this.orthoTop = null;
  13946. _this.fov = 0.8;
  13947. _this.minZ = 1.0;
  13948. _this.maxZ = 10000.0;
  13949. _this.inertia = 0.9;
  13950. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13951. _this.isIntermediate = false;
  13952. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13953. _this.layerMask = 0x0FFFFFFF;
  13954. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13955. // Camera rig members
  13956. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13957. _this._rigCameras = new Array();
  13958. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13959. _this.customRenderTargets = new Array();
  13960. // Cache
  13961. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13962. _this._projectionMatrix = new BABYLON.Matrix();
  13963. _this._doNotComputeProjectionMatrix = false;
  13964. _this._postProcesses = new Array();
  13965. _this._transformMatrix = BABYLON.Matrix.Zero();
  13966. _this._activeMeshes = new BABYLON.SmartArray(256);
  13967. _this._globalPosition = BABYLON.Vector3.Zero();
  13968. _this._refreshFrustumPlanes = true;
  13969. _this.getScene().addCamera(_this);
  13970. if (!_this.getScene().activeCamera) {
  13971. _this.getScene().activeCamera = _this;
  13972. }
  13973. _this.position = position;
  13974. return _this;
  13975. }
  13976. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13977. get: function () {
  13978. return Camera._PERSPECTIVE_CAMERA;
  13979. },
  13980. enumerable: true,
  13981. configurable: true
  13982. });
  13983. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13984. get: function () {
  13985. return Camera._ORTHOGRAPHIC_CAMERA;
  13986. },
  13987. enumerable: true,
  13988. configurable: true
  13989. });
  13990. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13991. get: function () {
  13992. return Camera._FOVMODE_VERTICAL_FIXED;
  13993. },
  13994. enumerable: true,
  13995. configurable: true
  13996. });
  13997. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13998. get: function () {
  13999. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14000. },
  14001. enumerable: true,
  14002. configurable: true
  14003. });
  14004. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14005. get: function () {
  14006. return Camera._RIG_MODE_NONE;
  14007. },
  14008. enumerable: true,
  14009. configurable: true
  14010. });
  14011. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14012. get: function () {
  14013. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14014. },
  14015. enumerable: true,
  14016. configurable: true
  14017. });
  14018. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14019. get: function () {
  14020. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14021. },
  14022. enumerable: true,
  14023. configurable: true
  14024. });
  14025. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14026. get: function () {
  14027. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14028. },
  14029. enumerable: true,
  14030. configurable: true
  14031. });
  14032. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14033. get: function () {
  14034. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14035. },
  14036. enumerable: true,
  14037. configurable: true
  14038. });
  14039. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14040. get: function () {
  14041. return Camera._RIG_MODE_VR;
  14042. },
  14043. enumerable: true,
  14044. configurable: true
  14045. });
  14046. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14047. get: function () {
  14048. return Camera._RIG_MODE_WEBVR;
  14049. },
  14050. enumerable: true,
  14051. configurable: true
  14052. });
  14053. Camera.prototype.getClassName = function () {
  14054. return "Camera";
  14055. };
  14056. /**
  14057. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14058. */
  14059. Camera.prototype.toString = function (fullDetails) {
  14060. var ret = "Name: " + this.name;
  14061. ret += ", type: " + this.getClassName();
  14062. if (this.animations) {
  14063. for (var i = 0; i < this.animations.length; i++) {
  14064. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14065. }
  14066. }
  14067. if (fullDetails) {
  14068. }
  14069. return ret;
  14070. };
  14071. Object.defineProperty(Camera.prototype, "globalPosition", {
  14072. get: function () {
  14073. return this._globalPosition;
  14074. },
  14075. enumerable: true,
  14076. configurable: true
  14077. });
  14078. Camera.prototype.getActiveMeshes = function () {
  14079. return this._activeMeshes;
  14080. };
  14081. Camera.prototype.isActiveMesh = function (mesh) {
  14082. return (this._activeMeshes.indexOf(mesh) !== -1);
  14083. };
  14084. //Cache
  14085. Camera.prototype._initCache = function () {
  14086. _super.prototype._initCache.call(this);
  14087. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14088. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14089. this._cache.mode = undefined;
  14090. this._cache.minZ = undefined;
  14091. this._cache.maxZ = undefined;
  14092. this._cache.fov = undefined;
  14093. this._cache.fovMode = undefined;
  14094. this._cache.aspectRatio = undefined;
  14095. this._cache.orthoLeft = undefined;
  14096. this._cache.orthoRight = undefined;
  14097. this._cache.orthoBottom = undefined;
  14098. this._cache.orthoTop = undefined;
  14099. this._cache.renderWidth = undefined;
  14100. this._cache.renderHeight = undefined;
  14101. };
  14102. Camera.prototype._updateCache = function (ignoreParentClass) {
  14103. if (!ignoreParentClass) {
  14104. _super.prototype._updateCache.call(this);
  14105. }
  14106. var engine = this.getEngine();
  14107. this._cache.position.copyFrom(this.position);
  14108. this._cache.upVector.copyFrom(this.upVector);
  14109. this._cache.mode = this.mode;
  14110. this._cache.minZ = this.minZ;
  14111. this._cache.maxZ = this.maxZ;
  14112. this._cache.fov = this.fov;
  14113. this._cache.fovMode = this.fovMode;
  14114. this._cache.aspectRatio = engine.getAspectRatio(this);
  14115. this._cache.orthoLeft = this.orthoLeft;
  14116. this._cache.orthoRight = this.orthoRight;
  14117. this._cache.orthoBottom = this.orthoBottom;
  14118. this._cache.orthoTop = this.orthoTop;
  14119. this._cache.renderWidth = engine.getRenderWidth();
  14120. this._cache.renderHeight = engine.getRenderHeight();
  14121. };
  14122. Camera.prototype._updateFromScene = function () {
  14123. this.updateCache();
  14124. this.update();
  14125. };
  14126. // Synchronized
  14127. Camera.prototype._isSynchronized = function () {
  14128. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14129. };
  14130. Camera.prototype._isSynchronizedViewMatrix = function () {
  14131. if (!_super.prototype._isSynchronized.call(this))
  14132. return false;
  14133. return this._cache.position.equals(this.position)
  14134. && this._cache.upVector.equals(this.upVector)
  14135. && this.isSynchronizedWithParent();
  14136. };
  14137. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14138. var check = this._cache.mode === this.mode
  14139. && this._cache.minZ === this.minZ
  14140. && this._cache.maxZ === this.maxZ;
  14141. if (!check) {
  14142. return false;
  14143. }
  14144. var engine = this.getEngine();
  14145. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14146. check = this._cache.fov === this.fov
  14147. && this._cache.fovMode === this.fovMode
  14148. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14149. }
  14150. else {
  14151. check = this._cache.orthoLeft === this.orthoLeft
  14152. && this._cache.orthoRight === this.orthoRight
  14153. && this._cache.orthoBottom === this.orthoBottom
  14154. && this._cache.orthoTop === this.orthoTop
  14155. && this._cache.renderWidth === engine.getRenderWidth()
  14156. && this._cache.renderHeight === engine.getRenderHeight();
  14157. }
  14158. return check;
  14159. };
  14160. // Controls
  14161. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14162. };
  14163. Camera.prototype.detachControl = function (element) {
  14164. };
  14165. Camera.prototype.update = function () {
  14166. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14167. this._updateRigCameras();
  14168. }
  14169. this._checkInputs();
  14170. };
  14171. Camera.prototype._checkInputs = function () {
  14172. };
  14173. Object.defineProperty(Camera.prototype, "rigCameras", {
  14174. get: function () {
  14175. return this._rigCameras;
  14176. },
  14177. enumerable: true,
  14178. configurable: true
  14179. });
  14180. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14181. get: function () {
  14182. return this._rigPostProcess;
  14183. },
  14184. enumerable: true,
  14185. configurable: true
  14186. });
  14187. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14188. // invalidate framebuffer
  14189. if (this._postProcesses.length > 0) {
  14190. this._postProcesses[0].markTextureDirty();
  14191. }
  14192. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14193. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14194. var cam = this._rigCameras[i];
  14195. var rigPostProcess = cam._rigPostProcess;
  14196. // for VR rig, there does not have to be a post process
  14197. if (rigPostProcess) {
  14198. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14199. if (isPass) {
  14200. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14201. cam.isIntermediate = this._postProcesses.length === 0;
  14202. }
  14203. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14204. rigPostProcess.markTextureDirty();
  14205. }
  14206. else {
  14207. cam._postProcesses = this._postProcesses.slice(0);
  14208. }
  14209. }
  14210. };
  14211. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14212. if (insertAt === void 0) { insertAt = null; }
  14213. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14214. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14215. return 0;
  14216. }
  14217. if (insertAt == null || insertAt < 0) {
  14218. this._postProcesses.push(postProcess);
  14219. }
  14220. else {
  14221. this._postProcesses.splice(insertAt, 0, postProcess);
  14222. }
  14223. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14224. return this._postProcesses.indexOf(postProcess);
  14225. };
  14226. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14227. if (atIndices === void 0) { atIndices = null; }
  14228. var result = [];
  14229. var i;
  14230. var index;
  14231. if (!atIndices) {
  14232. var idx = this._postProcesses.indexOf(postProcess);
  14233. if (idx !== -1) {
  14234. this._postProcesses.splice(idx, 1);
  14235. }
  14236. }
  14237. else {
  14238. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14239. // iterate descending, so can just splice as we go
  14240. for (i = atIndices.length - 1; i >= 0; i--) {
  14241. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14242. result.push(i);
  14243. continue;
  14244. }
  14245. index = atIndices[i];
  14246. this._postProcesses.splice(index, 1);
  14247. }
  14248. }
  14249. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14250. return result;
  14251. };
  14252. Camera.prototype.getWorldMatrix = function () {
  14253. if (!this._worldMatrix) {
  14254. this._worldMatrix = BABYLON.Matrix.Identity();
  14255. }
  14256. var viewMatrix = this.getViewMatrix();
  14257. viewMatrix.invertToRef(this._worldMatrix);
  14258. return this._worldMatrix;
  14259. };
  14260. Camera.prototype._getViewMatrix = function () {
  14261. return BABYLON.Matrix.Identity();
  14262. };
  14263. Camera.prototype.getViewMatrix = function (force) {
  14264. this._computedViewMatrix = this._computeViewMatrix(force);
  14265. if (!force && this._isSynchronizedViewMatrix()) {
  14266. return this._computedViewMatrix;
  14267. }
  14268. this._refreshFrustumPlanes = true;
  14269. if (!this.parent || !this.parent.getWorldMatrix) {
  14270. this._globalPosition.copyFrom(this.position);
  14271. }
  14272. else {
  14273. if (!this._worldMatrix) {
  14274. this._worldMatrix = BABYLON.Matrix.Identity();
  14275. }
  14276. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14277. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14278. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14279. this._computedViewMatrix.invert();
  14280. this._markSyncedWithParent();
  14281. }
  14282. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14283. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14284. }
  14285. this._currentRenderId = this.getScene().getRenderId();
  14286. return this._computedViewMatrix;
  14287. };
  14288. Camera.prototype._computeViewMatrix = function (force) {
  14289. if (!force && this._isSynchronizedViewMatrix()) {
  14290. return this._computedViewMatrix;
  14291. }
  14292. this._computedViewMatrix = this._getViewMatrix();
  14293. this._currentRenderId = this.getScene().getRenderId();
  14294. return this._computedViewMatrix;
  14295. };
  14296. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14297. this._doNotComputeProjectionMatrix = true;
  14298. if (projection !== undefined) {
  14299. this._projectionMatrix = projection;
  14300. }
  14301. };
  14302. ;
  14303. Camera.prototype.unfreezeProjectionMatrix = function () {
  14304. this._doNotComputeProjectionMatrix = false;
  14305. };
  14306. ;
  14307. Camera.prototype.getProjectionMatrix = function (force) {
  14308. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14309. return this._projectionMatrix;
  14310. }
  14311. this._refreshFrustumPlanes = true;
  14312. var engine = this.getEngine();
  14313. var scene = this.getScene();
  14314. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14315. if (this.minZ <= 0) {
  14316. this.minZ = 0.1;
  14317. }
  14318. if (scene.useRightHandedSystem) {
  14319. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14320. }
  14321. else {
  14322. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14323. }
  14324. return this._projectionMatrix;
  14325. }
  14326. var halfWidth = engine.getRenderWidth() / 2.0;
  14327. var halfHeight = engine.getRenderHeight() / 2.0;
  14328. if (scene.useRightHandedSystem) {
  14329. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14330. }
  14331. else {
  14332. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14333. }
  14334. return this._projectionMatrix;
  14335. };
  14336. Camera.prototype.getTranformationMatrix = function () {
  14337. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14338. return this._transformMatrix;
  14339. };
  14340. Camera.prototype.updateFrustumPlanes = function () {
  14341. if (!this._refreshFrustumPlanes) {
  14342. return;
  14343. }
  14344. this.getTranformationMatrix();
  14345. if (!this._frustumPlanes) {
  14346. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14347. }
  14348. else {
  14349. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14350. }
  14351. this._refreshFrustumPlanes = false;
  14352. };
  14353. Camera.prototype.isInFrustum = function (target) {
  14354. this.updateFrustumPlanes();
  14355. return target.isInFrustum(this._frustumPlanes);
  14356. };
  14357. Camera.prototype.isCompletelyInFrustum = function (target) {
  14358. this.updateFrustumPlanes();
  14359. return target.isCompletelyInFrustum(this._frustumPlanes);
  14360. };
  14361. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14362. if (length === void 0) { length = 100; }
  14363. if (!transform) {
  14364. transform = this.getWorldMatrix();
  14365. }
  14366. if (!origin) {
  14367. origin = this.position;
  14368. }
  14369. var forward = new BABYLON.Vector3(0, 0, 1);
  14370. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14371. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14372. return new BABYLON.Ray(origin, direction, length);
  14373. };
  14374. Camera.prototype.dispose = function () {
  14375. // Animations
  14376. this.getScene().stopAnimation(this);
  14377. // Remove from scene
  14378. this.getScene().removeCamera(this);
  14379. while (this._rigCameras.length > 0) {
  14380. this._rigCameras.pop().dispose();
  14381. }
  14382. // Postprocesses
  14383. var i = this._postProcesses.length;
  14384. while (--i >= 0) {
  14385. this._postProcesses[i].dispose(this);
  14386. }
  14387. _super.prototype.dispose.call(this);
  14388. };
  14389. Object.defineProperty(Camera.prototype, "leftCamera", {
  14390. // ---- Camera rigs section ----
  14391. get: function () {
  14392. if (this._rigCameras.length < 1) {
  14393. return undefined;
  14394. }
  14395. return this._rigCameras[0];
  14396. },
  14397. enumerable: true,
  14398. configurable: true
  14399. });
  14400. Object.defineProperty(Camera.prototype, "rightCamera", {
  14401. get: function () {
  14402. if (this._rigCameras.length < 2) {
  14403. return undefined;
  14404. }
  14405. return this._rigCameras[1];
  14406. },
  14407. enumerable: true,
  14408. configurable: true
  14409. });
  14410. Camera.prototype.getLeftTarget = function () {
  14411. if (this._rigCameras.length < 1) {
  14412. return undefined;
  14413. }
  14414. return this._rigCameras[0].getTarget();
  14415. };
  14416. Camera.prototype.getRightTarget = function () {
  14417. if (this._rigCameras.length < 2) {
  14418. return undefined;
  14419. }
  14420. return this._rigCameras[1].getTarget();
  14421. };
  14422. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14423. while (this._rigCameras.length > 0) {
  14424. this._rigCameras.pop().dispose();
  14425. }
  14426. this.cameraRigMode = mode;
  14427. this._cameraRigParams = {};
  14428. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14429. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14430. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14431. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14432. // create the rig cameras, unless none
  14433. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14434. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14435. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14436. }
  14437. switch (this.cameraRigMode) {
  14438. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14439. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14440. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14441. break;
  14442. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14443. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14444. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14445. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14446. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14447. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14448. break;
  14449. case Camera.RIG_MODE_VR:
  14450. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14451. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14452. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14453. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14454. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14455. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14456. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14457. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14458. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14459. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14460. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14461. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14462. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14463. if (metrics.compensateDistortion) {
  14464. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14465. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14466. }
  14467. break;
  14468. case Camera.RIG_MODE_WEBVR:
  14469. if (rigParams.vrDisplay) {
  14470. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14471. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14472. //Left eye
  14473. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14474. this._rigCameras[0].setCameraRigParameter("left", true);
  14475. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14476. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14477. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14478. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14479. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14480. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14481. this._rigCameras[0].parent = this;
  14482. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14483. //Right eye
  14484. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14485. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14486. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14487. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14488. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14489. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14490. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14491. this._rigCameras[1].parent = this;
  14492. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14493. }
  14494. break;
  14495. }
  14496. this._cascadePostProcessesToRigCams();
  14497. this.
  14498. update();
  14499. };
  14500. Camera.prototype._getVRProjectionMatrix = function () {
  14501. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14502. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14503. return this._projectionMatrix;
  14504. };
  14505. Camera.prototype._updateCameraRotationMatrix = function () {
  14506. //Here for WebVR
  14507. };
  14508. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14509. //Here for WebVR
  14510. };
  14511. /**
  14512. * This function MUST be overwritten by the different WebVR cameras available.
  14513. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14514. */
  14515. Camera.prototype._getWebVRProjectionMatrix = function () {
  14516. return BABYLON.Matrix.Identity();
  14517. };
  14518. /**
  14519. * This function MUST be overwritten by the different WebVR cameras available.
  14520. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14521. */
  14522. Camera.prototype._getWebVRViewMatrix = function () {
  14523. return BABYLON.Matrix.Identity();
  14524. };
  14525. Camera.prototype.setCameraRigParameter = function (name, value) {
  14526. if (!this._cameraRigParams) {
  14527. this._cameraRigParams = {};
  14528. }
  14529. this._cameraRigParams[name] = value;
  14530. //provisionnally:
  14531. if (name === "interaxialDistance") {
  14532. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14533. }
  14534. };
  14535. /**
  14536. * needs to be overridden by children so sub has required properties to be copied
  14537. */
  14538. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14539. return null;
  14540. };
  14541. /**
  14542. * May need to be overridden by children
  14543. */
  14544. Camera.prototype._updateRigCameras = function () {
  14545. for (var i = 0; i < this._rigCameras.length; i++) {
  14546. this._rigCameras[i].minZ = this.minZ;
  14547. this._rigCameras[i].maxZ = this.maxZ;
  14548. this._rigCameras[i].fov = this.fov;
  14549. }
  14550. // only update viewport when ANAGLYPH
  14551. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14552. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14553. }
  14554. };
  14555. Camera.prototype._setupInputs = function () {
  14556. };
  14557. Camera.prototype.serialize = function () {
  14558. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14559. // Type
  14560. serializationObject.type = this.getClassName();
  14561. // Parent
  14562. if (this.parent) {
  14563. serializationObject.parentId = this.parent.id;
  14564. }
  14565. if (this.inputs) {
  14566. this.inputs.serialize(serializationObject);
  14567. }
  14568. // Animations
  14569. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14570. serializationObject.ranges = this.serializeAnimationRanges();
  14571. return serializationObject;
  14572. };
  14573. Camera.prototype.clone = function (name) {
  14574. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14575. };
  14576. Camera.prototype.getDirection = function (localAxis) {
  14577. var result = BABYLON.Vector3.Zero();
  14578. this.getDirectionToRef(localAxis, result);
  14579. return result;
  14580. };
  14581. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14582. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14583. };
  14584. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14585. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14586. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14587. switch (type) {
  14588. case "ArcRotateCamera":
  14589. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14590. case "DeviceOrientationCamera":
  14591. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14592. case "FollowCamera":
  14593. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14594. case "ArcFollowCamera":
  14595. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14596. case "GamepadCamera":
  14597. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14598. case "TouchCamera":
  14599. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14600. case "VirtualJoysticksCamera":
  14601. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14602. case "WebVRFreeCamera":
  14603. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14604. case "WebVRGamepadCamera":
  14605. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14606. case "VRDeviceOrientationFreeCamera":
  14607. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14608. case "VRDeviceOrientationGamepadCamera":
  14609. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14610. case "AnaglyphArcRotateCamera":
  14611. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14612. case "AnaglyphFreeCamera":
  14613. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14614. case "AnaglyphGamepadCamera":
  14615. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14616. case "AnaglyphUniversalCamera":
  14617. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14618. case "StereoscopicArcRotateCamera":
  14619. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14620. case "StereoscopicFreeCamera":
  14621. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14622. case "StereoscopicGamepadCamera":
  14623. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14624. case "StereoscopicUniversalCamera":
  14625. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14626. case "FreeCamera":
  14627. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14628. default:
  14629. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14630. }
  14631. };
  14632. Camera.Parse = function (parsedCamera, scene) {
  14633. var type = parsedCamera.type;
  14634. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14635. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14636. // Parent
  14637. if (parsedCamera.parentId) {
  14638. camera._waitingParentId = parsedCamera.parentId;
  14639. }
  14640. //If camera has an input manager, let it parse inputs settings
  14641. if (camera.inputs) {
  14642. camera.inputs.parse(parsedCamera);
  14643. camera._setupInputs();
  14644. }
  14645. if (camera.setPosition) {
  14646. camera.position.copyFromFloats(0, 0, 0);
  14647. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  14648. }
  14649. // Target
  14650. if (parsedCamera.target) {
  14651. if (camera.setTarget) {
  14652. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14653. }
  14654. }
  14655. // Apply 3d rig, when found
  14656. if (parsedCamera.cameraRigMode) {
  14657. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14658. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14659. }
  14660. // Animations
  14661. if (parsedCamera.animations) {
  14662. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14663. var parsedAnimation = parsedCamera.animations[animationIndex];
  14664. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14665. }
  14666. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14667. }
  14668. if (parsedCamera.autoAnimate) {
  14669. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14670. }
  14671. return camera;
  14672. };
  14673. return Camera;
  14674. }(BABYLON.Node));
  14675. // Statics
  14676. Camera._PERSPECTIVE_CAMERA = 0;
  14677. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14678. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14679. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14680. Camera._RIG_MODE_NONE = 0;
  14681. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14682. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14683. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14684. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14685. Camera._RIG_MODE_VR = 20;
  14686. Camera._RIG_MODE_WEBVR = 21;
  14687. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14688. __decorate([
  14689. BABYLON.serializeAsVector3()
  14690. ], Camera.prototype, "position", void 0);
  14691. __decorate([
  14692. BABYLON.serializeAsVector3()
  14693. ], Camera.prototype, "upVector", void 0);
  14694. __decorate([
  14695. BABYLON.serialize()
  14696. ], Camera.prototype, "orthoLeft", void 0);
  14697. __decorate([
  14698. BABYLON.serialize()
  14699. ], Camera.prototype, "orthoRight", void 0);
  14700. __decorate([
  14701. BABYLON.serialize()
  14702. ], Camera.prototype, "orthoBottom", void 0);
  14703. __decorate([
  14704. BABYLON.serialize()
  14705. ], Camera.prototype, "orthoTop", void 0);
  14706. __decorate([
  14707. BABYLON.serialize()
  14708. ], Camera.prototype, "fov", void 0);
  14709. __decorate([
  14710. BABYLON.serialize()
  14711. ], Camera.prototype, "minZ", void 0);
  14712. __decorate([
  14713. BABYLON.serialize()
  14714. ], Camera.prototype, "maxZ", void 0);
  14715. __decorate([
  14716. BABYLON.serialize()
  14717. ], Camera.prototype, "inertia", void 0);
  14718. __decorate([
  14719. BABYLON.serialize()
  14720. ], Camera.prototype, "mode", void 0);
  14721. __decorate([
  14722. BABYLON.serialize()
  14723. ], Camera.prototype, "layerMask", void 0);
  14724. __decorate([
  14725. BABYLON.serialize()
  14726. ], Camera.prototype, "fovMode", void 0);
  14727. __decorate([
  14728. BABYLON.serialize()
  14729. ], Camera.prototype, "cameraRigMode", void 0);
  14730. __decorate([
  14731. BABYLON.serialize()
  14732. ], Camera.prototype, "interaxialDistance", void 0);
  14733. __decorate([
  14734. BABYLON.serialize()
  14735. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14736. BABYLON.Camera = Camera;
  14737. })(BABYLON || (BABYLON = {}));
  14738. //# sourceMappingURL=babylon.camera.js.map
  14739. var BABYLON;
  14740. (function (BABYLON) {
  14741. var RenderingManager = (function () {
  14742. function RenderingManager(scene) {
  14743. this._renderingGroups = new Array();
  14744. this._autoClearDepthStencil = {};
  14745. this._customOpaqueSortCompareFn = {};
  14746. this._customAlphaTestSortCompareFn = {};
  14747. this._customTransparentSortCompareFn = {};
  14748. this._renderinGroupInfo = null;
  14749. this._scene = scene;
  14750. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14751. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14752. }
  14753. }
  14754. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14755. if (depth === void 0) { depth = true; }
  14756. if (stencil === void 0) { stencil = true; }
  14757. if (this._depthStencilBufferAlreadyCleaned) {
  14758. return;
  14759. }
  14760. this._scene.getEngine().clear(null, false, depth, stencil);
  14761. this._depthStencilBufferAlreadyCleaned = true;
  14762. };
  14763. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14764. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14765. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14766. var info = null;
  14767. if (observable) {
  14768. if (!this._renderinGroupInfo) {
  14769. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14770. }
  14771. info = this._renderinGroupInfo;
  14772. info.scene = this._scene;
  14773. info.camera = this._scene.activeCamera;
  14774. }
  14775. // Dispatch sprites
  14776. if (renderSprites) {
  14777. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14778. var manager = this._scene.spriteManagers[index];
  14779. this.dispatchSprites(manager);
  14780. }
  14781. }
  14782. // Render
  14783. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14784. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14785. var renderingGroup = this._renderingGroups[index];
  14786. if (!renderingGroup && !observable)
  14787. continue;
  14788. this._currentIndex = index;
  14789. var renderingGroupMask = 0;
  14790. // Fire PRECLEAR stage
  14791. if (observable) {
  14792. renderingGroupMask = Math.pow(2, index);
  14793. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14794. info.renderingGroupId = index;
  14795. observable.notifyObservers(info, renderingGroupMask);
  14796. }
  14797. // Clear depth/stencil if needed
  14798. if (RenderingManager.AUTOCLEAR) {
  14799. var autoClear = this._autoClearDepthStencil[index];
  14800. if (autoClear && autoClear.autoClear) {
  14801. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14802. }
  14803. }
  14804. if (observable) {
  14805. // Fire PREOPAQUE stage
  14806. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14807. observable.notifyObservers(info, renderingGroupMask);
  14808. // Fire PRETRANSPARENT stage
  14809. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14810. observable.notifyObservers(info, renderingGroupMask);
  14811. }
  14812. if (renderingGroup)
  14813. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14814. // Fire POSTTRANSPARENT stage
  14815. if (observable) {
  14816. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14817. observable.notifyObservers(info, renderingGroupMask);
  14818. }
  14819. }
  14820. };
  14821. RenderingManager.prototype.reset = function () {
  14822. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14823. var renderingGroup = this._renderingGroups[index];
  14824. if (renderingGroup) {
  14825. renderingGroup.prepare();
  14826. }
  14827. }
  14828. };
  14829. RenderingManager.prototype.dispose = function () {
  14830. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14831. var renderingGroup = this._renderingGroups[index];
  14832. if (renderingGroup) {
  14833. renderingGroup.dispose();
  14834. }
  14835. }
  14836. this._renderingGroups.length = 0;
  14837. };
  14838. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14839. if (!this._renderingGroups[renderingGroupId]) {
  14840. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14841. }
  14842. };
  14843. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14844. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14845. this._prepareRenderingGroup(renderingGroupId);
  14846. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14847. };
  14848. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14849. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14850. this._prepareRenderingGroup(renderingGroupId);
  14851. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14852. };
  14853. RenderingManager.prototype.dispatch = function (subMesh) {
  14854. var mesh = subMesh.getMesh();
  14855. var renderingGroupId = mesh.renderingGroupId || 0;
  14856. this._prepareRenderingGroup(renderingGroupId);
  14857. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14858. };
  14859. /**
  14860. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14861. * This allowed control for front to back rendering or reversly depending of the special needs.
  14862. *
  14863. * @param renderingGroupId The rendering group id corresponding to its index
  14864. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14865. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14866. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14867. */
  14868. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14869. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14870. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14871. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14872. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14873. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14874. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14875. if (this._renderingGroups[renderingGroupId]) {
  14876. var group = this._renderingGroups[renderingGroupId];
  14877. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14878. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14879. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14880. }
  14881. };
  14882. /**
  14883. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14884. *
  14885. * @param renderingGroupId The rendering group id corresponding to its index
  14886. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14887. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14888. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14889. */
  14890. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14891. if (depth === void 0) { depth = true; }
  14892. if (stencil === void 0) { stencil = true; }
  14893. this._autoClearDepthStencil[renderingGroupId] = {
  14894. autoClear: autoClearDepthStencil,
  14895. depth: depth,
  14896. stencil: stencil
  14897. };
  14898. };
  14899. return RenderingManager;
  14900. }());
  14901. /**
  14902. * The max id used for rendering groups (not included)
  14903. */
  14904. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14905. /**
  14906. * The min id used for rendering groups (included)
  14907. */
  14908. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14909. /**
  14910. * Used to globally prevent autoclearing scenes.
  14911. */
  14912. RenderingManager.AUTOCLEAR = true;
  14913. BABYLON.RenderingManager = RenderingManager;
  14914. })(BABYLON || (BABYLON = {}));
  14915. //# sourceMappingURL=babylon.renderingManager.js.map
  14916. var BABYLON;
  14917. (function (BABYLON) {
  14918. var RenderingGroup = (function () {
  14919. /**
  14920. * Creates a new rendering group.
  14921. * @param index The rendering group index
  14922. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14923. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14924. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14925. */
  14926. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14927. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14928. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14929. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14930. this.index = index;
  14931. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14932. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14933. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14934. this._particleSystems = new BABYLON.SmartArray(256);
  14935. this._spriteManagers = new BABYLON.SmartArray(256);
  14936. this._edgesRenderers = new BABYLON.SmartArray(16);
  14937. this._scene = scene;
  14938. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14939. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14940. this.transparentSortCompareFn = transparentSortCompareFn;
  14941. }
  14942. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14943. /**
  14944. * Set the opaque sort comparison function.
  14945. * If null the sub meshes will be render in the order they were created
  14946. */
  14947. set: function (value) {
  14948. this._opaqueSortCompareFn = value;
  14949. if (value) {
  14950. this._renderOpaque = this.renderOpaqueSorted;
  14951. }
  14952. else {
  14953. this._renderOpaque = RenderingGroup.renderUnsorted;
  14954. }
  14955. },
  14956. enumerable: true,
  14957. configurable: true
  14958. });
  14959. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14960. /**
  14961. * Set the alpha test sort comparison function.
  14962. * If null the sub meshes will be render in the order they were created
  14963. */
  14964. set: function (value) {
  14965. this._alphaTestSortCompareFn = value;
  14966. if (value) {
  14967. this._renderAlphaTest = this.renderAlphaTestSorted;
  14968. }
  14969. else {
  14970. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14971. }
  14972. },
  14973. enumerable: true,
  14974. configurable: true
  14975. });
  14976. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14977. /**
  14978. * Set the transparent sort comparison function.
  14979. * If null the sub meshes will be render in the order they were created
  14980. */
  14981. set: function (value) {
  14982. if (value) {
  14983. this._transparentSortCompareFn = value;
  14984. }
  14985. else {
  14986. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14987. }
  14988. this._renderTransparent = this.renderTransparentSorted;
  14989. },
  14990. enumerable: true,
  14991. configurable: true
  14992. });
  14993. /**
  14994. * Render all the sub meshes contained in the group.
  14995. * @param customRenderFunction Used to override the default render behaviour of the group.
  14996. * @returns true if rendered some submeshes.
  14997. */
  14998. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14999. if (customRenderFunction) {
  15000. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15001. return;
  15002. }
  15003. var engine = this._scene.getEngine();
  15004. // Opaque
  15005. if (this._opaqueSubMeshes.length !== 0) {
  15006. this._renderOpaque(this._opaqueSubMeshes);
  15007. }
  15008. // Alpha test
  15009. if (this._alphaTestSubMeshes.length !== 0) {
  15010. engine.setAlphaTesting(true);
  15011. this._renderAlphaTest(this._alphaTestSubMeshes);
  15012. engine.setAlphaTesting(false);
  15013. }
  15014. var stencilState = engine.getStencilBuffer();
  15015. engine.setStencilBuffer(false);
  15016. // Sprites
  15017. if (renderSprites) {
  15018. this._renderSprites();
  15019. }
  15020. // Particles
  15021. if (renderParticles) {
  15022. this._renderParticles(activeMeshes);
  15023. }
  15024. if (this.onBeforeTransparentRendering) {
  15025. this.onBeforeTransparentRendering();
  15026. }
  15027. // Transparent
  15028. if (this._transparentSubMeshes.length !== 0) {
  15029. this._renderTransparent(this._transparentSubMeshes);
  15030. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15031. }
  15032. engine.setStencilBuffer(stencilState);
  15033. // Edges
  15034. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15035. this._edgesRenderers.data[edgesRendererIndex].render();
  15036. }
  15037. };
  15038. /**
  15039. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15040. * @param subMeshes The submeshes to render
  15041. */
  15042. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15043. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15044. };
  15045. /**
  15046. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15047. * @param subMeshes The submeshes to render
  15048. */
  15049. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15050. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15051. };
  15052. /**
  15053. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15054. * @param subMeshes The submeshes to render
  15055. */
  15056. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15057. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15058. };
  15059. /**
  15060. * Renders the submeshes in a specified order.
  15061. * @param subMeshes The submeshes to sort before render
  15062. * @param sortCompareFn The comparison function use to sort
  15063. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15064. * @param transparent Specifies to activate blending if true
  15065. */
  15066. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15067. var subIndex = 0;
  15068. var subMesh;
  15069. for (; subIndex < subMeshes.length; subIndex++) {
  15070. subMesh = subMeshes.data[subIndex];
  15071. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15072. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15073. }
  15074. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15075. sortedArray.sort(sortCompareFn);
  15076. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15077. subMesh = sortedArray[subIndex];
  15078. subMesh.render(transparent);
  15079. }
  15080. };
  15081. /**
  15082. * Renders the submeshes in the order they were dispatched (no sort applied).
  15083. * @param subMeshes The submeshes to render
  15084. */
  15085. RenderingGroup.renderUnsorted = function (subMeshes) {
  15086. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15087. var submesh = subMeshes.data[subIndex];
  15088. submesh.render(false);
  15089. }
  15090. };
  15091. /**
  15092. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15093. * are rendered back to front if in the same alpha index.
  15094. *
  15095. * @param a The first submesh
  15096. * @param b The second submesh
  15097. * @returns The result of the comparison
  15098. */
  15099. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15100. // Alpha index first
  15101. if (a._alphaIndex > b._alphaIndex) {
  15102. return 1;
  15103. }
  15104. if (a._alphaIndex < b._alphaIndex) {
  15105. return -1;
  15106. }
  15107. // Then distance to camera
  15108. return RenderingGroup.backToFrontSortCompare(a, b);
  15109. };
  15110. /**
  15111. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15112. * are rendered back to front.
  15113. *
  15114. * @param a The first submesh
  15115. * @param b The second submesh
  15116. * @returns The result of the comparison
  15117. */
  15118. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15119. // Then distance to camera
  15120. if (a._distanceToCamera < b._distanceToCamera) {
  15121. return 1;
  15122. }
  15123. if (a._distanceToCamera > b._distanceToCamera) {
  15124. return -1;
  15125. }
  15126. return 0;
  15127. };
  15128. /**
  15129. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15130. * are rendered front to back (prevent overdraw).
  15131. *
  15132. * @param a The first submesh
  15133. * @param b The second submesh
  15134. * @returns The result of the comparison
  15135. */
  15136. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15137. // Then distance to camera
  15138. if (a._distanceToCamera < b._distanceToCamera) {
  15139. return -1;
  15140. }
  15141. if (a._distanceToCamera > b._distanceToCamera) {
  15142. return 1;
  15143. }
  15144. return 0;
  15145. };
  15146. /**
  15147. * Resets the different lists of submeshes to prepare a new frame.
  15148. */
  15149. RenderingGroup.prototype.prepare = function () {
  15150. this._opaqueSubMeshes.reset();
  15151. this._transparentSubMeshes.reset();
  15152. this._alphaTestSubMeshes.reset();
  15153. this._particleSystems.reset();
  15154. this._spriteManagers.reset();
  15155. this._edgesRenderers.reset();
  15156. };
  15157. RenderingGroup.prototype.dispose = function () {
  15158. this._opaqueSubMeshes.dispose();
  15159. this._transparentSubMeshes.dispose();
  15160. this._alphaTestSubMeshes.dispose();
  15161. this._particleSystems.dispose();
  15162. this._spriteManagers.dispose();
  15163. this._edgesRenderers.dispose();
  15164. };
  15165. /**
  15166. * Inserts the submesh in its correct queue depending on its material.
  15167. * @param subMesh The submesh to dispatch
  15168. */
  15169. RenderingGroup.prototype.dispatch = function (subMesh) {
  15170. var material = subMesh.getMaterial();
  15171. var mesh = subMesh.getMesh();
  15172. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15173. this._transparentSubMeshes.push(subMesh);
  15174. }
  15175. else if (material.needAlphaTesting()) {
  15176. this._alphaTestSubMeshes.push(subMesh);
  15177. }
  15178. else {
  15179. this._opaqueSubMeshes.push(subMesh); // Opaque
  15180. }
  15181. if (mesh._edgesRenderer) {
  15182. this._edgesRenderers.push(mesh._edgesRenderer);
  15183. }
  15184. };
  15185. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15186. this._spriteManagers.push(spriteManager);
  15187. };
  15188. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15189. this._particleSystems.push(particleSystem);
  15190. };
  15191. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15192. if (this._particleSystems.length === 0) {
  15193. return;
  15194. }
  15195. // Particles
  15196. var activeCamera = this._scene.activeCamera;
  15197. this._scene._particlesDuration.beginMonitoring();
  15198. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15199. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15200. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15201. continue;
  15202. }
  15203. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15204. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15205. }
  15206. }
  15207. this._scene._particlesDuration.endMonitoring(false);
  15208. };
  15209. RenderingGroup.prototype._renderSprites = function () {
  15210. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15211. return;
  15212. }
  15213. // Sprites
  15214. var activeCamera = this._scene.activeCamera;
  15215. this._scene._spritesDuration.beginMonitoring();
  15216. for (var id = 0; id < this._spriteManagers.length; id++) {
  15217. var spriteManager = this._spriteManagers.data[id];
  15218. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15219. spriteManager.render();
  15220. }
  15221. }
  15222. this._scene._spritesDuration.endMonitoring(false);
  15223. };
  15224. return RenderingGroup;
  15225. }());
  15226. BABYLON.RenderingGroup = RenderingGroup;
  15227. })(BABYLON || (BABYLON = {}));
  15228. //# sourceMappingURL=babylon.renderingGroup.js.map
  15229. var BABYLON;
  15230. (function (BABYLON) {
  15231. var ClickInfo = (function () {
  15232. function ClickInfo() {
  15233. this._singleClick = false;
  15234. this._doubleClick = false;
  15235. this._hasSwiped = false;
  15236. this._ignore = false;
  15237. }
  15238. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15239. get: function () {
  15240. return this._singleClick;
  15241. },
  15242. set: function (b) {
  15243. this._singleClick = b;
  15244. },
  15245. enumerable: true,
  15246. configurable: true
  15247. });
  15248. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15249. get: function () {
  15250. return this._doubleClick;
  15251. },
  15252. set: function (b) {
  15253. this._doubleClick = b;
  15254. },
  15255. enumerable: true,
  15256. configurable: true
  15257. });
  15258. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15259. get: function () {
  15260. return this._hasSwiped;
  15261. },
  15262. set: function (b) {
  15263. this._hasSwiped = b;
  15264. },
  15265. enumerable: true,
  15266. configurable: true
  15267. });
  15268. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15269. get: function () {
  15270. return this._ignore;
  15271. },
  15272. set: function (b) {
  15273. this._ignore = b;
  15274. },
  15275. enumerable: true,
  15276. configurable: true
  15277. });
  15278. return ClickInfo;
  15279. }());
  15280. var PointerEventTypes = (function () {
  15281. function PointerEventTypes() {
  15282. }
  15283. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15284. get: function () {
  15285. return PointerEventTypes._POINTERDOWN;
  15286. },
  15287. enumerable: true,
  15288. configurable: true
  15289. });
  15290. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15291. get: function () {
  15292. return PointerEventTypes._POINTERUP;
  15293. },
  15294. enumerable: true,
  15295. configurable: true
  15296. });
  15297. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15298. get: function () {
  15299. return PointerEventTypes._POINTERMOVE;
  15300. },
  15301. enumerable: true,
  15302. configurable: true
  15303. });
  15304. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15305. get: function () {
  15306. return PointerEventTypes._POINTERWHEEL;
  15307. },
  15308. enumerable: true,
  15309. configurable: true
  15310. });
  15311. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15312. get: function () {
  15313. return PointerEventTypes._POINTERPICK;
  15314. },
  15315. enumerable: true,
  15316. configurable: true
  15317. });
  15318. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15319. get: function () {
  15320. return PointerEventTypes._POINTERTAP;
  15321. },
  15322. enumerable: true,
  15323. configurable: true
  15324. });
  15325. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15326. get: function () {
  15327. return PointerEventTypes._POINTERDOUBLETAP;
  15328. },
  15329. enumerable: true,
  15330. configurable: true
  15331. });
  15332. return PointerEventTypes;
  15333. }());
  15334. PointerEventTypes._POINTERDOWN = 0x01;
  15335. PointerEventTypes._POINTERUP = 0x02;
  15336. PointerEventTypes._POINTERMOVE = 0x04;
  15337. PointerEventTypes._POINTERWHEEL = 0x08;
  15338. PointerEventTypes._POINTERPICK = 0x10;
  15339. PointerEventTypes._POINTERTAP = 0x20;
  15340. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15341. BABYLON.PointerEventTypes = PointerEventTypes;
  15342. var PointerInfoBase = (function () {
  15343. function PointerInfoBase(type, event) {
  15344. this.type = type;
  15345. this.event = event;
  15346. }
  15347. return PointerInfoBase;
  15348. }());
  15349. BABYLON.PointerInfoBase = PointerInfoBase;
  15350. /**
  15351. * This class is used to store pointer related info for the onPrePointerObservable event.
  15352. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15353. */
  15354. var PointerInfoPre = (function (_super) {
  15355. __extends(PointerInfoPre, _super);
  15356. function PointerInfoPre(type, event, localX, localY) {
  15357. var _this = _super.call(this, type, event) || this;
  15358. _this.skipOnPointerObservable = false;
  15359. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15360. return _this;
  15361. }
  15362. return PointerInfoPre;
  15363. }(PointerInfoBase));
  15364. BABYLON.PointerInfoPre = PointerInfoPre;
  15365. /**
  15366. * This type contains all the data related to a pointer event in Babylon.js.
  15367. * 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.
  15368. */
  15369. var PointerInfo = (function (_super) {
  15370. __extends(PointerInfo, _super);
  15371. function PointerInfo(type, event, pickInfo) {
  15372. var _this = _super.call(this, type, event) || this;
  15373. _this.pickInfo = pickInfo;
  15374. return _this;
  15375. }
  15376. return PointerInfo;
  15377. }(PointerInfoBase));
  15378. BABYLON.PointerInfo = PointerInfo;
  15379. /**
  15380. * This class is used by the onRenderingGroupObservable
  15381. */
  15382. var RenderingGroupInfo = (function () {
  15383. function RenderingGroupInfo() {
  15384. }
  15385. return RenderingGroupInfo;
  15386. }());
  15387. /**
  15388. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15389. * This stage will be fired no matter what
  15390. */
  15391. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15392. /**
  15393. * Called before opaque object are rendered.
  15394. * This stage will be fired only if there's 3D Opaque content to render
  15395. */
  15396. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15397. /**
  15398. * Called after the opaque objects are rendered and before the transparent ones
  15399. * This stage will be fired only if there's 3D transparent content to render
  15400. */
  15401. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15402. /**
  15403. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15404. * This stage will be fired no matter what
  15405. */
  15406. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15407. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15408. /**
  15409. * Represents a scene to be rendered by the engine.
  15410. * @see http://doc.babylonjs.com/page.php?p=21911
  15411. */
  15412. var Scene = (function () {
  15413. /**
  15414. * @constructor
  15415. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15416. */
  15417. function Scene(engine) {
  15418. // Members
  15419. this.autoClear = true;
  15420. this.autoClearDepthAndStencil = true;
  15421. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15422. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15423. this.forceWireframe = false;
  15424. this._forcePointsCloud = false;
  15425. this.forceShowBoundingBoxes = false;
  15426. this.animationsEnabled = true;
  15427. this.constantlyUpdateMeshUnderPointer = false;
  15428. this.hoverCursor = "pointer";
  15429. // Metadata
  15430. this.metadata = null;
  15431. // Events
  15432. /**
  15433. * An event triggered when the scene is disposed.
  15434. * @type {BABYLON.Observable}
  15435. */
  15436. this.onDisposeObservable = new BABYLON.Observable();
  15437. /**
  15438. * An event triggered before rendering the scene
  15439. * @type {BABYLON.Observable}
  15440. */
  15441. this.onBeforeRenderObservable = new BABYLON.Observable();
  15442. /**
  15443. * An event triggered after rendering the scene
  15444. * @type {BABYLON.Observable}
  15445. */
  15446. this.onAfterRenderObservable = new BABYLON.Observable();
  15447. /**
  15448. * An event triggered when the scene is ready
  15449. * @type {BABYLON.Observable}
  15450. */
  15451. this.onReadyObservable = new BABYLON.Observable();
  15452. /**
  15453. * An event triggered before rendering a camera
  15454. * @type {BABYLON.Observable}
  15455. */
  15456. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15457. /**
  15458. * An event triggered after rendering a camera
  15459. * @type {BABYLON.Observable}
  15460. */
  15461. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15462. /**
  15463. * An event triggered when a camera is created
  15464. * @type {BABYLON.Observable}
  15465. */
  15466. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15467. /**
  15468. * An event triggered when a camera is removed
  15469. * @type {BABYLON.Observable}
  15470. */
  15471. this.onCameraRemovedObservable = new BABYLON.Observable();
  15472. /**
  15473. * An event triggered when a light is created
  15474. * @type {BABYLON.Observable}
  15475. */
  15476. this.onNewLightAddedObservable = new BABYLON.Observable();
  15477. /**
  15478. * An event triggered when a light is removed
  15479. * @type {BABYLON.Observable}
  15480. */
  15481. this.onLightRemovedObservable = new BABYLON.Observable();
  15482. /**
  15483. * An event triggered when a geometry is created
  15484. * @type {BABYLON.Observable}
  15485. */
  15486. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15487. /**
  15488. * An event triggered when a geometry is removed
  15489. * @type {BABYLON.Observable}
  15490. */
  15491. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15492. /**
  15493. * An event triggered when a mesh is created
  15494. * @type {BABYLON.Observable}
  15495. */
  15496. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15497. /**
  15498. * An event triggered when a mesh is removed
  15499. * @type {BABYLON.Observable}
  15500. */
  15501. this.onMeshRemovedObservable = new BABYLON.Observable();
  15502. /**
  15503. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15504. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15505. * 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)
  15506. */
  15507. this.onRenderingGroupObservable = new BABYLON.Observable();
  15508. // Animations
  15509. this.animations = [];
  15510. /**
  15511. * 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).
  15512. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15513. */
  15514. this.onPrePointerObservable = new BABYLON.Observable();
  15515. /**
  15516. * Observable event triggered each time an input event is received from the rendering canvas
  15517. */
  15518. this.onPointerObservable = new BABYLON.Observable();
  15519. this._meshPickProceed = false;
  15520. this._previousHasSwiped = false;
  15521. this._currentPickResult = null;
  15522. this._previousPickResult = null;
  15523. this._isButtonPressed = false;
  15524. this._doubleClickOccured = false;
  15525. 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
  15526. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15527. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15528. this._startingPointerTime = 0;
  15529. this._previousStartingPointerTime = 0;
  15530. // Coordinate system
  15531. /**
  15532. * use right-handed coordinate system on this scene.
  15533. * @type {boolean}
  15534. */
  15535. this._useRightHandedSystem = false;
  15536. // Fog
  15537. /**
  15538. * is fog enabled on this scene.
  15539. * @type {boolean}
  15540. */
  15541. this._fogEnabled = true;
  15542. this._fogMode = Scene.FOGMODE_NONE;
  15543. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15544. this.fogDensity = 0.1;
  15545. this.fogStart = 0;
  15546. this.fogEnd = 1000.0;
  15547. // Lights
  15548. /**
  15549. * is shadow enabled on this scene.
  15550. * @type {boolean}
  15551. */
  15552. this._shadowsEnabled = true;
  15553. /**
  15554. * is light enabled on this scene.
  15555. * @type {boolean}
  15556. */
  15557. this._lightsEnabled = true;
  15558. /**
  15559. * All of the lights added to this scene.
  15560. * @see BABYLON.Light
  15561. * @type {BABYLON.Light[]}
  15562. */
  15563. this.lights = new Array();
  15564. // Cameras
  15565. /**
  15566. * All of the cameras added to this scene.
  15567. * @see BABYLON.Camera
  15568. * @type {BABYLON.Camera[]}
  15569. */
  15570. this.cameras = new Array();
  15571. this.activeCameras = new Array();
  15572. // Meshes
  15573. /**
  15574. * All of the (abstract) meshes added to this scene.
  15575. * @see BABYLON.AbstractMesh
  15576. * @type {BABYLON.AbstractMesh[]}
  15577. */
  15578. this.meshes = new Array();
  15579. // Geometries
  15580. this._geometries = new Array();
  15581. this.materials = new Array();
  15582. this.multiMaterials = new Array();
  15583. // Textures
  15584. this._texturesEnabled = true;
  15585. this.textures = new Array();
  15586. // Particles
  15587. this.particlesEnabled = true;
  15588. this.particleSystems = new Array();
  15589. // Sprites
  15590. this.spritesEnabled = true;
  15591. this.spriteManagers = new Array();
  15592. // Layers
  15593. this.layers = new Array();
  15594. this.highlightLayers = new Array();
  15595. // Skeletons
  15596. this._skeletonsEnabled = true;
  15597. this.skeletons = new Array();
  15598. // Morph targets
  15599. this.morphTargetManagers = new Array();
  15600. // Lens flares
  15601. this.lensFlaresEnabled = true;
  15602. this.lensFlareSystems = new Array();
  15603. // Collisions
  15604. this.collisionsEnabled = true;
  15605. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15606. // Postprocesses
  15607. this.postProcessesEnabled = true;
  15608. // Customs render targets
  15609. this.renderTargetsEnabled = true;
  15610. this.dumpNextRenderTargets = false;
  15611. this.customRenderTargets = new Array();
  15612. // Imported meshes
  15613. this.importedMeshesFiles = new Array();
  15614. // Probes
  15615. this.probesEnabled = true;
  15616. this.reflectionProbes = new Array();
  15617. this._actionManagers = new Array();
  15618. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15619. // Procedural textures
  15620. this.proceduralTexturesEnabled = true;
  15621. this._proceduralTextures = new Array();
  15622. this.soundTracks = new Array();
  15623. this._audioEnabled = true;
  15624. this._headphone = false;
  15625. // Performance counters
  15626. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15627. this._totalLightsCounter = new BABYLON.PerfCounter();
  15628. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15629. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15630. this._totalVertices = new BABYLON.PerfCounter();
  15631. this._activeIndices = new BABYLON.PerfCounter();
  15632. this._activeParticles = new BABYLON.PerfCounter();
  15633. this._lastFrameDuration = new BABYLON.PerfCounter();
  15634. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15635. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15636. this._particlesDuration = new BABYLON.PerfCounter();
  15637. this._renderDuration = new BABYLON.PerfCounter();
  15638. this._spritesDuration = new BABYLON.PerfCounter();
  15639. this._activeBones = new BABYLON.PerfCounter();
  15640. this._animationTime = 0;
  15641. this.animationTimeScale = 1;
  15642. this._renderId = 0;
  15643. this._executeWhenReadyTimeoutId = -1;
  15644. this._intermediateRendering = false;
  15645. this._viewUpdateFlag = -1;
  15646. this._projectionUpdateFlag = -1;
  15647. this._toBeDisposed = new BABYLON.SmartArray(256);
  15648. this._pendingData = []; //ANY
  15649. this._activeMeshes = new BABYLON.SmartArray(256);
  15650. this._processedMaterials = new BABYLON.SmartArray(256);
  15651. this._renderTargets = new BABYLON.SmartArray(256);
  15652. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15653. this._activeSkeletons = new BABYLON.SmartArray(32);
  15654. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15655. this._activeAnimatables = new Array();
  15656. this._transformMatrix = BABYLON.Matrix.Zero();
  15657. this.requireLightSorting = false;
  15658. this._uniqueIdCounter = 0;
  15659. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15660. this._engine.scenes.push(this);
  15661. this._uid = null;
  15662. this._renderingManager = new BABYLON.RenderingManager(this);
  15663. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15664. if (BABYLON.OutlineRenderer) {
  15665. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15666. }
  15667. this.attachControl();
  15668. if (BABYLON.SoundTrack) {
  15669. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15670. }
  15671. //simplification queue
  15672. if (BABYLON.SimplificationQueue) {
  15673. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15674. }
  15675. //collision coordinator initialization. For now legacy per default.
  15676. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15677. // Uniform Buffer
  15678. this._createUbo();
  15679. // Default Image processing definition.
  15680. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  15681. }
  15682. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15683. get: function () {
  15684. return Scene._FOGMODE_NONE;
  15685. },
  15686. enumerable: true,
  15687. configurable: true
  15688. });
  15689. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15690. get: function () {
  15691. return Scene._FOGMODE_EXP;
  15692. },
  15693. enumerable: true,
  15694. configurable: true
  15695. });
  15696. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15697. get: function () {
  15698. return Scene._FOGMODE_EXP2;
  15699. },
  15700. enumerable: true,
  15701. configurable: true
  15702. });
  15703. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15704. get: function () {
  15705. return Scene._FOGMODE_LINEAR;
  15706. },
  15707. enumerable: true,
  15708. configurable: true
  15709. });
  15710. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15711. /**
  15712. * Texture used in all pbr material as the reflection texture.
  15713. * As in the majority of the scene they are the same (exception for multi room and so on),
  15714. * this is easier to reference from here than from all the materials.
  15715. */
  15716. get: function () {
  15717. return this._environmentTexture;
  15718. },
  15719. /**
  15720. * Texture used in all pbr material as the reflection texture.
  15721. * As in the majority of the scene they are the same (exception for multi room and so on),
  15722. * this is easier to set here than in all the materials.
  15723. */
  15724. set: function (value) {
  15725. this._environmentTexture = value;
  15726. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15727. },
  15728. enumerable: true,
  15729. configurable: true
  15730. });
  15731. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  15732. /**
  15733. * Default image processing configuration used either in the rendering
  15734. * Forward main pass or through the imageProcessingPostProcess if present.
  15735. * As in the majority of the scene they are the same (exception for multi camera),
  15736. * this is easier to reference from here than from all the materials and post process.
  15737. *
  15738. * No setter as we it is a shared configuration, you can set the values instead.
  15739. */
  15740. get: function () {
  15741. return this._imageProcessingConfiguration;
  15742. },
  15743. enumerable: true,
  15744. configurable: true
  15745. });
  15746. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15747. get: function () {
  15748. return this._forcePointsCloud;
  15749. },
  15750. set: function (value) {
  15751. if (this._forcePointsCloud === value) {
  15752. return;
  15753. }
  15754. this._forcePointsCloud = value;
  15755. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15756. },
  15757. enumerable: true,
  15758. configurable: true
  15759. });
  15760. Object.defineProperty(Scene.prototype, "onDispose", {
  15761. set: function (callback) {
  15762. if (this._onDisposeObserver) {
  15763. this.onDisposeObservable.remove(this._onDisposeObserver);
  15764. }
  15765. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15766. },
  15767. enumerable: true,
  15768. configurable: true
  15769. });
  15770. Object.defineProperty(Scene.prototype, "beforeRender", {
  15771. set: function (callback) {
  15772. if (this._onBeforeRenderObserver) {
  15773. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15774. }
  15775. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15776. },
  15777. enumerable: true,
  15778. configurable: true
  15779. });
  15780. Object.defineProperty(Scene.prototype, "afterRender", {
  15781. set: function (callback) {
  15782. if (this._onAfterRenderObserver) {
  15783. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15784. }
  15785. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15786. },
  15787. enumerable: true,
  15788. configurable: true
  15789. });
  15790. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15791. set: function (callback) {
  15792. if (this._onBeforeCameraRenderObserver) {
  15793. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15794. }
  15795. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15796. },
  15797. enumerable: true,
  15798. configurable: true
  15799. });
  15800. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15801. set: function (callback) {
  15802. if (this._onAfterCameraRenderObserver) {
  15803. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15804. }
  15805. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15806. },
  15807. enumerable: true,
  15808. configurable: true
  15809. });
  15810. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15811. get: function () {
  15812. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15813. },
  15814. enumerable: true,
  15815. configurable: true
  15816. });
  15817. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15818. get: function () {
  15819. return this._useRightHandedSystem;
  15820. },
  15821. set: function (value) {
  15822. if (this._useRightHandedSystem === value) {
  15823. return;
  15824. }
  15825. this._useRightHandedSystem = value;
  15826. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15827. },
  15828. enumerable: true,
  15829. configurable: true
  15830. });
  15831. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15832. get: function () {
  15833. return this._fogEnabled;
  15834. },
  15835. set: function (value) {
  15836. if (this._fogEnabled === value) {
  15837. return;
  15838. }
  15839. this._fogEnabled = value;
  15840. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15841. },
  15842. enumerable: true,
  15843. configurable: true
  15844. });
  15845. Object.defineProperty(Scene.prototype, "fogMode", {
  15846. get: function () {
  15847. return this._fogMode;
  15848. },
  15849. set: function (value) {
  15850. if (this._fogMode === value) {
  15851. return;
  15852. }
  15853. this._fogMode = value;
  15854. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15855. },
  15856. enumerable: true,
  15857. configurable: true
  15858. });
  15859. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15860. get: function () {
  15861. return this._shadowsEnabled;
  15862. },
  15863. set: function (value) {
  15864. if (this._shadowsEnabled === value) {
  15865. return;
  15866. }
  15867. this._shadowsEnabled = value;
  15868. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15869. },
  15870. enumerable: true,
  15871. configurable: true
  15872. });
  15873. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15874. get: function () {
  15875. return this._lightsEnabled;
  15876. },
  15877. set: function (value) {
  15878. if (this._lightsEnabled === value) {
  15879. return;
  15880. }
  15881. this._lightsEnabled = value;
  15882. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15883. },
  15884. enumerable: true,
  15885. configurable: true
  15886. });
  15887. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15888. get: function () {
  15889. if (!this._defaultMaterial) {
  15890. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15891. }
  15892. return this._defaultMaterial;
  15893. },
  15894. set: function (value) {
  15895. this._defaultMaterial = value;
  15896. },
  15897. enumerable: true,
  15898. configurable: true
  15899. });
  15900. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15901. get: function () {
  15902. return this._texturesEnabled;
  15903. },
  15904. set: function (value) {
  15905. if (this._texturesEnabled === value) {
  15906. return;
  15907. }
  15908. this._texturesEnabled = value;
  15909. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15910. },
  15911. enumerable: true,
  15912. configurable: true
  15913. });
  15914. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15915. get: function () {
  15916. return this._skeletonsEnabled;
  15917. },
  15918. set: function (value) {
  15919. if (this._skeletonsEnabled === value) {
  15920. return;
  15921. }
  15922. this._skeletonsEnabled = value;
  15923. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15924. },
  15925. enumerable: true,
  15926. configurable: true
  15927. });
  15928. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15929. get: function () {
  15930. if (!this._postProcessRenderPipelineManager) {
  15931. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15932. }
  15933. return this._postProcessRenderPipelineManager;
  15934. },
  15935. enumerable: true,
  15936. configurable: true
  15937. });
  15938. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15939. get: function () {
  15940. return this._frustumPlanes;
  15941. },
  15942. enumerable: true,
  15943. configurable: true
  15944. });
  15945. Object.defineProperty(Scene.prototype, "debugLayer", {
  15946. // Properties
  15947. get: function () {
  15948. if (!this._debugLayer) {
  15949. this._debugLayer = new BABYLON.DebugLayer(this);
  15950. }
  15951. return this._debugLayer;
  15952. },
  15953. enumerable: true,
  15954. configurable: true
  15955. });
  15956. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15957. get: function () {
  15958. return this._workerCollisions;
  15959. },
  15960. set: function (enabled) {
  15961. if (!BABYLON.CollisionCoordinatorLegacy) {
  15962. return;
  15963. }
  15964. enabled = (enabled && !!Worker);
  15965. this._workerCollisions = enabled;
  15966. if (this.collisionCoordinator) {
  15967. this.collisionCoordinator.destroy();
  15968. }
  15969. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15970. this.collisionCoordinator.init(this);
  15971. },
  15972. enumerable: true,
  15973. configurable: true
  15974. });
  15975. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15976. get: function () {
  15977. return this._selectionOctree;
  15978. },
  15979. enumerable: true,
  15980. configurable: true
  15981. });
  15982. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15983. /**
  15984. * The mesh that is currently under the pointer.
  15985. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15986. */
  15987. get: function () {
  15988. return this._pointerOverMesh;
  15989. },
  15990. enumerable: true,
  15991. configurable: true
  15992. });
  15993. Object.defineProperty(Scene.prototype, "pointerX", {
  15994. /**
  15995. * Current on-screen X position of the pointer
  15996. * @return {number} X position of the pointer
  15997. */
  15998. get: function () {
  15999. return this._pointerX;
  16000. },
  16001. enumerable: true,
  16002. configurable: true
  16003. });
  16004. Object.defineProperty(Scene.prototype, "pointerY", {
  16005. /**
  16006. * Current on-screen Y position of the pointer
  16007. * @return {number} Y position of the pointer
  16008. */
  16009. get: function () {
  16010. return this._pointerY;
  16011. },
  16012. enumerable: true,
  16013. configurable: true
  16014. });
  16015. Scene.prototype.getCachedMaterial = function () {
  16016. return this._cachedMaterial;
  16017. };
  16018. Scene.prototype.getCachedEffect = function () {
  16019. return this._cachedEffect;
  16020. };
  16021. Scene.prototype.getCachedVisibility = function () {
  16022. return this._cachedVisibility;
  16023. };
  16024. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  16025. if (visibility === void 0) { visibility = 0; }
  16026. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16027. };
  16028. Scene.prototype.getBoundingBoxRenderer = function () {
  16029. if (!this._boundingBoxRenderer) {
  16030. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16031. }
  16032. return this._boundingBoxRenderer;
  16033. };
  16034. Scene.prototype.getOutlineRenderer = function () {
  16035. return this._outlineRenderer;
  16036. };
  16037. Scene.prototype.getEngine = function () {
  16038. return this._engine;
  16039. };
  16040. Scene.prototype.getTotalVertices = function () {
  16041. return this._totalVertices.current;
  16042. };
  16043. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16044. get: function () {
  16045. return this._totalVertices;
  16046. },
  16047. enumerable: true,
  16048. configurable: true
  16049. });
  16050. Scene.prototype.getActiveIndices = function () {
  16051. return this._activeIndices.current;
  16052. };
  16053. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16054. get: function () {
  16055. return this._activeIndices;
  16056. },
  16057. enumerable: true,
  16058. configurable: true
  16059. });
  16060. Scene.prototype.getActiveParticles = function () {
  16061. return this._activeParticles.current;
  16062. };
  16063. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16064. get: function () {
  16065. return this._activeParticles;
  16066. },
  16067. enumerable: true,
  16068. configurable: true
  16069. });
  16070. Scene.prototype.getActiveBones = function () {
  16071. return this._activeBones.current;
  16072. };
  16073. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16074. get: function () {
  16075. return this._activeBones;
  16076. },
  16077. enumerable: true,
  16078. configurable: true
  16079. });
  16080. // Stats
  16081. Scene.prototype.getLastFrameDuration = function () {
  16082. return this._lastFrameDuration.current;
  16083. };
  16084. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16085. get: function () {
  16086. return this._lastFrameDuration;
  16087. },
  16088. enumerable: true,
  16089. configurable: true
  16090. });
  16091. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16092. return this._evaluateActiveMeshesDuration.current;
  16093. };
  16094. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16095. get: function () {
  16096. return this._evaluateActiveMeshesDuration;
  16097. },
  16098. enumerable: true,
  16099. configurable: true
  16100. });
  16101. Scene.prototype.getActiveMeshes = function () {
  16102. return this._activeMeshes;
  16103. };
  16104. Scene.prototype.getRenderTargetsDuration = function () {
  16105. return this._renderTargetsDuration.current;
  16106. };
  16107. Scene.prototype.getRenderDuration = function () {
  16108. return this._renderDuration.current;
  16109. };
  16110. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16111. get: function () {
  16112. return this._renderDuration;
  16113. },
  16114. enumerable: true,
  16115. configurable: true
  16116. });
  16117. Scene.prototype.getParticlesDuration = function () {
  16118. return this._particlesDuration.current;
  16119. };
  16120. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16121. get: function () {
  16122. return this._particlesDuration;
  16123. },
  16124. enumerable: true,
  16125. configurable: true
  16126. });
  16127. Scene.prototype.getSpritesDuration = function () {
  16128. return this._spritesDuration.current;
  16129. };
  16130. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16131. get: function () {
  16132. return this._spritesDuration;
  16133. },
  16134. enumerable: true,
  16135. configurable: true
  16136. });
  16137. Scene.prototype.getAnimationRatio = function () {
  16138. return this._animationRatio;
  16139. };
  16140. Scene.prototype.getRenderId = function () {
  16141. return this._renderId;
  16142. };
  16143. Scene.prototype.incrementRenderId = function () {
  16144. this._renderId++;
  16145. };
  16146. Scene.prototype._updatePointerPosition = function (evt) {
  16147. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16148. this._pointerX = evt.clientX - canvasRect.left;
  16149. this._pointerY = evt.clientY - canvasRect.top;
  16150. this._unTranslatedPointerX = this._pointerX;
  16151. this._unTranslatedPointerY = this._pointerY;
  16152. if (this.cameraToUseForPointers) {
  16153. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16154. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16155. }
  16156. };
  16157. Scene.prototype._createUbo = function () {
  16158. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16159. this._sceneUbo.addUniform("viewProjection", 16);
  16160. this._sceneUbo.addUniform("view", 16);
  16161. };
  16162. // Pointers handling
  16163. /**
  16164. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16165. * @param attachUp defines if you want to attach events to pointerup
  16166. * @param attachDown defines if you want to attach events to pointerdown
  16167. * @param attachMove defines if you want to attach events to pointermove
  16168. */
  16169. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16170. var _this = this;
  16171. if (attachUp === void 0) { attachUp = true; }
  16172. if (attachDown === void 0) { attachDown = true; }
  16173. if (attachMove === void 0) { attachMove = true; }
  16174. this._initActionManager = function (act, clickInfo) {
  16175. if (!_this._meshPickProceed) {
  16176. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16177. _this._currentPickResult = pickResult;
  16178. if (pickResult) {
  16179. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16180. }
  16181. _this._meshPickProceed = true;
  16182. }
  16183. return act;
  16184. };
  16185. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16186. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16187. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16188. btn !== _this._previousButtonPressed) {
  16189. _this._doubleClickOccured = false;
  16190. clickInfo.singleClick = true;
  16191. clickInfo.ignore = false;
  16192. cb(clickInfo, _this._currentPickResult);
  16193. }
  16194. };
  16195. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16196. var clickInfo = new ClickInfo();
  16197. _this._currentPickResult = null;
  16198. var act;
  16199. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16200. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16201. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16202. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16203. act = _this._initActionManager(act, clickInfo);
  16204. if (act)
  16205. checkPicking = act.hasPickTriggers;
  16206. }
  16207. if (checkPicking) {
  16208. var btn = evt.button;
  16209. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16210. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16211. if (!clickInfo.hasSwiped) {
  16212. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16213. if (!checkSingleClickImmediately) {
  16214. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16215. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16216. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16217. act = _this._initActionManager(act, clickInfo);
  16218. if (act)
  16219. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16220. }
  16221. }
  16222. if (checkSingleClickImmediately) {
  16223. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16224. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16225. btn !== _this._previousButtonPressed) {
  16226. clickInfo.singleClick = true;
  16227. cb(clickInfo, _this._currentPickResult);
  16228. }
  16229. }
  16230. else {
  16231. // wait that no double click has been raised during the double click delay
  16232. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16233. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16234. }
  16235. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16236. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16237. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16238. act = _this._initActionManager(act, clickInfo);
  16239. if (act)
  16240. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16241. }
  16242. if (checkDoubleClick) {
  16243. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16244. if (btn === _this._previousButtonPressed &&
  16245. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16246. !_this._doubleClickOccured) {
  16247. // pointer has not moved for 2 clicks, it's a double click
  16248. if (!clickInfo.hasSwiped &&
  16249. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16250. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16251. _this._previousStartingPointerTime = 0;
  16252. _this._doubleClickOccured = true;
  16253. clickInfo.doubleClick = true;
  16254. clickInfo.ignore = false;
  16255. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16256. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16257. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16258. cb(clickInfo, _this._currentPickResult);
  16259. }
  16260. else {
  16261. _this._doubleClickOccured = false;
  16262. _this._previousStartingPointerTime = _this._startingPointerTime;
  16263. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16264. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16265. _this._previousButtonPressed = btn;
  16266. _this._previousHasSwiped = clickInfo.hasSwiped;
  16267. if (Scene.ExclusiveDoubleClickMode) {
  16268. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16269. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16270. }
  16271. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16272. cb(clickInfo, _this._previousPickResult);
  16273. }
  16274. else {
  16275. cb(clickInfo, _this._currentPickResult);
  16276. }
  16277. }
  16278. }
  16279. else {
  16280. _this._doubleClickOccured = false;
  16281. _this._previousStartingPointerTime = _this._startingPointerTime;
  16282. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16283. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16284. _this._previousButtonPressed = btn;
  16285. _this._previousHasSwiped = clickInfo.hasSwiped;
  16286. }
  16287. }
  16288. }
  16289. }
  16290. clickInfo.ignore = true;
  16291. cb(clickInfo, _this._currentPickResult);
  16292. };
  16293. var spritePredicate = function (sprite) {
  16294. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16295. };
  16296. this._onPointerMove = function (evt) {
  16297. _this._updatePointerPosition(evt);
  16298. // PreObservable support
  16299. if (_this.onPrePointerObservable.hasObservers()) {
  16300. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16301. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16302. _this.onPrePointerObservable.notifyObservers(pi, type);
  16303. if (pi.skipOnPointerObservable) {
  16304. return;
  16305. }
  16306. }
  16307. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16308. return;
  16309. }
  16310. var canvas = _this._engine.getRenderingCanvas();
  16311. if (!_this.pointerMovePredicate) {
  16312. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16313. }
  16314. // Meshes
  16315. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16316. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16317. _this.setPointerOverSprite(null);
  16318. _this.setPointerOverMesh(pickResult.pickedMesh);
  16319. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16320. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16321. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16322. }
  16323. else {
  16324. canvas.style.cursor = _this.hoverCursor;
  16325. }
  16326. }
  16327. else {
  16328. canvas.style.cursor = "";
  16329. }
  16330. }
  16331. else {
  16332. _this.setPointerOverMesh(null);
  16333. // Sprites
  16334. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16335. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16336. _this.setPointerOverSprite(pickResult.pickedSprite);
  16337. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16338. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16339. }
  16340. else {
  16341. canvas.style.cursor = _this.hoverCursor;
  16342. }
  16343. }
  16344. else {
  16345. _this.setPointerOverSprite(null);
  16346. // Restore pointer
  16347. canvas.style.cursor = "";
  16348. }
  16349. }
  16350. if (_this.onPointerMove) {
  16351. _this.onPointerMove(evt, pickResult);
  16352. }
  16353. if (_this.onPointerObservable.hasObservers()) {
  16354. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16355. var pi = new PointerInfo(type, evt, pickResult);
  16356. _this.onPointerObservable.notifyObservers(pi, type);
  16357. }
  16358. };
  16359. this._onPointerDown = function (evt) {
  16360. _this._isButtonPressed = true;
  16361. _this._pickedDownMesh = null;
  16362. _this._meshPickProceed = false;
  16363. _this._updatePointerPosition(evt);
  16364. // PreObservable support
  16365. if (_this.onPrePointerObservable.hasObservers()) {
  16366. var type = PointerEventTypes.POINTERDOWN;
  16367. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16368. _this.onPrePointerObservable.notifyObservers(pi, type);
  16369. if (pi.skipOnPointerObservable) {
  16370. return;
  16371. }
  16372. }
  16373. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16374. return;
  16375. }
  16376. _this._startingPointerPosition.x = _this._pointerX;
  16377. _this._startingPointerPosition.y = _this._pointerY;
  16378. _this._startingPointerTime = new Date().getTime();
  16379. if (!_this.pointerDownPredicate) {
  16380. _this.pointerDownPredicate = function (mesh) {
  16381. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16382. };
  16383. }
  16384. // Meshes
  16385. _this._pickedDownMesh = null;
  16386. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16387. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16388. _this._pickedDownMesh = pickResult.pickedMesh;
  16389. var actionManager = pickResult.pickedMesh.actionManager;
  16390. if (actionManager) {
  16391. if (actionManager.hasPickTriggers) {
  16392. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16393. switch (evt.button) {
  16394. case 0:
  16395. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16396. break;
  16397. case 1:
  16398. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16399. break;
  16400. case 2:
  16401. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16402. break;
  16403. }
  16404. }
  16405. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16406. window.setTimeout((function () {
  16407. var _this = this;
  16408. 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);
  16409. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16410. if (this._isButtonPressed &&
  16411. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16412. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16413. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16414. this._startingPointerTime = 0;
  16415. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16416. }
  16417. }
  16418. }).bind(_this), Scene.LongPressDelay);
  16419. }
  16420. }
  16421. }
  16422. if (_this.onPointerDown) {
  16423. _this.onPointerDown(evt, pickResult);
  16424. }
  16425. if (_this.onPointerObservable.hasObservers()) {
  16426. var type = PointerEventTypes.POINTERDOWN;
  16427. var pi = new PointerInfo(type, evt, pickResult);
  16428. _this.onPointerObservable.notifyObservers(pi, type);
  16429. }
  16430. // Sprites
  16431. _this._pickedDownSprite = null;
  16432. if (_this.spriteManagers.length > 0) {
  16433. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16434. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16435. if (pickResult.pickedSprite.actionManager) {
  16436. _this._pickedDownSprite = pickResult.pickedSprite;
  16437. switch (evt.button) {
  16438. case 0:
  16439. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16440. break;
  16441. case 1:
  16442. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16443. break;
  16444. case 2:
  16445. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16446. break;
  16447. }
  16448. if (pickResult.pickedSprite.actionManager) {
  16449. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16450. }
  16451. }
  16452. }
  16453. }
  16454. };
  16455. this._onPointerUp = function (evt) {
  16456. _this._isButtonPressed = false;
  16457. _this._pickedUpMesh = null;
  16458. _this._meshPickProceed = false;
  16459. _this._updatePointerPosition(evt);
  16460. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16461. // PreObservable support
  16462. if (this.onPrePointerObservable.hasObservers()) {
  16463. if (!clickInfo.ignore) {
  16464. if (!clickInfo.hasSwiped) {
  16465. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16466. var type = PointerEventTypes.POINTERTAP;
  16467. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16468. this.onPrePointerObservable.notifyObservers(pi, type);
  16469. if (pi.skipOnPointerObservable) {
  16470. return;
  16471. }
  16472. }
  16473. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16474. var type = PointerEventTypes.POINTERDOUBLETAP;
  16475. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16476. this.onPrePointerObservable.notifyObservers(pi, type);
  16477. if (pi.skipOnPointerObservable) {
  16478. return;
  16479. }
  16480. }
  16481. }
  16482. }
  16483. else {
  16484. var type = PointerEventTypes.POINTERUP;
  16485. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16486. this.onPrePointerObservable.notifyObservers(pi, type);
  16487. if (pi.skipOnPointerObservable) {
  16488. return;
  16489. }
  16490. }
  16491. }
  16492. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16493. return;
  16494. }
  16495. if (!this.pointerUpPredicate) {
  16496. this.pointerUpPredicate = function (mesh) {
  16497. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16498. };
  16499. }
  16500. // Meshes
  16501. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16502. this._initActionManager(null, clickInfo);
  16503. }
  16504. if (!pickResult) {
  16505. pickResult = this._currentPickResult;
  16506. }
  16507. if (pickResult && pickResult && pickResult.pickedMesh) {
  16508. this._pickedUpMesh = pickResult.pickedMesh;
  16509. if (this._pickedDownMesh === this._pickedUpMesh) {
  16510. if (this.onPointerPick) {
  16511. this.onPointerPick(evt, pickResult);
  16512. }
  16513. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16514. var type = PointerEventTypes.POINTERPICK;
  16515. var pi = new PointerInfo(type, evt, pickResult);
  16516. this.onPointerObservable.notifyObservers(pi, type);
  16517. }
  16518. }
  16519. if (pickResult.pickedMesh.actionManager) {
  16520. if (clickInfo.ignore) {
  16521. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16522. }
  16523. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16524. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16525. }
  16526. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16527. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16528. }
  16529. }
  16530. }
  16531. if (this._pickedDownMesh &&
  16532. this._pickedDownMesh.actionManager &&
  16533. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16534. this._pickedDownMesh !== this._pickedUpMesh) {
  16535. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16536. }
  16537. if (this.onPointerUp) {
  16538. this.onPointerUp(evt, pickResult);
  16539. }
  16540. if (this.onPointerObservable.hasObservers()) {
  16541. if (!clickInfo.ignore) {
  16542. if (!clickInfo.hasSwiped) {
  16543. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16544. var type = PointerEventTypes.POINTERTAP;
  16545. var pi = new PointerInfo(type, evt, pickResult);
  16546. this.onPointerObservable.notifyObservers(pi, type);
  16547. }
  16548. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16549. var type = PointerEventTypes.POINTERDOUBLETAP;
  16550. var pi = new PointerInfo(type, evt, pickResult);
  16551. this.onPointerObservable.notifyObservers(pi, type);
  16552. }
  16553. }
  16554. }
  16555. else {
  16556. var type = PointerEventTypes.POINTERUP;
  16557. var pi = new PointerInfo(type, evt, pickResult);
  16558. this.onPointerObservable.notifyObservers(pi, type);
  16559. }
  16560. }
  16561. // Sprites
  16562. if (this.spriteManagers.length > 0) {
  16563. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16564. if (pickResult.hit && pickResult.pickedSprite) {
  16565. if (pickResult.pickedSprite.actionManager) {
  16566. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16567. if (pickResult.pickedSprite.actionManager) {
  16568. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16569. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16570. }
  16571. }
  16572. }
  16573. }
  16574. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16575. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16576. }
  16577. }
  16578. this._previousPickResult = this._currentPickResult;
  16579. }).bind(_this));
  16580. };
  16581. this._onKeyDown = function (evt) {
  16582. if (_this.actionManager) {
  16583. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16584. }
  16585. };
  16586. this._onKeyUp = function (evt) {
  16587. if (_this.actionManager) {
  16588. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16589. }
  16590. };
  16591. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16592. var canvas = this._engine.getRenderingCanvas();
  16593. if (attachMove) {
  16594. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16595. // Wheel
  16596. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16597. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16598. }
  16599. if (attachDown) {
  16600. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16601. }
  16602. if (attachUp) {
  16603. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16604. }
  16605. canvas.tabIndex = 1;
  16606. canvas.addEventListener("keydown", this._onKeyDown, false);
  16607. canvas.addEventListener("keyup", this._onKeyUp, false);
  16608. };
  16609. Scene.prototype.detachControl = function () {
  16610. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16611. var canvas = this._engine.getRenderingCanvas();
  16612. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16613. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16614. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16615. // Wheel
  16616. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16617. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16618. canvas.removeEventListener("keydown", this._onKeyDown);
  16619. canvas.removeEventListener("keyup", this._onKeyUp);
  16620. };
  16621. // Ready
  16622. Scene.prototype.isReady = function () {
  16623. if (this._pendingData.length > 0) {
  16624. return false;
  16625. }
  16626. var index;
  16627. // Geometries
  16628. for (index = 0; index < this._geometries.length; index++) {
  16629. var geometry = this._geometries[index];
  16630. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16631. return false;
  16632. }
  16633. }
  16634. // Meshes
  16635. for (index = 0; index < this.meshes.length; index++) {
  16636. var mesh = this.meshes[index];
  16637. if (!mesh.isEnabled()) {
  16638. continue;
  16639. }
  16640. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16641. continue;
  16642. }
  16643. if (!mesh.isReady()) {
  16644. return false;
  16645. }
  16646. var mat = mesh.material;
  16647. if (mat) {
  16648. if (!mat.isReady(mesh)) {
  16649. return false;
  16650. }
  16651. }
  16652. }
  16653. return true;
  16654. };
  16655. Scene.prototype.resetCachedMaterial = function () {
  16656. this._cachedMaterial = null;
  16657. this._cachedEffect = null;
  16658. this._cachedVisibility = null;
  16659. };
  16660. Scene.prototype.registerBeforeRender = function (func) {
  16661. this.onBeforeRenderObservable.add(func);
  16662. };
  16663. Scene.prototype.unregisterBeforeRender = function (func) {
  16664. this.onBeforeRenderObservable.removeCallback(func);
  16665. };
  16666. Scene.prototype.registerAfterRender = function (func) {
  16667. this.onAfterRenderObservable.add(func);
  16668. };
  16669. Scene.prototype.unregisterAfterRender = function (func) {
  16670. this.onAfterRenderObservable.removeCallback(func);
  16671. };
  16672. Scene.prototype._addPendingData = function (data) {
  16673. this._pendingData.push(data);
  16674. };
  16675. Scene.prototype._removePendingData = function (data) {
  16676. var index = this._pendingData.indexOf(data);
  16677. if (index !== -1) {
  16678. this._pendingData.splice(index, 1);
  16679. }
  16680. };
  16681. Scene.prototype.getWaitingItemsCount = function () {
  16682. return this._pendingData.length;
  16683. };
  16684. /**
  16685. * Registers a function to be executed when the scene is ready.
  16686. * @param {Function} func - the function to be executed.
  16687. */
  16688. Scene.prototype.executeWhenReady = function (func) {
  16689. var _this = this;
  16690. this.onReadyObservable.add(func);
  16691. if (this._executeWhenReadyTimeoutId !== -1) {
  16692. return;
  16693. }
  16694. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16695. _this._checkIsReady();
  16696. }, 150);
  16697. };
  16698. Scene.prototype._checkIsReady = function () {
  16699. var _this = this;
  16700. if (this.isReady()) {
  16701. this.onReadyObservable.notifyObservers(this);
  16702. this.onReadyObservable.clear();
  16703. this._executeWhenReadyTimeoutId = -1;
  16704. return;
  16705. }
  16706. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16707. _this._checkIsReady();
  16708. }, 150);
  16709. };
  16710. // Animations
  16711. /**
  16712. * Will start the animation sequence of a given target
  16713. * @param target - the target
  16714. * @param {number} from - from which frame should animation start
  16715. * @param {number} to - till which frame should animation run.
  16716. * @param {boolean} [loop] - should the animation loop
  16717. * @param {number} [speedRatio] - the speed in which to run the animation
  16718. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16719. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16720. * @return {BABYLON.Animatable} the animatable object created for this animation
  16721. * @see BABYLON.Animatable
  16722. * @see http://doc.babylonjs.com/page.php?p=22081
  16723. */
  16724. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16725. if (speedRatio === void 0) { speedRatio = 1.0; }
  16726. if (from > to && speedRatio > 0) {
  16727. speedRatio *= -1;
  16728. }
  16729. this.stopAnimation(target);
  16730. if (!animatable) {
  16731. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16732. }
  16733. // Local animations
  16734. if (target.animations) {
  16735. animatable.appendAnimations(target, target.animations);
  16736. }
  16737. // Children animations
  16738. if (target.getAnimatables) {
  16739. var animatables = target.getAnimatables();
  16740. for (var index = 0; index < animatables.length; index++) {
  16741. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16742. }
  16743. }
  16744. animatable.reset();
  16745. return animatable;
  16746. };
  16747. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16748. if (speedRatio === undefined) {
  16749. speedRatio = 1.0;
  16750. }
  16751. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16752. return animatable;
  16753. };
  16754. Scene.prototype.getAnimatableByTarget = function (target) {
  16755. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16756. if (this._activeAnimatables[index].target === target) {
  16757. return this._activeAnimatables[index];
  16758. }
  16759. }
  16760. return null;
  16761. };
  16762. Object.defineProperty(Scene.prototype, "Animatables", {
  16763. get: function () {
  16764. return this._activeAnimatables;
  16765. },
  16766. enumerable: true,
  16767. configurable: true
  16768. });
  16769. /**
  16770. * Will stop the animation of the given target
  16771. * @param target - the target
  16772. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16773. * @see beginAnimation
  16774. */
  16775. Scene.prototype.stopAnimation = function (target, animationName) {
  16776. var animatable = this.getAnimatableByTarget(target);
  16777. if (animatable) {
  16778. animatable.stop(animationName);
  16779. }
  16780. };
  16781. Scene.prototype._animate = function () {
  16782. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16783. return;
  16784. }
  16785. // Getting time
  16786. var now = BABYLON.Tools.Now;
  16787. if (!this._animationTimeLast) {
  16788. if (this._pendingData.length > 0) {
  16789. return;
  16790. }
  16791. this._animationTimeLast = now;
  16792. }
  16793. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16794. this._animationTime += deltaTime;
  16795. this._animationTimeLast = now;
  16796. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16797. this._activeAnimatables[index]._animate(this._animationTime);
  16798. }
  16799. };
  16800. // Matrix
  16801. Scene.prototype.getViewMatrix = function () {
  16802. return this._viewMatrix;
  16803. };
  16804. Scene.prototype.getProjectionMatrix = function () {
  16805. return this._projectionMatrix;
  16806. };
  16807. Scene.prototype.getTransformMatrix = function () {
  16808. return this._transformMatrix;
  16809. };
  16810. Scene.prototype.setTransformMatrix = function (view, projection) {
  16811. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16812. return;
  16813. }
  16814. this._viewUpdateFlag = view.updateFlag;
  16815. this._projectionUpdateFlag = projection.updateFlag;
  16816. this._viewMatrix = view;
  16817. this._projectionMatrix = projection;
  16818. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16819. // Update frustum
  16820. if (!this._frustumPlanes) {
  16821. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16822. }
  16823. else {
  16824. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16825. }
  16826. if (this._sceneUbo.useUbo) {
  16827. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16828. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16829. this._sceneUbo.update();
  16830. }
  16831. };
  16832. Scene.prototype.getSceneUniformBuffer = function () {
  16833. return this._sceneUbo;
  16834. };
  16835. // Methods
  16836. Scene.prototype.getUniqueId = function () {
  16837. var result = this._uniqueIdCounter;
  16838. this._uniqueIdCounter++;
  16839. return result;
  16840. };
  16841. Scene.prototype.addMesh = function (newMesh) {
  16842. newMesh.uniqueId = this.getUniqueId();
  16843. var position = this.meshes.push(newMesh);
  16844. //notify the collision coordinator
  16845. if (this.collisionCoordinator) {
  16846. this.collisionCoordinator.onMeshAdded(newMesh);
  16847. }
  16848. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16849. };
  16850. Scene.prototype.removeMesh = function (toRemove) {
  16851. var index = this.meshes.indexOf(toRemove);
  16852. if (index !== -1) {
  16853. // Remove from the scene if mesh found
  16854. this.meshes.splice(index, 1);
  16855. }
  16856. //notify the collision coordinator
  16857. if (this.collisionCoordinator) {
  16858. this.collisionCoordinator.onMeshRemoved(toRemove);
  16859. }
  16860. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16861. return index;
  16862. };
  16863. Scene.prototype.removeSkeleton = function (toRemove) {
  16864. var index = this.skeletons.indexOf(toRemove);
  16865. if (index !== -1) {
  16866. // Remove from the scene if found
  16867. this.skeletons.splice(index, 1);
  16868. }
  16869. return index;
  16870. };
  16871. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16872. var index = this.morphTargetManagers.indexOf(toRemove);
  16873. if (index !== -1) {
  16874. // Remove from the scene if found
  16875. this.morphTargetManagers.splice(index, 1);
  16876. }
  16877. return index;
  16878. };
  16879. Scene.prototype.removeLight = function (toRemove) {
  16880. var index = this.lights.indexOf(toRemove);
  16881. if (index !== -1) {
  16882. // Remove from the scene if mesh found
  16883. this.lights.splice(index, 1);
  16884. this.sortLightsByPriority();
  16885. }
  16886. this.onLightRemovedObservable.notifyObservers(toRemove);
  16887. return index;
  16888. };
  16889. Scene.prototype.removeCamera = function (toRemove) {
  16890. var index = this.cameras.indexOf(toRemove);
  16891. if (index !== -1) {
  16892. // Remove from the scene if mesh found
  16893. this.cameras.splice(index, 1);
  16894. }
  16895. // Remove from activeCameras
  16896. var index2 = this.activeCameras.indexOf(toRemove);
  16897. if (index2 !== -1) {
  16898. // Remove from the scene if mesh found
  16899. this.activeCameras.splice(index2, 1);
  16900. }
  16901. // Reset the activeCamera
  16902. if (this.activeCamera === toRemove) {
  16903. if (this.cameras.length > 0) {
  16904. this.activeCamera = this.cameras[0];
  16905. }
  16906. else {
  16907. this.activeCamera = null;
  16908. }
  16909. }
  16910. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16911. return index;
  16912. };
  16913. Scene.prototype.addLight = function (newLight) {
  16914. newLight.uniqueId = this.getUniqueId();
  16915. this.lights.push(newLight);
  16916. this.sortLightsByPriority();
  16917. this.onNewLightAddedObservable.notifyObservers(newLight);
  16918. };
  16919. Scene.prototype.sortLightsByPriority = function () {
  16920. if (this.requireLightSorting) {
  16921. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16922. }
  16923. };
  16924. Scene.prototype.addCamera = function (newCamera) {
  16925. newCamera.uniqueId = this.getUniqueId();
  16926. var position = this.cameras.push(newCamera);
  16927. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16928. };
  16929. /**
  16930. * Switch active camera
  16931. * @param {Camera} newCamera - new active camera
  16932. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16933. */
  16934. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16935. if (attachControl === void 0) { attachControl = true; }
  16936. var canvas = this._engine.getRenderingCanvas();
  16937. this.activeCamera.detachControl(canvas);
  16938. this.activeCamera = newCamera;
  16939. if (attachControl) {
  16940. newCamera.attachControl(canvas);
  16941. }
  16942. };
  16943. /**
  16944. * sets the active camera of the scene using its ID
  16945. * @param {string} id - the camera's ID
  16946. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16947. * @see activeCamera
  16948. */
  16949. Scene.prototype.setActiveCameraByID = function (id) {
  16950. var camera = this.getCameraByID(id);
  16951. if (camera) {
  16952. this.activeCamera = camera;
  16953. return camera;
  16954. }
  16955. return null;
  16956. };
  16957. /**
  16958. * sets the active camera of the scene using its name
  16959. * @param {string} name - the camera's name
  16960. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16961. * @see activeCamera
  16962. */
  16963. Scene.prototype.setActiveCameraByName = function (name) {
  16964. var camera = this.getCameraByName(name);
  16965. if (camera) {
  16966. this.activeCamera = camera;
  16967. return camera;
  16968. }
  16969. return null;
  16970. };
  16971. /**
  16972. * get a material using its id
  16973. * @param {string} the material's ID
  16974. * @return {BABYLON.Material|null} the material or null if none found.
  16975. */
  16976. Scene.prototype.getMaterialByID = function (id) {
  16977. for (var index = 0; index < this.materials.length; index++) {
  16978. if (this.materials[index].id === id) {
  16979. return this.materials[index];
  16980. }
  16981. }
  16982. return null;
  16983. };
  16984. /**
  16985. * get a material using its name
  16986. * @param {string} the material's name
  16987. * @return {BABYLON.Material|null} the material or null if none found.
  16988. */
  16989. Scene.prototype.getMaterialByName = function (name) {
  16990. for (var index = 0; index < this.materials.length; index++) {
  16991. if (this.materials[index].name === name) {
  16992. return this.materials[index];
  16993. }
  16994. }
  16995. return null;
  16996. };
  16997. Scene.prototype.getLensFlareSystemByName = function (name) {
  16998. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16999. if (this.lensFlareSystems[index].name === name) {
  17000. return this.lensFlareSystems[index];
  17001. }
  17002. }
  17003. return null;
  17004. };
  17005. Scene.prototype.getLensFlareSystemByID = function (id) {
  17006. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17007. if (this.lensFlareSystems[index].id === id) {
  17008. return this.lensFlareSystems[index];
  17009. }
  17010. }
  17011. return null;
  17012. };
  17013. Scene.prototype.getCameraByID = function (id) {
  17014. for (var index = 0; index < this.cameras.length; index++) {
  17015. if (this.cameras[index].id === id) {
  17016. return this.cameras[index];
  17017. }
  17018. }
  17019. return null;
  17020. };
  17021. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17022. for (var index = 0; index < this.cameras.length; index++) {
  17023. if (this.cameras[index].uniqueId === uniqueId) {
  17024. return this.cameras[index];
  17025. }
  17026. }
  17027. return null;
  17028. };
  17029. /**
  17030. * get a camera using its name
  17031. * @param {string} the camera's name
  17032. * @return {BABYLON.Camera|null} the camera or null if none found.
  17033. */
  17034. Scene.prototype.getCameraByName = function (name) {
  17035. for (var index = 0; index < this.cameras.length; index++) {
  17036. if (this.cameras[index].name === name) {
  17037. return this.cameras[index];
  17038. }
  17039. }
  17040. return null;
  17041. };
  17042. /**
  17043. * get a bone using its id
  17044. * @param {string} the bone's id
  17045. * @return {BABYLON.Bone|null} the bone or null if not found
  17046. */
  17047. Scene.prototype.getBoneByID = function (id) {
  17048. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17049. var skeleton = this.skeletons[skeletonIndex];
  17050. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17051. if (skeleton.bones[boneIndex].id === id) {
  17052. return skeleton.bones[boneIndex];
  17053. }
  17054. }
  17055. }
  17056. return null;
  17057. };
  17058. /**
  17059. * get a bone using its id
  17060. * @param {string} the bone's name
  17061. * @return {BABYLON.Bone|null} the bone or null if not found
  17062. */
  17063. Scene.prototype.getBoneByName = function (name) {
  17064. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17065. var skeleton = this.skeletons[skeletonIndex];
  17066. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17067. if (skeleton.bones[boneIndex].name === name) {
  17068. return skeleton.bones[boneIndex];
  17069. }
  17070. }
  17071. }
  17072. return null;
  17073. };
  17074. /**
  17075. * get a light node using its name
  17076. * @param {string} the light's name
  17077. * @return {BABYLON.Light|null} the light or null if none found.
  17078. */
  17079. Scene.prototype.getLightByName = function (name) {
  17080. for (var index = 0; index < this.lights.length; index++) {
  17081. if (this.lights[index].name === name) {
  17082. return this.lights[index];
  17083. }
  17084. }
  17085. return null;
  17086. };
  17087. /**
  17088. * get a light node using its ID
  17089. * @param {string} the light's id
  17090. * @return {BABYLON.Light|null} the light or null if none found.
  17091. */
  17092. Scene.prototype.getLightByID = function (id) {
  17093. for (var index = 0; index < this.lights.length; index++) {
  17094. if (this.lights[index].id === id) {
  17095. return this.lights[index];
  17096. }
  17097. }
  17098. return null;
  17099. };
  17100. /**
  17101. * get a light node using its scene-generated unique ID
  17102. * @param {number} the light's unique id
  17103. * @return {BABYLON.Light|null} the light or null if none found.
  17104. */
  17105. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17106. for (var index = 0; index < this.lights.length; index++) {
  17107. if (this.lights[index].uniqueId === uniqueId) {
  17108. return this.lights[index];
  17109. }
  17110. }
  17111. return null;
  17112. };
  17113. /**
  17114. * get a particle system by id
  17115. * @param id {number} the particle system id
  17116. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17117. */
  17118. Scene.prototype.getParticleSystemByID = function (id) {
  17119. for (var index = 0; index < this.particleSystems.length; index++) {
  17120. if (this.particleSystems[index].id === id) {
  17121. return this.particleSystems[index];
  17122. }
  17123. }
  17124. return null;
  17125. };
  17126. /**
  17127. * get a geometry using its ID
  17128. * @param {string} the geometry's id
  17129. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17130. */
  17131. Scene.prototype.getGeometryByID = function (id) {
  17132. for (var index = 0; index < this._geometries.length; index++) {
  17133. if (this._geometries[index].id === id) {
  17134. return this._geometries[index];
  17135. }
  17136. }
  17137. return null;
  17138. };
  17139. /**
  17140. * add a new geometry to this scene.
  17141. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17142. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17143. * @return {boolean} was the geometry added or not
  17144. */
  17145. Scene.prototype.pushGeometry = function (geometry, force) {
  17146. if (!force && this.getGeometryByID(geometry.id)) {
  17147. return false;
  17148. }
  17149. this._geometries.push(geometry);
  17150. //notify the collision coordinator
  17151. if (this.collisionCoordinator) {
  17152. this.collisionCoordinator.onGeometryAdded(geometry);
  17153. }
  17154. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17155. return true;
  17156. };
  17157. /**
  17158. * Removes an existing geometry
  17159. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17160. * @return {boolean} was the geometry removed or not
  17161. */
  17162. Scene.prototype.removeGeometry = function (geometry) {
  17163. var index = this._geometries.indexOf(geometry);
  17164. if (index > -1) {
  17165. this._geometries.splice(index, 1);
  17166. //notify the collision coordinator
  17167. if (this.collisionCoordinator) {
  17168. this.collisionCoordinator.onGeometryDeleted(geometry);
  17169. }
  17170. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17171. return true;
  17172. }
  17173. return false;
  17174. };
  17175. Scene.prototype.getGeometries = function () {
  17176. return this._geometries;
  17177. };
  17178. /**
  17179. * Get the first added mesh found of a given ID
  17180. * @param {string} id - the id to search for
  17181. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17182. */
  17183. Scene.prototype.getMeshByID = function (id) {
  17184. for (var index = 0; index < this.meshes.length; index++) {
  17185. if (this.meshes[index].id === id) {
  17186. return this.meshes[index];
  17187. }
  17188. }
  17189. return null;
  17190. };
  17191. Scene.prototype.getMeshesByID = function (id) {
  17192. return this.meshes.filter(function (m) {
  17193. return m.id === id;
  17194. });
  17195. };
  17196. /**
  17197. * Get a mesh with its auto-generated unique id
  17198. * @param {number} uniqueId - the unique id to search for
  17199. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17200. */
  17201. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17202. for (var index = 0; index < this.meshes.length; index++) {
  17203. if (this.meshes[index].uniqueId === uniqueId) {
  17204. return this.meshes[index];
  17205. }
  17206. }
  17207. return null;
  17208. };
  17209. /**
  17210. * Get a the last added mesh found of a given ID
  17211. * @param {string} id - the id to search for
  17212. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17213. */
  17214. Scene.prototype.getLastMeshByID = function (id) {
  17215. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17216. if (this.meshes[index].id === id) {
  17217. return this.meshes[index];
  17218. }
  17219. }
  17220. return null;
  17221. };
  17222. /**
  17223. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17224. * @param {string} id - the id to search for
  17225. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17226. */
  17227. Scene.prototype.getLastEntryByID = function (id) {
  17228. var index;
  17229. for (index = this.meshes.length - 1; index >= 0; index--) {
  17230. if (this.meshes[index].id === id) {
  17231. return this.meshes[index];
  17232. }
  17233. }
  17234. for (index = this.cameras.length - 1; index >= 0; index--) {
  17235. if (this.cameras[index].id === id) {
  17236. return this.cameras[index];
  17237. }
  17238. }
  17239. for (index = this.lights.length - 1; index >= 0; index--) {
  17240. if (this.lights[index].id === id) {
  17241. return this.lights[index];
  17242. }
  17243. }
  17244. return null;
  17245. };
  17246. Scene.prototype.getNodeByID = function (id) {
  17247. var mesh = this.getMeshByID(id);
  17248. if (mesh) {
  17249. return mesh;
  17250. }
  17251. var light = this.getLightByID(id);
  17252. if (light) {
  17253. return light;
  17254. }
  17255. var camera = this.getCameraByID(id);
  17256. if (camera) {
  17257. return camera;
  17258. }
  17259. var bone = this.getBoneByID(id);
  17260. return bone;
  17261. };
  17262. Scene.prototype.getNodeByName = function (name) {
  17263. var mesh = this.getMeshByName(name);
  17264. if (mesh) {
  17265. return mesh;
  17266. }
  17267. var light = this.getLightByName(name);
  17268. if (light) {
  17269. return light;
  17270. }
  17271. var camera = this.getCameraByName(name);
  17272. if (camera) {
  17273. return camera;
  17274. }
  17275. var bone = this.getBoneByName(name);
  17276. return bone;
  17277. };
  17278. Scene.prototype.getMeshByName = function (name) {
  17279. for (var index = 0; index < this.meshes.length; index++) {
  17280. if (this.meshes[index].name === name) {
  17281. return this.meshes[index];
  17282. }
  17283. }
  17284. return null;
  17285. };
  17286. Scene.prototype.getSoundByName = function (name) {
  17287. var index;
  17288. if (BABYLON.AudioEngine) {
  17289. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17290. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17291. return this.mainSoundTrack.soundCollection[index];
  17292. }
  17293. }
  17294. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17295. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17296. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17297. return this.soundTracks[sdIndex].soundCollection[index];
  17298. }
  17299. }
  17300. }
  17301. }
  17302. return null;
  17303. };
  17304. Scene.prototype.getLastSkeletonByID = function (id) {
  17305. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17306. if (this.skeletons[index].id === id) {
  17307. return this.skeletons[index];
  17308. }
  17309. }
  17310. return null;
  17311. };
  17312. Scene.prototype.getSkeletonById = function (id) {
  17313. for (var index = 0; index < this.skeletons.length; index++) {
  17314. if (this.skeletons[index].id === id) {
  17315. return this.skeletons[index];
  17316. }
  17317. }
  17318. return null;
  17319. };
  17320. Scene.prototype.getSkeletonByName = function (name) {
  17321. for (var index = 0; index < this.skeletons.length; index++) {
  17322. if (this.skeletons[index].name === name) {
  17323. return this.skeletons[index];
  17324. }
  17325. }
  17326. return null;
  17327. };
  17328. Scene.prototype.getMorphTargetManagerById = function (id) {
  17329. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17330. if (this.morphTargetManagers[index].uniqueId === id) {
  17331. return this.morphTargetManagers[index];
  17332. }
  17333. }
  17334. return null;
  17335. };
  17336. Scene.prototype.isActiveMesh = function (mesh) {
  17337. return (this._activeMeshes.indexOf(mesh) !== -1);
  17338. };
  17339. /**
  17340. * Return a the first highlight layer of the scene with a given name.
  17341. * @param name The name of the highlight layer to look for.
  17342. * @return The highlight layer if found otherwise null.
  17343. */
  17344. Scene.prototype.getHighlightLayerByName = function (name) {
  17345. for (var index = 0; index < this.highlightLayers.length; index++) {
  17346. if (this.highlightLayers[index].name === name) {
  17347. return this.highlightLayers[index];
  17348. }
  17349. }
  17350. return null;
  17351. };
  17352. Object.defineProperty(Scene.prototype, "uid", {
  17353. /**
  17354. * Return a unique id as a string which can serve as an identifier for the scene
  17355. */
  17356. get: function () {
  17357. if (!this._uid) {
  17358. this._uid = BABYLON.Tools.RandomId();
  17359. }
  17360. return this._uid;
  17361. },
  17362. enumerable: true,
  17363. configurable: true
  17364. });
  17365. /**
  17366. * Add an externaly attached data from its key.
  17367. * This method call will fail and return false, if such key already exists.
  17368. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17369. * @param key the unique key that identifies the data
  17370. * @param data the data object to associate to the key for this Engine instance
  17371. * @return true if no such key were already present and the data was added successfully, false otherwise
  17372. */
  17373. Scene.prototype.addExternalData = function (key, data) {
  17374. if (!this._externalData) {
  17375. this._externalData = new BABYLON.StringDictionary();
  17376. }
  17377. return this._externalData.add(key, data);
  17378. };
  17379. /**
  17380. * Get an externaly attached data from its key
  17381. * @param key the unique key that identifies the data
  17382. * @return the associated data, if present (can be null), or undefined if not present
  17383. */
  17384. Scene.prototype.getExternalData = function (key) {
  17385. if (!this._externalData) {
  17386. return null;
  17387. }
  17388. return this._externalData.get(key);
  17389. };
  17390. /**
  17391. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17392. * @param key the unique key that identifies the data
  17393. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17394. * @return the associated data, can be null if the factory returned null.
  17395. */
  17396. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17397. if (!this._externalData) {
  17398. this._externalData = new BABYLON.StringDictionary();
  17399. }
  17400. return this._externalData.getOrAddWithFactory(key, factory);
  17401. };
  17402. /**
  17403. * Remove an externaly attached data from the Engine instance
  17404. * @param key the unique key that identifies the data
  17405. * @return true if the data was successfully removed, false if it doesn't exist
  17406. */
  17407. Scene.prototype.removeExternalData = function (key) {
  17408. return this._externalData.remove(key);
  17409. };
  17410. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17411. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17412. var material = subMesh.getMaterial();
  17413. if (mesh.showSubMeshesBoundingBox) {
  17414. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17415. }
  17416. if (material) {
  17417. // Render targets
  17418. if (material.getRenderTargetTextures) {
  17419. if (this._processedMaterials.indexOf(material) === -1) {
  17420. this._processedMaterials.push(material);
  17421. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17422. }
  17423. }
  17424. // Dispatch
  17425. this._activeIndices.addCount(subMesh.indexCount, false);
  17426. this._renderingManager.dispatch(subMesh);
  17427. }
  17428. }
  17429. };
  17430. Scene.prototype._isInIntermediateRendering = function () {
  17431. return this._intermediateRendering;
  17432. };
  17433. Scene.prototype._evaluateActiveMeshes = function () {
  17434. this.activeCamera._activeMeshes.reset();
  17435. this._activeMeshes.reset();
  17436. this._renderingManager.reset();
  17437. this._processedMaterials.reset();
  17438. this._activeParticleSystems.reset();
  17439. this._activeSkeletons.reset();
  17440. this._softwareSkinnedMeshes.reset();
  17441. if (this._boundingBoxRenderer) {
  17442. this._boundingBoxRenderer.reset();
  17443. }
  17444. // Meshes
  17445. var meshes;
  17446. var len;
  17447. if (this._selectionOctree) {
  17448. var selection = this._selectionOctree.select(this._frustumPlanes);
  17449. meshes = selection.data;
  17450. len = selection.length;
  17451. }
  17452. else {
  17453. len = this.meshes.length;
  17454. meshes = this.meshes;
  17455. }
  17456. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17457. var mesh = meshes[meshIndex];
  17458. if (mesh.isBlocked) {
  17459. continue;
  17460. }
  17461. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17462. if (!mesh.isReady() || !mesh.isEnabled()) {
  17463. continue;
  17464. }
  17465. mesh.computeWorldMatrix();
  17466. // Intersections
  17467. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17468. this._meshesForIntersections.pushNoDuplicate(mesh);
  17469. }
  17470. // Switch to current LOD
  17471. var meshLOD = mesh.getLOD(this.activeCamera);
  17472. if (!meshLOD) {
  17473. continue;
  17474. }
  17475. mesh._preActivate();
  17476. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17477. this._activeMeshes.push(mesh);
  17478. this.activeCamera._activeMeshes.push(mesh);
  17479. mesh._activate(this._renderId);
  17480. this._activeMesh(mesh, meshLOD);
  17481. }
  17482. }
  17483. // Particle systems
  17484. this._particlesDuration.beginMonitoring();
  17485. var beforeParticlesDate = BABYLON.Tools.Now;
  17486. if (this.particlesEnabled) {
  17487. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17488. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17489. var particleSystem = this.particleSystems[particleIndex];
  17490. if (!particleSystem.isStarted()) {
  17491. continue;
  17492. }
  17493. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17494. this._activeParticleSystems.push(particleSystem);
  17495. particleSystem.animate();
  17496. this._renderingManager.dispatchParticles(particleSystem);
  17497. }
  17498. }
  17499. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17500. }
  17501. this._particlesDuration.endMonitoring(false);
  17502. };
  17503. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17504. if (mesh.skeleton && this.skeletonsEnabled) {
  17505. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17506. mesh.skeleton.prepare();
  17507. }
  17508. if (!mesh.computeBonesUsingShaders) {
  17509. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17510. }
  17511. }
  17512. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17513. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17514. }
  17515. if (mesh && mesh.subMeshes) {
  17516. // Submeshes Octrees
  17517. var len;
  17518. var subMeshes;
  17519. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17520. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17521. len = intersections.length;
  17522. subMeshes = intersections.data;
  17523. }
  17524. else {
  17525. subMeshes = mesh.subMeshes;
  17526. len = subMeshes.length;
  17527. }
  17528. for (var subIndex = 0; subIndex < len; subIndex++) {
  17529. var subMesh = subMeshes[subIndex];
  17530. this._evaluateSubMesh(subMesh, mesh);
  17531. }
  17532. }
  17533. };
  17534. Scene.prototype.updateTransformMatrix = function (force) {
  17535. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17536. };
  17537. Scene.prototype._renderForCamera = function (camera) {
  17538. var engine = this._engine;
  17539. var startTime = BABYLON.Tools.Now;
  17540. this.activeCamera = camera;
  17541. if (!this.activeCamera)
  17542. throw new Error("Active camera not set");
  17543. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17544. // Viewport
  17545. engine.setViewport(this.activeCamera.viewport);
  17546. // Camera
  17547. this.resetCachedMaterial();
  17548. this._renderId++;
  17549. this.updateTransformMatrix();
  17550. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17551. // Meshes
  17552. this._evaluateActiveMeshesDuration.beginMonitoring();
  17553. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17554. this._evaluateActiveMeshes();
  17555. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17556. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17557. // Software skinning
  17558. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17559. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17560. mesh.applySkeleton(mesh.skeleton);
  17561. }
  17562. // Render targets
  17563. this._renderTargetsDuration.beginMonitoring();
  17564. var needsRestoreFrameBuffer = false;
  17565. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17566. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  17567. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  17568. }
  17569. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17570. this._intermediateRendering = true;
  17571. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17572. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17573. var renderTarget = this._renderTargets.data[renderIndex];
  17574. if (renderTarget._shouldRender()) {
  17575. this._renderId++;
  17576. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17577. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17578. }
  17579. }
  17580. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17581. this._intermediateRendering = false;
  17582. this._renderId++;
  17583. needsRestoreFrameBuffer = true; // Restore back buffer
  17584. }
  17585. // Render HighlightLayer Texture
  17586. var stencilState = this._engine.getStencilBuffer();
  17587. var renderhighlights = false;
  17588. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17589. this._intermediateRendering = true;
  17590. for (var i = 0; i < this.highlightLayers.length; i++) {
  17591. var highlightLayer = this.highlightLayers[i];
  17592. if (highlightLayer.shouldRender() &&
  17593. (!highlightLayer.camera ||
  17594. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17595. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17596. renderhighlights = true;
  17597. var renderTarget = highlightLayer._mainTexture;
  17598. if (renderTarget._shouldRender()) {
  17599. this._renderId++;
  17600. renderTarget.render(false, false);
  17601. needsRestoreFrameBuffer = true;
  17602. }
  17603. }
  17604. }
  17605. this._intermediateRendering = false;
  17606. this._renderId++;
  17607. }
  17608. if (needsRestoreFrameBuffer) {
  17609. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17610. }
  17611. this._renderTargetsDuration.endMonitoring(false);
  17612. // Prepare Frame
  17613. this.postProcessManager._prepareFrame();
  17614. this._renderDuration.beginMonitoring();
  17615. // Backgrounds
  17616. var layerIndex;
  17617. var layer;
  17618. if (this.layers.length) {
  17619. engine.setDepthBuffer(false);
  17620. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17621. layer = this.layers[layerIndex];
  17622. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17623. layer.render();
  17624. }
  17625. }
  17626. engine.setDepthBuffer(true);
  17627. }
  17628. // Render
  17629. BABYLON.Tools.StartPerformanceCounter("Main render");
  17630. // Activate HighlightLayer stencil
  17631. if (renderhighlights) {
  17632. this._engine.setStencilBuffer(true);
  17633. }
  17634. this._renderingManager.render(null, null, true, true);
  17635. // Restore HighlightLayer stencil
  17636. if (renderhighlights) {
  17637. this._engine.setStencilBuffer(stencilState);
  17638. }
  17639. BABYLON.Tools.EndPerformanceCounter("Main render");
  17640. // Bounding boxes
  17641. if (this._boundingBoxRenderer) {
  17642. this._boundingBoxRenderer.render();
  17643. }
  17644. // Lens flares
  17645. if (this.lensFlaresEnabled) {
  17646. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17647. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17648. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17649. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17650. lensFlareSystem.render();
  17651. }
  17652. }
  17653. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17654. }
  17655. // Foregrounds
  17656. if (this.layers.length) {
  17657. engine.setDepthBuffer(false);
  17658. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17659. layer = this.layers[layerIndex];
  17660. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17661. layer.render();
  17662. }
  17663. }
  17664. engine.setDepthBuffer(true);
  17665. }
  17666. // Highlight Layer
  17667. if (renderhighlights) {
  17668. engine.setDepthBuffer(false);
  17669. for (var i = 0; i < this.highlightLayers.length; i++) {
  17670. if (this.highlightLayers[i].shouldRender()) {
  17671. this.highlightLayers[i].render();
  17672. }
  17673. }
  17674. engine.setDepthBuffer(true);
  17675. }
  17676. this._renderDuration.endMonitoring(false);
  17677. // Finalize frame
  17678. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17679. // Update camera
  17680. this.activeCamera._updateFromScene();
  17681. // Reset some special arrays
  17682. this._renderTargets.reset();
  17683. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17684. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17685. };
  17686. Scene.prototype._processSubCameras = function (camera) {
  17687. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17688. this._renderForCamera(camera);
  17689. return;
  17690. }
  17691. // rig cameras
  17692. for (var index = 0; index < camera._rigCameras.length; index++) {
  17693. this._renderForCamera(camera._rigCameras[index]);
  17694. }
  17695. this.activeCamera = camera;
  17696. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17697. // Update camera
  17698. this.activeCamera._updateFromScene();
  17699. };
  17700. Scene.prototype._checkIntersections = function () {
  17701. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17702. var sourceMesh = this._meshesForIntersections.data[index];
  17703. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17704. var action = sourceMesh.actionManager.actions[actionIndex];
  17705. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17706. var parameters = action.getTriggerParameter();
  17707. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17708. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17709. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17710. if (areIntersecting && currentIntersectionInProgress === -1) {
  17711. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17712. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17713. sourceMesh._intersectionsInProgress.push(otherMesh);
  17714. }
  17715. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17716. sourceMesh._intersectionsInProgress.push(otherMesh);
  17717. }
  17718. }
  17719. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17720. //They intersected, and now they don't.
  17721. //is this trigger an exit trigger? execute an event.
  17722. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17723. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17724. }
  17725. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17726. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17727. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17728. }
  17729. }
  17730. }
  17731. }
  17732. }
  17733. };
  17734. Scene.prototype.render = function () {
  17735. if (this.isDisposed) {
  17736. return;
  17737. }
  17738. this._lastFrameDuration.beginMonitoring();
  17739. this._particlesDuration.fetchNewFrame();
  17740. this._spritesDuration.fetchNewFrame();
  17741. this._activeParticles.fetchNewFrame();
  17742. this._renderDuration.fetchNewFrame();
  17743. this._renderTargetsDuration.fetchNewFrame();
  17744. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17745. this._totalVertices.fetchNewFrame();
  17746. this._activeIndices.fetchNewFrame();
  17747. this._activeBones.fetchNewFrame();
  17748. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17749. this._meshesForIntersections.reset();
  17750. this.resetCachedMaterial();
  17751. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17752. // Actions
  17753. if (this.actionManager) {
  17754. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17755. }
  17756. //Simplification Queue
  17757. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17758. this.simplificationQueue.executeNext();
  17759. }
  17760. // Animations
  17761. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17762. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17763. this._animate();
  17764. // Physics
  17765. if (this._physicsEngine) {
  17766. BABYLON.Tools.StartPerformanceCounter("Physics");
  17767. this._physicsEngine._step(deltaTime / 1000.0);
  17768. BABYLON.Tools.EndPerformanceCounter("Physics");
  17769. }
  17770. // Before render
  17771. this.onBeforeRenderObservable.notifyObservers(this);
  17772. // Customs render targets
  17773. this._renderTargetsDuration.beginMonitoring();
  17774. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17775. var engine = this.getEngine();
  17776. var currentActiveCamera = this.activeCamera;
  17777. if (this.renderTargetsEnabled) {
  17778. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17779. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17780. var renderTarget = this.customRenderTargets[customIndex];
  17781. if (renderTarget._shouldRender()) {
  17782. this._renderId++;
  17783. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17784. if (!this.activeCamera)
  17785. throw new Error("Active camera not set");
  17786. // Viewport
  17787. engine.setViewport(this.activeCamera.viewport);
  17788. // Camera
  17789. this.updateTransformMatrix();
  17790. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17791. }
  17792. }
  17793. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17794. this._renderId++;
  17795. }
  17796. // Restore back buffer
  17797. if (this.customRenderTargets.length > 0) {
  17798. engine.restoreDefaultFramebuffer();
  17799. }
  17800. this._renderTargetsDuration.endMonitoring();
  17801. this.activeCamera = currentActiveCamera;
  17802. // Procedural textures
  17803. if (this.proceduralTexturesEnabled) {
  17804. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17805. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17806. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17807. if (proceduralTexture._shouldRender()) {
  17808. proceduralTexture.render();
  17809. }
  17810. }
  17811. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17812. }
  17813. // Clear
  17814. if (this.autoClearDepthAndStencil || this.autoClear) {
  17815. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17816. }
  17817. // Shadows
  17818. if (this.shadowsEnabled) {
  17819. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17820. var light = this.lights[lightIndex];
  17821. var shadowGenerator = light.getShadowGenerator();
  17822. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17823. var shadowMap = shadowGenerator.getShadowMap();
  17824. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17825. this._renderTargets.push(shadowMap);
  17826. }
  17827. }
  17828. }
  17829. }
  17830. // Depth renderer
  17831. if (this._depthRenderer) {
  17832. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17833. }
  17834. // Geometry renderer
  17835. if (this._geometryBufferRenderer) {
  17836. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17837. }
  17838. // RenderPipeline
  17839. if (this._postProcessRenderPipelineManager) {
  17840. this._postProcessRenderPipelineManager.update();
  17841. }
  17842. // Multi-cameras?
  17843. if (this.activeCameras.length > 0) {
  17844. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17845. if (cameraIndex > 0) {
  17846. this._engine.clear(null, false, true, true);
  17847. }
  17848. this._processSubCameras(this.activeCameras[cameraIndex]);
  17849. }
  17850. }
  17851. else {
  17852. if (!this.activeCamera) {
  17853. throw new Error("No camera defined");
  17854. }
  17855. this._processSubCameras(this.activeCamera);
  17856. }
  17857. // Intersection checks
  17858. this._checkIntersections();
  17859. // Update the audio listener attached to the camera
  17860. if (BABYLON.AudioEngine) {
  17861. this._updateAudioParameters();
  17862. }
  17863. // After render
  17864. if (this.afterRender) {
  17865. this.afterRender();
  17866. }
  17867. this.onAfterRenderObservable.notifyObservers(this);
  17868. // Cleaning
  17869. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17870. this._toBeDisposed.data[index].dispose();
  17871. this._toBeDisposed[index] = null;
  17872. }
  17873. this._toBeDisposed.reset();
  17874. if (this.dumpNextRenderTargets) {
  17875. this.dumpNextRenderTargets = false;
  17876. }
  17877. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17878. this._lastFrameDuration.endMonitoring();
  17879. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17880. this._totalLightsCounter.addCount(this.lights.length, true);
  17881. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17882. this._totalTexturesCounter.addCount(this.textures.length, true);
  17883. this._activeBones.addCount(0, true);
  17884. this._activeIndices.addCount(0, true);
  17885. this._activeParticles.addCount(0, true);
  17886. };
  17887. Scene.prototype._updateAudioParameters = function () {
  17888. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17889. return;
  17890. }
  17891. var listeningCamera;
  17892. var audioEngine = BABYLON.Engine.audioEngine;
  17893. if (this.activeCameras.length > 0) {
  17894. listeningCamera = this.activeCameras[0];
  17895. }
  17896. else {
  17897. listeningCamera = this.activeCamera;
  17898. }
  17899. if (listeningCamera && audioEngine.canUseWebAudio) {
  17900. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17901. // for VR cameras
  17902. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  17903. listeningCamera = listeningCamera.rigCameras[0];
  17904. }
  17905. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17906. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17907. cameraDirection.normalize();
  17908. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17909. var i;
  17910. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17911. var sound = this.mainSoundTrack.soundCollection[i];
  17912. if (sound.useCustomAttenuation) {
  17913. sound.updateDistanceFromListener();
  17914. }
  17915. }
  17916. for (i = 0; i < this.soundTracks.length; i++) {
  17917. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17918. sound = this.soundTracks[i].soundCollection[j];
  17919. if (sound.useCustomAttenuation) {
  17920. sound.updateDistanceFromListener();
  17921. }
  17922. }
  17923. }
  17924. }
  17925. };
  17926. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17927. // Audio
  17928. get: function () {
  17929. return this._audioEnabled;
  17930. },
  17931. set: function (value) {
  17932. this._audioEnabled = value;
  17933. if (BABYLON.AudioEngine) {
  17934. if (this._audioEnabled) {
  17935. this._enableAudio();
  17936. }
  17937. else {
  17938. this._disableAudio();
  17939. }
  17940. }
  17941. },
  17942. enumerable: true,
  17943. configurable: true
  17944. });
  17945. Scene.prototype._disableAudio = function () {
  17946. var i;
  17947. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17948. this.mainSoundTrack.soundCollection[i].pause();
  17949. }
  17950. for (i = 0; i < this.soundTracks.length; i++) {
  17951. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17952. this.soundTracks[i].soundCollection[j].pause();
  17953. }
  17954. }
  17955. };
  17956. Scene.prototype._enableAudio = function () {
  17957. var i;
  17958. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17959. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17960. this.mainSoundTrack.soundCollection[i].play();
  17961. }
  17962. }
  17963. for (i = 0; i < this.soundTracks.length; i++) {
  17964. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17965. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17966. this.soundTracks[i].soundCollection[j].play();
  17967. }
  17968. }
  17969. }
  17970. };
  17971. Object.defineProperty(Scene.prototype, "headphone", {
  17972. get: function () {
  17973. return this._headphone;
  17974. },
  17975. set: function (value) {
  17976. this._headphone = value;
  17977. if (BABYLON.AudioEngine) {
  17978. if (this._headphone) {
  17979. this._switchAudioModeForHeadphones();
  17980. }
  17981. else {
  17982. this._switchAudioModeForNormalSpeakers();
  17983. }
  17984. }
  17985. },
  17986. enumerable: true,
  17987. configurable: true
  17988. });
  17989. Scene.prototype._switchAudioModeForHeadphones = function () {
  17990. this.mainSoundTrack.switchPanningModelToHRTF();
  17991. for (var i = 0; i < this.soundTracks.length; i++) {
  17992. this.soundTracks[i].switchPanningModelToHRTF();
  17993. }
  17994. };
  17995. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17996. this.mainSoundTrack.switchPanningModelToEqualPower();
  17997. for (var i = 0; i < this.soundTracks.length; i++) {
  17998. this.soundTracks[i].switchPanningModelToEqualPower();
  17999. }
  18000. };
  18001. Scene.prototype.enableDepthRenderer = function () {
  18002. if (this._depthRenderer) {
  18003. return this._depthRenderer;
  18004. }
  18005. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18006. return this._depthRenderer;
  18007. };
  18008. Scene.prototype.disableDepthRenderer = function () {
  18009. if (!this._depthRenderer) {
  18010. return;
  18011. }
  18012. this._depthRenderer.dispose();
  18013. this._depthRenderer = null;
  18014. };
  18015. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18016. if (ratio === void 0) { ratio = 1; }
  18017. if (this._geometryBufferRenderer) {
  18018. return this._geometryBufferRenderer;
  18019. }
  18020. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18021. if (!this._geometryBufferRenderer.isSupported) {
  18022. this._geometryBufferRenderer = null;
  18023. }
  18024. return this._geometryBufferRenderer;
  18025. };
  18026. Scene.prototype.disableGeometryBufferRenderer = function () {
  18027. if (!this._geometryBufferRenderer) {
  18028. return;
  18029. }
  18030. this._geometryBufferRenderer.dispose();
  18031. this._geometryBufferRenderer = null;
  18032. };
  18033. Scene.prototype.freezeMaterials = function () {
  18034. for (var i = 0; i < this.materials.length; i++) {
  18035. this.materials[i].freeze();
  18036. }
  18037. };
  18038. Scene.prototype.unfreezeMaterials = function () {
  18039. for (var i = 0; i < this.materials.length; i++) {
  18040. this.materials[i].unfreeze();
  18041. }
  18042. };
  18043. Scene.prototype.dispose = function () {
  18044. this.beforeRender = null;
  18045. this.afterRender = null;
  18046. this.skeletons = [];
  18047. this.morphTargetManagers = [];
  18048. this.importedMeshesFiles = new Array();
  18049. if (this._depthRenderer) {
  18050. this._depthRenderer.dispose();
  18051. }
  18052. // Smart arrays
  18053. if (this.activeCamera) {
  18054. this.activeCamera._activeMeshes.dispose();
  18055. this.activeCamera = null;
  18056. }
  18057. this._activeMeshes.dispose();
  18058. this._renderingManager.dispose();
  18059. this._processedMaterials.dispose();
  18060. this._activeParticleSystems.dispose();
  18061. this._activeSkeletons.dispose();
  18062. this._softwareSkinnedMeshes.dispose();
  18063. if (this._boundingBoxRenderer) {
  18064. this._boundingBoxRenderer.dispose();
  18065. }
  18066. this._meshesForIntersections.dispose();
  18067. this._toBeDisposed.dispose();
  18068. // Debug layer
  18069. if (this._debugLayer) {
  18070. this._debugLayer.hide();
  18071. }
  18072. // Events
  18073. this.onDisposeObservable.notifyObservers(this);
  18074. this.onDisposeObservable.clear();
  18075. this.onBeforeRenderObservable.clear();
  18076. this.onAfterRenderObservable.clear();
  18077. this.detachControl();
  18078. // Release sounds & sounds tracks
  18079. if (BABYLON.AudioEngine) {
  18080. this.disposeSounds();
  18081. }
  18082. // Detach cameras
  18083. var canvas = this._engine.getRenderingCanvas();
  18084. var index;
  18085. for (index = 0; index < this.cameras.length; index++) {
  18086. this.cameras[index].detachControl(canvas);
  18087. }
  18088. // Release lights
  18089. while (this.lights.length) {
  18090. this.lights[0].dispose();
  18091. }
  18092. // Release meshes
  18093. while (this.meshes.length) {
  18094. this.meshes[0].dispose(true);
  18095. }
  18096. // Release cameras
  18097. while (this.cameras.length) {
  18098. this.cameras[0].dispose();
  18099. }
  18100. // Release materials
  18101. while (this.materials.length) {
  18102. this.materials[0].dispose();
  18103. }
  18104. // Release particles
  18105. while (this.particleSystems.length) {
  18106. this.particleSystems[0].dispose();
  18107. }
  18108. // Release sprites
  18109. while (this.spriteManagers.length) {
  18110. this.spriteManagers[0].dispose();
  18111. }
  18112. // Release layers
  18113. while (this.layers.length) {
  18114. this.layers[0].dispose();
  18115. }
  18116. while (this.highlightLayers.length) {
  18117. this.highlightLayers[0].dispose();
  18118. }
  18119. // Release textures
  18120. while (this.textures.length) {
  18121. this.textures[0].dispose();
  18122. }
  18123. // Release UBO
  18124. this._sceneUbo.dispose();
  18125. // Post-processes
  18126. this.postProcessManager.dispose();
  18127. // Physics
  18128. if (this._physicsEngine) {
  18129. this.disablePhysicsEngine();
  18130. }
  18131. // Remove from engine
  18132. index = this._engine.scenes.indexOf(this);
  18133. if (index > -1) {
  18134. this._engine.scenes.splice(index, 1);
  18135. }
  18136. this._engine.wipeCaches();
  18137. this._engine = null;
  18138. };
  18139. Object.defineProperty(Scene.prototype, "isDisposed", {
  18140. get: function () {
  18141. return !this._engine;
  18142. },
  18143. enumerable: true,
  18144. configurable: true
  18145. });
  18146. // Release sounds & sounds tracks
  18147. Scene.prototype.disposeSounds = function () {
  18148. this.mainSoundTrack.dispose();
  18149. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18150. this.soundTracks[scIndex].dispose();
  18151. }
  18152. };
  18153. // Octrees
  18154. Scene.prototype.getWorldExtends = function () {
  18155. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18156. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18157. for (var index = 0; index < this.meshes.length; index++) {
  18158. var mesh = this.meshes[index];
  18159. mesh.computeWorldMatrix(true);
  18160. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18161. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18162. BABYLON.Tools.CheckExtends(minBox, min, max);
  18163. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18164. }
  18165. return {
  18166. min: min,
  18167. max: max
  18168. };
  18169. };
  18170. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18171. if (maxCapacity === void 0) { maxCapacity = 64; }
  18172. if (maxDepth === void 0) { maxDepth = 2; }
  18173. if (!this._selectionOctree) {
  18174. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18175. }
  18176. var worldExtends = this.getWorldExtends();
  18177. // Update octree
  18178. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18179. return this._selectionOctree;
  18180. };
  18181. // Picking
  18182. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18183. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18184. var engine = this._engine;
  18185. if (!camera) {
  18186. if (!this.activeCamera)
  18187. throw new Error("Active camera not set");
  18188. camera = this.activeCamera;
  18189. }
  18190. var cameraViewport = camera.viewport;
  18191. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18192. // Moving coordinates to local viewport world
  18193. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18194. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18195. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18196. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18197. };
  18198. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18199. if (!BABYLON.PickingInfo) {
  18200. return null;
  18201. }
  18202. var engine = this._engine;
  18203. if (!camera) {
  18204. if (!this.activeCamera)
  18205. throw new Error("Active camera not set");
  18206. camera = this.activeCamera;
  18207. }
  18208. var cameraViewport = camera.viewport;
  18209. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18210. var identity = BABYLON.Matrix.Identity();
  18211. // Moving coordinates to local viewport world
  18212. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18213. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18214. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18215. };
  18216. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18217. if (!BABYLON.PickingInfo) {
  18218. return null;
  18219. }
  18220. var pickingInfo = null;
  18221. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18222. var mesh = this.meshes[meshIndex];
  18223. if (predicate) {
  18224. if (!predicate(mesh)) {
  18225. continue;
  18226. }
  18227. }
  18228. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18229. continue;
  18230. }
  18231. var world = mesh.getWorldMatrix();
  18232. var ray = rayFunction(world);
  18233. var result = mesh.intersects(ray, fastCheck);
  18234. if (!result || !result.hit)
  18235. continue;
  18236. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18237. continue;
  18238. pickingInfo = result;
  18239. if (fastCheck) {
  18240. break;
  18241. }
  18242. }
  18243. return pickingInfo || new BABYLON.PickingInfo();
  18244. };
  18245. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18246. if (!BABYLON.PickingInfo) {
  18247. return null;
  18248. }
  18249. var pickingInfos = new Array();
  18250. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18251. var mesh = this.meshes[meshIndex];
  18252. if (predicate) {
  18253. if (!predicate(mesh)) {
  18254. continue;
  18255. }
  18256. }
  18257. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18258. continue;
  18259. }
  18260. var world = mesh.getWorldMatrix();
  18261. var ray = rayFunction(world);
  18262. var result = mesh.intersects(ray, false);
  18263. if (!result || !result.hit)
  18264. continue;
  18265. pickingInfos.push(result);
  18266. }
  18267. return pickingInfos;
  18268. };
  18269. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18270. if (!BABYLON.PickingInfo) {
  18271. return null;
  18272. }
  18273. var pickingInfo = null;
  18274. camera = camera || this.activeCamera;
  18275. if (this.spriteManagers.length > 0) {
  18276. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18277. var spriteManager = this.spriteManagers[spriteIndex];
  18278. if (!spriteManager.isPickable) {
  18279. continue;
  18280. }
  18281. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18282. if (!result || !result.hit)
  18283. continue;
  18284. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18285. continue;
  18286. pickingInfo = result;
  18287. if (fastCheck) {
  18288. break;
  18289. }
  18290. }
  18291. }
  18292. return pickingInfo || new BABYLON.PickingInfo();
  18293. };
  18294. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18295. /// <param name="x">X position on screen</param>
  18296. /// <param name="y">Y position on screen</param>
  18297. /// <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>
  18298. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18299. /// <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>
  18300. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18301. var _this = this;
  18302. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18303. };
  18304. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18305. /// <param name="x">X position on screen</param>
  18306. /// <param name="y">Y position on screen</param>
  18307. /// <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>
  18308. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18309. /// <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>
  18310. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18311. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18312. };
  18313. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18314. var _this = this;
  18315. return this._internalPick(function (world) {
  18316. if (!_this._pickWithRayInverseMatrix) {
  18317. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18318. }
  18319. world.invertToRef(_this._pickWithRayInverseMatrix);
  18320. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18321. }, predicate, fastCheck);
  18322. };
  18323. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18324. /// <param name="x">X position on screen</param>
  18325. /// <param name="y">Y position on screen</param>
  18326. /// <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>
  18327. /// <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>
  18328. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18329. var _this = this;
  18330. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18331. };
  18332. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18333. /// <param name="ray">Ray to use</param>
  18334. /// <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>
  18335. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18336. var _this = this;
  18337. return this._internalMultiPick(function (world) {
  18338. if (!_this._pickWithRayInverseMatrix) {
  18339. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18340. }
  18341. world.invertToRef(_this._pickWithRayInverseMatrix);
  18342. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18343. }, predicate);
  18344. };
  18345. Scene.prototype.setPointerOverMesh = function (mesh) {
  18346. if (this._pointerOverMesh === mesh) {
  18347. return;
  18348. }
  18349. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18350. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18351. }
  18352. this._pointerOverMesh = mesh;
  18353. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18354. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18355. }
  18356. };
  18357. Scene.prototype.getPointerOverMesh = function () {
  18358. return this._pointerOverMesh;
  18359. };
  18360. Scene.prototype.setPointerOverSprite = function (sprite) {
  18361. if (this._pointerOverSprite === sprite) {
  18362. return;
  18363. }
  18364. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18365. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18366. }
  18367. this._pointerOverSprite = sprite;
  18368. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18369. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18370. }
  18371. };
  18372. Scene.prototype.getPointerOverSprite = function () {
  18373. return this._pointerOverSprite;
  18374. };
  18375. // Physics
  18376. Scene.prototype.getPhysicsEngine = function () {
  18377. return this._physicsEngine;
  18378. };
  18379. /**
  18380. * Enables physics to the current scene
  18381. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18382. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18383. * @return {boolean} was the physics engine initialized
  18384. */
  18385. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18386. if (this._physicsEngine) {
  18387. return true;
  18388. }
  18389. try {
  18390. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18391. return true;
  18392. }
  18393. catch (e) {
  18394. BABYLON.Tools.Error(e.message);
  18395. return false;
  18396. }
  18397. };
  18398. Scene.prototype.disablePhysicsEngine = function () {
  18399. if (!this._physicsEngine) {
  18400. return;
  18401. }
  18402. this._physicsEngine.dispose();
  18403. this._physicsEngine = undefined;
  18404. };
  18405. Scene.prototype.isPhysicsEnabled = function () {
  18406. return this._physicsEngine !== undefined;
  18407. };
  18408. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18409. var mesh = compound.parts[0].mesh;
  18410. mesh.physicsImpostor.dispose();
  18411. mesh.physicsImpostor = null;
  18412. };
  18413. // Misc.
  18414. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18415. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18416. // Light
  18417. if (this.lights.length === 0) {
  18418. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18419. }
  18420. // Camera
  18421. if (!this.activeCamera) {
  18422. var worldExtends = this.getWorldExtends();
  18423. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18424. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18425. var camera;
  18426. var radius = worldSize.length() * 1.5;
  18427. if (createArcRotateCamera) {
  18428. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18429. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18430. arcRotateCamera.wheelPrecision = 100 / radius;
  18431. camera = arcRotateCamera;
  18432. }
  18433. else {
  18434. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18435. freeCamera.setTarget(worldCenter);
  18436. camera = freeCamera;
  18437. }
  18438. camera.minZ = radius * 0.01;
  18439. camera.maxZ = radius * 100;
  18440. camera.speed = radius * 0.2;
  18441. this.activeCamera = camera;
  18442. }
  18443. };
  18444. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale) {
  18445. if (pbr === void 0) { pbr = false; }
  18446. if (scale === void 0) { scale = 1000; }
  18447. if (environmentTexture) {
  18448. this.environmentTexture = environmentTexture;
  18449. }
  18450. if (!this.environmentTexture) {
  18451. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18452. return;
  18453. }
  18454. // Skybox
  18455. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  18456. if (pbr) {
  18457. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18458. hdrSkyboxMaterial.backFaceCulling = false;
  18459. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18460. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18461. hdrSkyboxMaterial.microSurface = 1.0;
  18462. hdrSkyboxMaterial.disableLighting = true;
  18463. hdrSkybox.infiniteDistance = true;
  18464. hdrSkybox.material = hdrSkyboxMaterial;
  18465. }
  18466. else {
  18467. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18468. skyboxMaterial.backFaceCulling = false;
  18469. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18470. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18471. skyboxMaterial.disableLighting = true;
  18472. hdrSkybox.infiniteDistance = true;
  18473. hdrSkybox.material = skyboxMaterial;
  18474. }
  18475. return hdrSkybox;
  18476. };
  18477. // Tags
  18478. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18479. if (tagsQuery === undefined) {
  18480. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18481. return list;
  18482. }
  18483. var listByTags = [];
  18484. forEach = forEach || (function (item) { return; });
  18485. for (var i in list) {
  18486. var item = list[i];
  18487. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18488. listByTags.push(item);
  18489. forEach(item);
  18490. }
  18491. }
  18492. return listByTags;
  18493. };
  18494. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18495. return this._getByTags(this.meshes, tagsQuery, forEach);
  18496. };
  18497. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18498. return this._getByTags(this.cameras, tagsQuery, forEach);
  18499. };
  18500. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18501. return this._getByTags(this.lights, tagsQuery, forEach);
  18502. };
  18503. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18504. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18505. };
  18506. /**
  18507. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18508. * This allowed control for front to back rendering or reversly depending of the special needs.
  18509. *
  18510. * @param renderingGroupId The rendering group id corresponding to its index
  18511. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18512. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18513. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18514. */
  18515. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18516. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18517. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18518. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18519. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18520. };
  18521. /**
  18522. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18523. *
  18524. * @param renderingGroupId The rendering group id corresponding to its index
  18525. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18526. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18527. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18528. */
  18529. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18530. if (depth === void 0) { depth = true; }
  18531. if (stencil === void 0) { stencil = true; }
  18532. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18533. };
  18534. /**
  18535. * Will flag all materials as dirty to trigger new shader compilation
  18536. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18537. */
  18538. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18539. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18540. var material = _a[_i];
  18541. if (predicate && !predicate(material)) {
  18542. continue;
  18543. }
  18544. material.markAsDirty(flag);
  18545. }
  18546. };
  18547. return Scene;
  18548. }());
  18549. // Statics
  18550. Scene._FOGMODE_NONE = 0;
  18551. Scene._FOGMODE_EXP = 1;
  18552. Scene._FOGMODE_EXP2 = 2;
  18553. Scene._FOGMODE_LINEAR = 3;
  18554. Scene.MinDeltaTime = 1.0;
  18555. Scene.MaxDeltaTime = 1000.0;
  18556. Scene.DragMovementThreshold = 10; // in pixels
  18557. Scene.LongPressDelay = 500; // in milliseconds
  18558. Scene.DoubleClickDelay = 300; // in milliseconds
  18559. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18560. BABYLON.Scene = Scene;
  18561. })(BABYLON || (BABYLON = {}));
  18562. //# sourceMappingURL=babylon.scene.js.map
  18563. var BABYLON;
  18564. (function (BABYLON) {
  18565. var Buffer = (function () {
  18566. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18567. if (engine instanceof BABYLON.Mesh) {
  18568. this._engine = engine.getScene().getEngine();
  18569. }
  18570. else {
  18571. this._engine = engine;
  18572. }
  18573. this._updatable = updatable;
  18574. this._data = data;
  18575. this._strideSize = stride;
  18576. if (!postponeInternalCreation) {
  18577. this.create();
  18578. }
  18579. this._instanced = instanced;
  18580. this._instanceDivisor = instanced ? 1 : 0;
  18581. }
  18582. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18583. // a lot of these parameters are ignored as they are overriden by the buffer
  18584. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18585. };
  18586. // Properties
  18587. Buffer.prototype.isUpdatable = function () {
  18588. return this._updatable;
  18589. };
  18590. Buffer.prototype.getData = function () {
  18591. return this._data;
  18592. };
  18593. Buffer.prototype.getBuffer = function () {
  18594. return this._buffer;
  18595. };
  18596. Buffer.prototype.getStrideSize = function () {
  18597. return this._strideSize;
  18598. };
  18599. Buffer.prototype.getIsInstanced = function () {
  18600. return this._instanced;
  18601. };
  18602. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  18603. get: function () {
  18604. return this._instanceDivisor;
  18605. },
  18606. set: function (value) {
  18607. this._instanceDivisor = value;
  18608. if (value == 0) {
  18609. this._instanced = false;
  18610. }
  18611. else {
  18612. this._instanced = true;
  18613. }
  18614. },
  18615. enumerable: true,
  18616. configurable: true
  18617. });
  18618. // Methods
  18619. Buffer.prototype.create = function (data) {
  18620. if (!data && this._buffer) {
  18621. return; // nothing to do
  18622. }
  18623. data = data || this._data;
  18624. if (!this._buffer) {
  18625. if (this._updatable) {
  18626. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18627. this._data = data;
  18628. }
  18629. else {
  18630. this._buffer = this._engine.createVertexBuffer(data);
  18631. }
  18632. }
  18633. else if (this._updatable) {
  18634. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18635. this._data = data;
  18636. }
  18637. };
  18638. Buffer.prototype.update = function (data) {
  18639. this.create(data);
  18640. };
  18641. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18642. if (!this._buffer) {
  18643. return;
  18644. }
  18645. if (this._updatable) {
  18646. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18647. this._data = null;
  18648. }
  18649. };
  18650. Buffer.prototype.dispose = function () {
  18651. if (!this._buffer) {
  18652. return;
  18653. }
  18654. if (this._engine._releaseBuffer(this._buffer)) {
  18655. this._buffer = null;
  18656. }
  18657. };
  18658. return Buffer;
  18659. }());
  18660. BABYLON.Buffer = Buffer;
  18661. })(BABYLON || (BABYLON = {}));
  18662. //# sourceMappingURL=babylon.buffer.js.map
  18663. var BABYLON;
  18664. (function (BABYLON) {
  18665. var VertexBuffer = (function () {
  18666. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18667. if (!stride) {
  18668. // Deduce stride from kind
  18669. switch (kind) {
  18670. case VertexBuffer.PositionKind:
  18671. stride = 3;
  18672. break;
  18673. case VertexBuffer.NormalKind:
  18674. stride = 3;
  18675. break;
  18676. case VertexBuffer.UVKind:
  18677. case VertexBuffer.UV2Kind:
  18678. case VertexBuffer.UV3Kind:
  18679. case VertexBuffer.UV4Kind:
  18680. case VertexBuffer.UV5Kind:
  18681. case VertexBuffer.UV6Kind:
  18682. stride = 2;
  18683. break;
  18684. case VertexBuffer.TangentKind:
  18685. case VertexBuffer.ColorKind:
  18686. stride = 4;
  18687. break;
  18688. case VertexBuffer.MatricesIndicesKind:
  18689. case VertexBuffer.MatricesIndicesExtraKind:
  18690. stride = 4;
  18691. break;
  18692. case VertexBuffer.MatricesWeightsKind:
  18693. case VertexBuffer.MatricesWeightsExtraKind:
  18694. stride = 4;
  18695. break;
  18696. }
  18697. }
  18698. if (data instanceof BABYLON.Buffer) {
  18699. if (!stride) {
  18700. stride = data.getStrideSize();
  18701. }
  18702. this._buffer = data;
  18703. this._ownsBuffer = false;
  18704. }
  18705. else {
  18706. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18707. this._ownsBuffer = true;
  18708. }
  18709. this._stride = stride;
  18710. this._offset = offset ? offset : 0;
  18711. this._size = size ? size : stride;
  18712. this._kind = kind;
  18713. }
  18714. /**
  18715. * Returns the kind of the VertexBuffer (string).
  18716. */
  18717. VertexBuffer.prototype.getKind = function () {
  18718. return this._kind;
  18719. };
  18720. // Properties
  18721. /**
  18722. * Boolean : is the VertexBuffer updatable ?
  18723. */
  18724. VertexBuffer.prototype.isUpdatable = function () {
  18725. return this._buffer.isUpdatable();
  18726. };
  18727. /**
  18728. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18729. */
  18730. VertexBuffer.prototype.getData = function () {
  18731. return this._buffer.getData();
  18732. };
  18733. /**
  18734. * Returns the WebGLBuffer associated to the VertexBuffer.
  18735. */
  18736. VertexBuffer.prototype.getBuffer = function () {
  18737. return this._buffer.getBuffer();
  18738. };
  18739. /**
  18740. * Returns the stride of the VertexBuffer (integer).
  18741. */
  18742. VertexBuffer.prototype.getStrideSize = function () {
  18743. return this._stride;
  18744. };
  18745. /**
  18746. * Returns the offset (integer).
  18747. */
  18748. VertexBuffer.prototype.getOffset = function () {
  18749. return this._offset;
  18750. };
  18751. /**
  18752. * Returns the VertexBuffer total size (integer).
  18753. */
  18754. VertexBuffer.prototype.getSize = function () {
  18755. return this._size;
  18756. };
  18757. /**
  18758. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18759. */
  18760. VertexBuffer.prototype.getIsInstanced = function () {
  18761. return this._buffer.getIsInstanced();
  18762. };
  18763. /**
  18764. * Returns the instancing divisor, zero for non-instanced (integer).
  18765. */
  18766. VertexBuffer.prototype.getInstanceDivisor = function () {
  18767. return this._buffer.instanceDivisor;
  18768. };
  18769. // Methods
  18770. /**
  18771. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18772. * Returns the created WebGLBuffer.
  18773. */
  18774. VertexBuffer.prototype.create = function (data) {
  18775. return this._buffer.create(data);
  18776. };
  18777. /**
  18778. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18779. * Returns the updated WebGLBuffer.
  18780. */
  18781. VertexBuffer.prototype.update = function (data) {
  18782. return this._buffer.update(data);
  18783. };
  18784. /**
  18785. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18786. * Returns the directly updated WebGLBuffer.
  18787. */
  18788. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18789. return this._buffer.updateDirectly(data, offset);
  18790. };
  18791. /**
  18792. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18793. */
  18794. VertexBuffer.prototype.dispose = function () {
  18795. if (this._ownsBuffer) {
  18796. this._buffer.dispose();
  18797. }
  18798. };
  18799. Object.defineProperty(VertexBuffer, "PositionKind", {
  18800. get: function () {
  18801. return VertexBuffer._PositionKind;
  18802. },
  18803. enumerable: true,
  18804. configurable: true
  18805. });
  18806. Object.defineProperty(VertexBuffer, "NormalKind", {
  18807. get: function () {
  18808. return VertexBuffer._NormalKind;
  18809. },
  18810. enumerable: true,
  18811. configurable: true
  18812. });
  18813. Object.defineProperty(VertexBuffer, "TangentKind", {
  18814. get: function () {
  18815. return VertexBuffer._TangentKind;
  18816. },
  18817. enumerable: true,
  18818. configurable: true
  18819. });
  18820. Object.defineProperty(VertexBuffer, "UVKind", {
  18821. get: function () {
  18822. return VertexBuffer._UVKind;
  18823. },
  18824. enumerable: true,
  18825. configurable: true
  18826. });
  18827. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18828. get: function () {
  18829. return VertexBuffer._UV2Kind;
  18830. },
  18831. enumerable: true,
  18832. configurable: true
  18833. });
  18834. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18835. get: function () {
  18836. return VertexBuffer._UV3Kind;
  18837. },
  18838. enumerable: true,
  18839. configurable: true
  18840. });
  18841. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18842. get: function () {
  18843. return VertexBuffer._UV4Kind;
  18844. },
  18845. enumerable: true,
  18846. configurable: true
  18847. });
  18848. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18849. get: function () {
  18850. return VertexBuffer._UV5Kind;
  18851. },
  18852. enumerable: true,
  18853. configurable: true
  18854. });
  18855. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18856. get: function () {
  18857. return VertexBuffer._UV6Kind;
  18858. },
  18859. enumerable: true,
  18860. configurable: true
  18861. });
  18862. Object.defineProperty(VertexBuffer, "ColorKind", {
  18863. get: function () {
  18864. return VertexBuffer._ColorKind;
  18865. },
  18866. enumerable: true,
  18867. configurable: true
  18868. });
  18869. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18870. get: function () {
  18871. return VertexBuffer._MatricesIndicesKind;
  18872. },
  18873. enumerable: true,
  18874. configurable: true
  18875. });
  18876. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18877. get: function () {
  18878. return VertexBuffer._MatricesWeightsKind;
  18879. },
  18880. enumerable: true,
  18881. configurable: true
  18882. });
  18883. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18884. get: function () {
  18885. return VertexBuffer._MatricesIndicesExtraKind;
  18886. },
  18887. enumerable: true,
  18888. configurable: true
  18889. });
  18890. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18891. get: function () {
  18892. return VertexBuffer._MatricesWeightsExtraKind;
  18893. },
  18894. enumerable: true,
  18895. configurable: true
  18896. });
  18897. return VertexBuffer;
  18898. }());
  18899. // Enums
  18900. VertexBuffer._PositionKind = "position";
  18901. VertexBuffer._NormalKind = "normal";
  18902. VertexBuffer._TangentKind = "tangent";
  18903. VertexBuffer._UVKind = "uv";
  18904. VertexBuffer._UV2Kind = "uv2";
  18905. VertexBuffer._UV3Kind = "uv3";
  18906. VertexBuffer._UV4Kind = "uv4";
  18907. VertexBuffer._UV5Kind = "uv5";
  18908. VertexBuffer._UV6Kind = "uv6";
  18909. VertexBuffer._ColorKind = "color";
  18910. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18911. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18912. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18913. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18914. BABYLON.VertexBuffer = VertexBuffer;
  18915. })(BABYLON || (BABYLON = {}));
  18916. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18917. var BABYLON;
  18918. (function (BABYLON) {
  18919. var BaseTexture = (function () {
  18920. function BaseTexture(scene) {
  18921. this._hasAlpha = false;
  18922. this.getAlphaFromRGB = false;
  18923. this.level = 1;
  18924. this.coordinatesIndex = 0;
  18925. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18926. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18927. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18928. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18929. this.isCube = false;
  18930. this.isRenderTarget = false;
  18931. this.animations = new Array();
  18932. /**
  18933. * An event triggered when the texture is disposed.
  18934. * @type {BABYLON.Observable}
  18935. */
  18936. this.onDisposeObservable = new BABYLON.Observable();
  18937. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18938. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18939. this._scene.textures.push(this);
  18940. this._uid = null;
  18941. }
  18942. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18943. get: function () {
  18944. return this._hasAlpha;
  18945. },
  18946. set: function (value) {
  18947. if (this._hasAlpha === value) {
  18948. return;
  18949. }
  18950. this._hasAlpha = value;
  18951. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18952. },
  18953. enumerable: true,
  18954. configurable: true
  18955. });
  18956. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18957. get: function () {
  18958. return this._coordinatesMode;
  18959. },
  18960. set: function (value) {
  18961. if (this._coordinatesMode === value) {
  18962. return;
  18963. }
  18964. this._coordinatesMode = value;
  18965. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18966. },
  18967. enumerable: true,
  18968. configurable: true
  18969. });
  18970. Object.defineProperty(BaseTexture.prototype, "uid", {
  18971. get: function () {
  18972. if (!this._uid) {
  18973. this._uid = BABYLON.Tools.RandomId();
  18974. }
  18975. return this._uid;
  18976. },
  18977. enumerable: true,
  18978. configurable: true
  18979. });
  18980. BaseTexture.prototype.toString = function () {
  18981. return this.name;
  18982. };
  18983. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18984. set: function (callback) {
  18985. if (this._onDisposeObserver) {
  18986. this.onDisposeObservable.remove(this._onDisposeObserver);
  18987. }
  18988. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18989. },
  18990. enumerable: true,
  18991. configurable: true
  18992. });
  18993. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18994. get: function () {
  18995. return true;
  18996. },
  18997. enumerable: true,
  18998. configurable: true
  18999. });
  19000. BaseTexture.prototype.getScene = function () {
  19001. return this._scene;
  19002. };
  19003. BaseTexture.prototype.getTextureMatrix = function () {
  19004. return null;
  19005. };
  19006. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  19007. return null;
  19008. };
  19009. BaseTexture.prototype.getInternalTexture = function () {
  19010. return this._texture;
  19011. };
  19012. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  19013. return !this.isBlocking || this.isReady();
  19014. };
  19015. BaseTexture.prototype.isReady = function () {
  19016. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19017. this.delayLoad();
  19018. return false;
  19019. }
  19020. if (this._texture) {
  19021. return this._texture.isReady;
  19022. }
  19023. return false;
  19024. };
  19025. BaseTexture.prototype.getSize = function () {
  19026. if (this._texture._width) {
  19027. return new BABYLON.Size(this._texture._width, this._texture._height);
  19028. }
  19029. if (this._texture._size) {
  19030. return new BABYLON.Size(this._texture._size, this._texture._size);
  19031. }
  19032. return BABYLON.Size.Zero();
  19033. };
  19034. BaseTexture.prototype.getBaseSize = function () {
  19035. if (!this.isReady() || !this._texture)
  19036. return BABYLON.Size.Zero();
  19037. if (this._texture._size) {
  19038. return new BABYLON.Size(this._texture._size, this._texture._size);
  19039. }
  19040. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19041. };
  19042. BaseTexture.prototype.scale = function (ratio) {
  19043. };
  19044. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19045. get: function () {
  19046. return false;
  19047. },
  19048. enumerable: true,
  19049. configurable: true
  19050. });
  19051. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19052. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19053. for (var index = 0; index < texturesCache.length; index++) {
  19054. var texturesCacheEntry = texturesCache[index];
  19055. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19056. texturesCache.splice(index, 1);
  19057. return;
  19058. }
  19059. }
  19060. };
  19061. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19062. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19063. for (var index = 0; index < texturesCache.length; index++) {
  19064. var texturesCacheEntry = texturesCache[index];
  19065. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19066. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19067. texturesCacheEntry.references++;
  19068. return texturesCacheEntry;
  19069. }
  19070. }
  19071. }
  19072. return null;
  19073. };
  19074. BaseTexture.prototype.delayLoad = function () {
  19075. };
  19076. BaseTexture.prototype.clone = function () {
  19077. return null;
  19078. };
  19079. Object.defineProperty(BaseTexture.prototype, "textureType", {
  19080. get: function () {
  19081. if (!this._texture) {
  19082. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19083. }
  19084. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19085. },
  19086. enumerable: true,
  19087. configurable: true
  19088. });
  19089. BaseTexture.prototype.readPixels = function (faceIndex, lodIndex) {
  19090. if (faceIndex === void 0) { faceIndex = 0; }
  19091. if (lodIndex === void 0) { lodIndex = 0; }
  19092. if (!this._texture) {
  19093. return null;
  19094. }
  19095. var size = this.getSize();
  19096. var engine = this.getScene().getEngine();
  19097. if (this._texture.isCube) {
  19098. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex, lodIndex);
  19099. }
  19100. return engine._readTexturePixels(this._texture, size.width, size.height, -1, lodIndex);
  19101. };
  19102. BaseTexture.prototype.releaseInternalTexture = function () {
  19103. if (this._texture) {
  19104. this._scene.getEngine().releaseInternalTexture(this._texture);
  19105. delete this._texture;
  19106. }
  19107. };
  19108. BaseTexture.prototype.dispose = function () {
  19109. // Animations
  19110. this.getScene().stopAnimation(this);
  19111. // Remove from scene
  19112. this._scene._removePendingData(this);
  19113. var index = this._scene.textures.indexOf(this);
  19114. if (index >= 0) {
  19115. this._scene.textures.splice(index, 1);
  19116. }
  19117. if (this._texture === undefined) {
  19118. return;
  19119. }
  19120. // Release
  19121. this.releaseInternalTexture();
  19122. // Callback
  19123. this.onDisposeObservable.notifyObservers(this);
  19124. this.onDisposeObservable.clear();
  19125. };
  19126. BaseTexture.prototype.serialize = function () {
  19127. if (!this.name) {
  19128. return null;
  19129. }
  19130. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19131. // Animations
  19132. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19133. return serializationObject;
  19134. };
  19135. BaseTexture.WhenAllReady = function (textures, onLoad) {
  19136. var numReady = 0;
  19137. var _loop_1 = function () {
  19138. texture = textures[i];
  19139. if (texture.isReady()) {
  19140. if (++numReady === textures.length) {
  19141. onLoad();
  19142. }
  19143. }
  19144. else {
  19145. observable = texture.onLoadObservable;
  19146. var callback_1 = function () {
  19147. observable.removeCallback(callback_1);
  19148. if (++numReady === textures.length) {
  19149. onLoad();
  19150. }
  19151. };
  19152. observable.add(callback_1);
  19153. }
  19154. };
  19155. var texture, observable;
  19156. for (var i = 0; i < textures.length; i++) {
  19157. _loop_1();
  19158. }
  19159. };
  19160. return BaseTexture;
  19161. }());
  19162. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19163. __decorate([
  19164. BABYLON.serialize()
  19165. ], BaseTexture.prototype, "name", void 0);
  19166. __decorate([
  19167. BABYLON.serialize("hasAlpha")
  19168. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19169. __decorate([
  19170. BABYLON.serialize()
  19171. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19172. __decorate([
  19173. BABYLON.serialize()
  19174. ], BaseTexture.prototype, "level", void 0);
  19175. __decorate([
  19176. BABYLON.serialize()
  19177. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19178. __decorate([
  19179. BABYLON.serialize("coordinatesMode")
  19180. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19181. __decorate([
  19182. BABYLON.serialize()
  19183. ], BaseTexture.prototype, "wrapU", void 0);
  19184. __decorate([
  19185. BABYLON.serialize()
  19186. ], BaseTexture.prototype, "wrapV", void 0);
  19187. __decorate([
  19188. BABYLON.serialize()
  19189. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19190. __decorate([
  19191. BABYLON.serialize()
  19192. ], BaseTexture.prototype, "isCube", void 0);
  19193. __decorate([
  19194. BABYLON.serialize()
  19195. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19196. BABYLON.BaseTexture = BaseTexture;
  19197. })(BABYLON || (BABYLON = {}));
  19198. //# sourceMappingURL=babylon.baseTexture.js.map
  19199. var BABYLON;
  19200. (function (BABYLON) {
  19201. var Texture = (function (_super) {
  19202. __extends(Texture, _super);
  19203. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19204. if (noMipmap === void 0) { noMipmap = false; }
  19205. if (invertY === void 0) { invertY = true; }
  19206. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19207. if (onLoad === void 0) { onLoad = null; }
  19208. if (onError === void 0) { onError = null; }
  19209. if (buffer === void 0) { buffer = null; }
  19210. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19211. var _this = _super.call(this, scene) || this;
  19212. _this.uOffset = 0;
  19213. _this.vOffset = 0;
  19214. _this.uScale = 1.0;
  19215. _this.vScale = 1.0;
  19216. _this.uAng = 0;
  19217. _this.vAng = 0;
  19218. _this.wAng = 0;
  19219. _this._isBlocking = true;
  19220. _this.name = url;
  19221. _this.url = url;
  19222. _this._noMipmap = noMipmap;
  19223. _this._invertY = invertY;
  19224. _this._samplingMode = samplingMode;
  19225. _this._buffer = buffer;
  19226. _this._deleteBuffer = deleteBuffer;
  19227. _this._format = format;
  19228. scene = _this.getScene();
  19229. var load = function () {
  19230. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19231. _this.onLoadObservable.notifyObservers(_this);
  19232. }
  19233. if (onLoad) {
  19234. onLoad();
  19235. }
  19236. if (!_this.isBlocking) {
  19237. scene.resetCachedMaterial();
  19238. }
  19239. };
  19240. if (!url) {
  19241. _this._delayedOnLoad = load;
  19242. _this._delayedOnError = onError;
  19243. return _this;
  19244. }
  19245. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19246. if (!_this._texture) {
  19247. if (!scene.useDelayedTextureLoading) {
  19248. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19249. if (deleteBuffer) {
  19250. delete _this._buffer;
  19251. }
  19252. }
  19253. else {
  19254. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19255. _this._delayedOnLoad = load;
  19256. _this._delayedOnError = onError;
  19257. }
  19258. }
  19259. else {
  19260. if (_this._texture.isReady) {
  19261. BABYLON.Tools.SetImmediate(function () { return load(); });
  19262. }
  19263. else {
  19264. _this._texture.onLoadedCallbacks.push(load);
  19265. }
  19266. }
  19267. return _this;
  19268. }
  19269. Object.defineProperty(Texture.prototype, "noMipmap", {
  19270. get: function () {
  19271. return this._noMipmap;
  19272. },
  19273. enumerable: true,
  19274. configurable: true
  19275. });
  19276. Object.defineProperty(Texture.prototype, "isBlocking", {
  19277. get: function () {
  19278. return this._isBlocking;
  19279. },
  19280. set: function (value) {
  19281. this._isBlocking = value;
  19282. },
  19283. enumerable: true,
  19284. configurable: true
  19285. });
  19286. Texture.prototype.updateURL = function (url) {
  19287. this.url = url;
  19288. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19289. this.delayLoad();
  19290. };
  19291. Texture.prototype.delayLoad = function () {
  19292. var _this = this;
  19293. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19294. return;
  19295. }
  19296. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19297. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19298. if (!this._texture) {
  19299. 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);
  19300. if (this._deleteBuffer) {
  19301. delete this._buffer;
  19302. }
  19303. }
  19304. else {
  19305. if (this._texture.isReady) {
  19306. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19307. }
  19308. else {
  19309. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19310. }
  19311. }
  19312. };
  19313. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19314. if (!this._texture) {
  19315. return;
  19316. }
  19317. this._samplingMode = samplingMode;
  19318. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19319. };
  19320. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19321. x *= this.uScale;
  19322. y *= this.vScale;
  19323. x -= 0.5 * this.uScale;
  19324. y -= 0.5 * this.vScale;
  19325. z -= 0.5;
  19326. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19327. t.x += 0.5 * this.uScale + this.uOffset;
  19328. t.y += 0.5 * this.vScale + this.vOffset;
  19329. t.z += 0.5;
  19330. };
  19331. Texture.prototype.getTextureMatrix = function () {
  19332. if (this.uOffset === this._cachedUOffset &&
  19333. this.vOffset === this._cachedVOffset &&
  19334. this.uScale === this._cachedUScale &&
  19335. this.vScale === this._cachedVScale &&
  19336. this.uAng === this._cachedUAng &&
  19337. this.vAng === this._cachedVAng &&
  19338. this.wAng === this._cachedWAng) {
  19339. return this._cachedTextureMatrix;
  19340. }
  19341. this._cachedUOffset = this.uOffset;
  19342. this._cachedVOffset = this.vOffset;
  19343. this._cachedUScale = this.uScale;
  19344. this._cachedVScale = this.vScale;
  19345. this._cachedUAng = this.uAng;
  19346. this._cachedVAng = this.vAng;
  19347. this._cachedWAng = this.wAng;
  19348. if (!this._cachedTextureMatrix) {
  19349. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19350. this._rowGenerationMatrix = new BABYLON.Matrix();
  19351. this._t0 = BABYLON.Vector3.Zero();
  19352. this._t1 = BABYLON.Vector3.Zero();
  19353. this._t2 = BABYLON.Vector3.Zero();
  19354. }
  19355. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19356. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19357. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19358. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19359. this._t1.subtractInPlace(this._t0);
  19360. this._t2.subtractInPlace(this._t0);
  19361. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19362. this._cachedTextureMatrix.m[0] = this._t1.x;
  19363. this._cachedTextureMatrix.m[1] = this._t1.y;
  19364. this._cachedTextureMatrix.m[2] = this._t1.z;
  19365. this._cachedTextureMatrix.m[4] = this._t2.x;
  19366. this._cachedTextureMatrix.m[5] = this._t2.y;
  19367. this._cachedTextureMatrix.m[6] = this._t2.z;
  19368. this._cachedTextureMatrix.m[8] = this._t0.x;
  19369. this._cachedTextureMatrix.m[9] = this._t0.y;
  19370. this._cachedTextureMatrix.m[10] = this._t0.z;
  19371. return this._cachedTextureMatrix;
  19372. };
  19373. Texture.prototype.getReflectionTextureMatrix = function () {
  19374. if (this.uOffset === this._cachedUOffset &&
  19375. this.vOffset === this._cachedVOffset &&
  19376. this.uScale === this._cachedUScale &&
  19377. this.vScale === this._cachedVScale &&
  19378. this.coordinatesMode === this._cachedCoordinatesMode) {
  19379. return this._cachedTextureMatrix;
  19380. }
  19381. if (!this._cachedTextureMatrix) {
  19382. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19383. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19384. }
  19385. this._cachedCoordinatesMode = this.coordinatesMode;
  19386. switch (this.coordinatesMode) {
  19387. case Texture.PLANAR_MODE:
  19388. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19389. this._cachedTextureMatrix[0] = this.uScale;
  19390. this._cachedTextureMatrix[5] = this.vScale;
  19391. this._cachedTextureMatrix[12] = this.uOffset;
  19392. this._cachedTextureMatrix[13] = this.vOffset;
  19393. break;
  19394. case Texture.PROJECTION_MODE:
  19395. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19396. this._projectionModeMatrix.m[0] = 0.5;
  19397. this._projectionModeMatrix.m[5] = -0.5;
  19398. this._projectionModeMatrix.m[10] = 0.0;
  19399. this._projectionModeMatrix.m[12] = 0.5;
  19400. this._projectionModeMatrix.m[13] = 0.5;
  19401. this._projectionModeMatrix.m[14] = 1.0;
  19402. this._projectionModeMatrix.m[15] = 1.0;
  19403. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19404. break;
  19405. default:
  19406. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19407. break;
  19408. }
  19409. return this._cachedTextureMatrix;
  19410. };
  19411. Texture.prototype.clone = function () {
  19412. var _this = this;
  19413. return BABYLON.SerializationHelper.Clone(function () {
  19414. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19415. }, this);
  19416. };
  19417. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19418. get: function () {
  19419. if (!this._onLoadObservable) {
  19420. this._onLoadObservable = new BABYLON.Observable();
  19421. }
  19422. return this._onLoadObservable;
  19423. },
  19424. enumerable: true,
  19425. configurable: true
  19426. });
  19427. // Statics
  19428. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19429. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19430. if (onLoad === void 0) { onLoad = null; }
  19431. if (onError === void 0) { onError = null; }
  19432. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19433. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19434. };
  19435. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19436. if (parsedTexture.customType) {
  19437. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19438. // Update Sampling Mode
  19439. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19440. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19441. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19442. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19443. }
  19444. }
  19445. return parsedCustomTexture;
  19446. }
  19447. if (parsedTexture.isCube) {
  19448. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19449. }
  19450. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19451. return null;
  19452. }
  19453. var texture = BABYLON.SerializationHelper.Parse(function () {
  19454. if (parsedTexture.mirrorPlane) {
  19455. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19456. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19457. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19458. return mirrorTexture;
  19459. }
  19460. else if (parsedTexture.isRenderTarget) {
  19461. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19462. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19463. return renderTargetTexture;
  19464. }
  19465. else {
  19466. var texture;
  19467. if (parsedTexture.base64String) {
  19468. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19469. }
  19470. else {
  19471. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19472. }
  19473. return texture;
  19474. }
  19475. }, parsedTexture, scene);
  19476. // Update Sampling Mode
  19477. if (parsedTexture.samplingMode) {
  19478. var sampling = parsedTexture.samplingMode;
  19479. if (texture._samplingMode !== sampling) {
  19480. texture.updateSamplingMode(sampling);
  19481. }
  19482. }
  19483. // Animations
  19484. if (parsedTexture.animations) {
  19485. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19486. var parsedAnimation = parsedTexture.animations[animationIndex];
  19487. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19488. }
  19489. }
  19490. return texture;
  19491. };
  19492. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19493. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19494. if (noMipmap === void 0) { noMipmap = false; }
  19495. if (invertY === void 0) { invertY = true; }
  19496. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19497. if (onLoad === void 0) { onLoad = null; }
  19498. if (onError === void 0) { onError = null; }
  19499. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19500. if (name.substr(0, 5) !== "data:") {
  19501. name = "data:" + name;
  19502. }
  19503. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19504. };
  19505. return Texture;
  19506. }(BABYLON.BaseTexture));
  19507. // Constants
  19508. Texture.NEAREST_SAMPLINGMODE = 1;
  19509. Texture.BILINEAR_SAMPLINGMODE = 2;
  19510. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19511. Texture.EXPLICIT_MODE = 0;
  19512. Texture.SPHERICAL_MODE = 1;
  19513. Texture.PLANAR_MODE = 2;
  19514. Texture.CUBIC_MODE = 3;
  19515. Texture.PROJECTION_MODE = 4;
  19516. Texture.SKYBOX_MODE = 5;
  19517. Texture.INVCUBIC_MODE = 6;
  19518. Texture.EQUIRECTANGULAR_MODE = 7;
  19519. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19520. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19521. Texture.CLAMP_ADDRESSMODE = 0;
  19522. Texture.WRAP_ADDRESSMODE = 1;
  19523. Texture.MIRROR_ADDRESSMODE = 2;
  19524. __decorate([
  19525. BABYLON.serialize()
  19526. ], Texture.prototype, "url", void 0);
  19527. __decorate([
  19528. BABYLON.serialize()
  19529. ], Texture.prototype, "uOffset", void 0);
  19530. __decorate([
  19531. BABYLON.serialize()
  19532. ], Texture.prototype, "vOffset", void 0);
  19533. __decorate([
  19534. BABYLON.serialize()
  19535. ], Texture.prototype, "uScale", void 0);
  19536. __decorate([
  19537. BABYLON.serialize()
  19538. ], Texture.prototype, "vScale", void 0);
  19539. __decorate([
  19540. BABYLON.serialize()
  19541. ], Texture.prototype, "uAng", void 0);
  19542. __decorate([
  19543. BABYLON.serialize()
  19544. ], Texture.prototype, "vAng", void 0);
  19545. __decorate([
  19546. BABYLON.serialize()
  19547. ], Texture.prototype, "wAng", void 0);
  19548. __decorate([
  19549. BABYLON.serialize()
  19550. ], Texture.prototype, "isBlocking", null);
  19551. BABYLON.Texture = Texture;
  19552. })(BABYLON || (BABYLON = {}));
  19553. //# sourceMappingURL=babylon.texture.js.map
  19554. var BABYLON;
  19555. (function (BABYLON) {
  19556. var _InstancesBatch = (function () {
  19557. function _InstancesBatch() {
  19558. this.mustReturn = false;
  19559. this.visibleInstances = new Array();
  19560. this.renderSelf = new Array();
  19561. }
  19562. return _InstancesBatch;
  19563. }());
  19564. BABYLON._InstancesBatch = _InstancesBatch;
  19565. var Mesh = (function (_super) {
  19566. __extends(Mesh, _super);
  19567. /**
  19568. * @constructor
  19569. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19570. * @param {Scene} scene The scene to add this mesh to.
  19571. * @param {Node} parent The parent of this mesh, if it has one
  19572. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19573. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19574. * When false, achieved by calling a clone(), also passing False.
  19575. * This will make creation of children, recursive.
  19576. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19577. */
  19578. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19579. if (parent === void 0) { parent = null; }
  19580. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19581. var _this = _super.call(this, name, scene) || this;
  19582. // Events
  19583. /**
  19584. * An event triggered before rendering the mesh
  19585. * @type {BABYLON.Observable}
  19586. */
  19587. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19588. /**
  19589. * An event triggered after rendering the mesh
  19590. * @type {BABYLON.Observable}
  19591. */
  19592. _this.onAfterRenderObservable = new BABYLON.Observable();
  19593. /**
  19594. * An event triggered before drawing the mesh
  19595. * @type {BABYLON.Observable}
  19596. */
  19597. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19598. // Members
  19599. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19600. _this.instances = new Array();
  19601. _this._LODLevels = new Array();
  19602. _this._visibleInstances = {};
  19603. _this._renderIdForInstances = new Array();
  19604. _this._batchCache = new _InstancesBatch();
  19605. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19606. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19607. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19608. // Will be used to save a source mesh reference, If any
  19609. _this._source = null;
  19610. if (source) {
  19611. // Source mesh
  19612. _this._source = source;
  19613. // Geometry
  19614. if (source._geometry) {
  19615. source._geometry.applyToMesh(_this);
  19616. }
  19617. // Deep copy
  19618. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19619. // Parent
  19620. _this.parent = source.parent;
  19621. // Pivot
  19622. _this.setPivotMatrix(source.getPivotMatrix());
  19623. _this.id = name + "." + source.id;
  19624. // Material
  19625. _this.material = source.material;
  19626. var index;
  19627. if (!doNotCloneChildren) {
  19628. // Children
  19629. for (index = 0; index < scene.meshes.length; index++) {
  19630. var mesh = scene.meshes[index];
  19631. if (mesh.parent === source) {
  19632. // doNotCloneChildren is always going to be False
  19633. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19634. }
  19635. }
  19636. }
  19637. // Physics clone
  19638. var physicsEngine = _this.getScene().getPhysicsEngine();
  19639. if (clonePhysicsImpostor && physicsEngine) {
  19640. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19641. if (impostor) {
  19642. _this.physicsImpostor = impostor.clone(_this);
  19643. }
  19644. }
  19645. // Particles
  19646. for (index = 0; index < scene.particleSystems.length; index++) {
  19647. var system = scene.particleSystems[index];
  19648. if (system.emitter === source) {
  19649. system.clone(system.name, _this);
  19650. }
  19651. }
  19652. _this.computeWorldMatrix(true);
  19653. }
  19654. // Parent
  19655. if (parent !== null) {
  19656. _this.parent = parent;
  19657. }
  19658. return _this;
  19659. }
  19660. Object.defineProperty(Mesh, "FRONTSIDE", {
  19661. /**
  19662. * Mesh side orientation : usually the external or front surface
  19663. */
  19664. get: function () {
  19665. return Mesh._FRONTSIDE;
  19666. },
  19667. enumerable: true,
  19668. configurable: true
  19669. });
  19670. Object.defineProperty(Mesh, "BACKSIDE", {
  19671. /**
  19672. * Mesh side orientation : usually the internal or back surface
  19673. */
  19674. get: function () {
  19675. return Mesh._BACKSIDE;
  19676. },
  19677. enumerable: true,
  19678. configurable: true
  19679. });
  19680. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19681. /**
  19682. * Mesh side orientation : both internal and external or front and back surfaces
  19683. */
  19684. get: function () {
  19685. return Mesh._DOUBLESIDE;
  19686. },
  19687. enumerable: true,
  19688. configurable: true
  19689. });
  19690. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19691. /**
  19692. * Mesh side orientation : by default, `FRONTSIDE`
  19693. */
  19694. get: function () {
  19695. return Mesh._DEFAULTSIDE;
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(Mesh, "NO_CAP", {
  19701. /**
  19702. * Mesh cap setting : no cap
  19703. */
  19704. get: function () {
  19705. return Mesh._NO_CAP;
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(Mesh, "CAP_START", {
  19711. /**
  19712. * Mesh cap setting : one cap at the beginning of the mesh
  19713. */
  19714. get: function () {
  19715. return Mesh._CAP_START;
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Object.defineProperty(Mesh, "CAP_END", {
  19721. /**
  19722. * Mesh cap setting : one cap at the end of the mesh
  19723. */
  19724. get: function () {
  19725. return Mesh._CAP_END;
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(Mesh, "CAP_ALL", {
  19731. /**
  19732. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19733. */
  19734. get: function () {
  19735. return Mesh._CAP_ALL;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19741. set: function (callback) {
  19742. if (this._onBeforeDrawObserver) {
  19743. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19744. }
  19745. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19746. },
  19747. enumerable: true,
  19748. configurable: true
  19749. });
  19750. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19751. get: function () {
  19752. return this._morphTargetManager;
  19753. },
  19754. set: function (value) {
  19755. if (this._morphTargetManager === value) {
  19756. return;
  19757. }
  19758. this._morphTargetManager = value;
  19759. this._syncGeometryWithMorphTargetManager();
  19760. },
  19761. enumerable: true,
  19762. configurable: true
  19763. });
  19764. Object.defineProperty(Mesh.prototype, "source", {
  19765. get: function () {
  19766. return this._source;
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. // Methods
  19772. /**
  19773. * Returns the string "Mesh".
  19774. */
  19775. Mesh.prototype.getClassName = function () {
  19776. return "Mesh";
  19777. };
  19778. /**
  19779. * Returns a string.
  19780. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19781. */
  19782. Mesh.prototype.toString = function (fullDetails) {
  19783. var ret = _super.prototype.toString.call(this, fullDetails);
  19784. ret += ", n vertices: " + this.getTotalVertices();
  19785. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19786. if (this.animations) {
  19787. for (var i = 0; i < this.animations.length; i++) {
  19788. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19789. }
  19790. }
  19791. if (fullDetails) {
  19792. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19793. }
  19794. return ret;
  19795. };
  19796. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19797. /**
  19798. * True if the mesh has some Levels Of Details (LOD).
  19799. * Returns a boolean.
  19800. */
  19801. get: function () {
  19802. return this._LODLevels.length > 0;
  19803. },
  19804. enumerable: true,
  19805. configurable: true
  19806. });
  19807. Mesh.prototype._sortLODLevels = function () {
  19808. this._LODLevels.sort(function (a, b) {
  19809. if (a.distance < b.distance) {
  19810. return 1;
  19811. }
  19812. if (a.distance > b.distance) {
  19813. return -1;
  19814. }
  19815. return 0;
  19816. });
  19817. };
  19818. /**
  19819. * Add a mesh as LOD level triggered at the given distance.
  19820. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19821. * @param {number} distance The distance from the center of the object to show this level
  19822. * @param {Mesh} mesh The mesh to be added as LOD level
  19823. * @return {Mesh} This mesh (for chaining)
  19824. */
  19825. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19826. if (mesh && mesh._masterMesh) {
  19827. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19828. return this;
  19829. }
  19830. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19831. this._LODLevels.push(level);
  19832. if (mesh) {
  19833. mesh._masterMesh = this;
  19834. }
  19835. this._sortLODLevels();
  19836. return this;
  19837. };
  19838. /**
  19839. * Returns the LOD level mesh at the passed distance or null if not found.
  19840. * It is related to the method `addLODLevel(distance, mesh)`.
  19841. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19842. * Returns an object Mesh or `null`.
  19843. */
  19844. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19845. for (var index = 0; index < this._LODLevels.length; index++) {
  19846. var level = this._LODLevels[index];
  19847. if (level.distance === distance) {
  19848. return level.mesh;
  19849. }
  19850. }
  19851. return null;
  19852. };
  19853. /**
  19854. * Remove a mesh from the LOD array
  19855. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19856. * @param {Mesh} mesh The mesh to be removed.
  19857. * @return {Mesh} This mesh (for chaining)
  19858. */
  19859. Mesh.prototype.removeLODLevel = function (mesh) {
  19860. for (var index = 0; index < this._LODLevels.length; index++) {
  19861. if (this._LODLevels[index].mesh === mesh) {
  19862. this._LODLevels.splice(index, 1);
  19863. if (mesh) {
  19864. mesh._masterMesh = null;
  19865. }
  19866. }
  19867. }
  19868. this._sortLODLevels();
  19869. return this;
  19870. };
  19871. /**
  19872. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19873. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19874. */
  19875. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19876. if (!this._LODLevels || this._LODLevels.length === 0) {
  19877. return this;
  19878. }
  19879. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19880. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19881. if (this.onLODLevelSelection) {
  19882. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19883. }
  19884. return this;
  19885. }
  19886. for (var index = 0; index < this._LODLevels.length; index++) {
  19887. var level = this._LODLevels[index];
  19888. if (level.distance < distanceToCamera) {
  19889. if (level.mesh) {
  19890. level.mesh._preActivate();
  19891. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19892. }
  19893. if (this.onLODLevelSelection) {
  19894. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19895. }
  19896. return level.mesh;
  19897. }
  19898. }
  19899. if (this.onLODLevelSelection) {
  19900. this.onLODLevelSelection(distanceToCamera, this, this);
  19901. }
  19902. return this;
  19903. };
  19904. Object.defineProperty(Mesh.prototype, "geometry", {
  19905. /**
  19906. * Returns the mesh internal Geometry object.
  19907. */
  19908. get: function () {
  19909. return this._geometry;
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. /**
  19915. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19916. */
  19917. Mesh.prototype.getTotalVertices = function () {
  19918. if (!this._geometry) {
  19919. return 0;
  19920. }
  19921. return this._geometry.getTotalVertices();
  19922. };
  19923. /**
  19924. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19925. * 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.
  19926. * You can force the copy with forceCopy === true
  19927. * Returns null if the mesh has no geometry or no vertex buffer.
  19928. * Possible `kind` values :
  19929. * - BABYLON.VertexBuffer.PositionKind
  19930. * - BABYLON.VertexBuffer.UVKind
  19931. * - BABYLON.VertexBuffer.UV2Kind
  19932. * - BABYLON.VertexBuffer.UV3Kind
  19933. * - BABYLON.VertexBuffer.UV4Kind
  19934. * - BABYLON.VertexBuffer.UV5Kind
  19935. * - BABYLON.VertexBuffer.UV6Kind
  19936. * - BABYLON.VertexBuffer.ColorKind
  19937. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19938. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19939. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19940. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19941. */
  19942. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19943. if (!this._geometry) {
  19944. return null;
  19945. }
  19946. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19947. };
  19948. /**
  19949. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19950. * Returns `undefined` if the mesh has no geometry.
  19951. * Possible `kind` values :
  19952. * - BABYLON.VertexBuffer.PositionKind
  19953. * - BABYLON.VertexBuffer.UVKind
  19954. * - BABYLON.VertexBuffer.UV2Kind
  19955. * - BABYLON.VertexBuffer.UV3Kind
  19956. * - BABYLON.VertexBuffer.UV4Kind
  19957. * - BABYLON.VertexBuffer.UV5Kind
  19958. * - BABYLON.VertexBuffer.UV6Kind
  19959. * - BABYLON.VertexBuffer.ColorKind
  19960. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19961. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19962. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19963. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19964. */
  19965. Mesh.prototype.getVertexBuffer = function (kind) {
  19966. if (!this._geometry) {
  19967. return undefined;
  19968. }
  19969. return this._geometry.getVertexBuffer(kind);
  19970. };
  19971. /**
  19972. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19973. * Possible `kind` values :
  19974. * - BABYLON.VertexBuffer.PositionKind
  19975. * - BABYLON.VertexBuffer.UVKind
  19976. * - BABYLON.VertexBuffer.UV2Kind
  19977. * - BABYLON.VertexBuffer.UV3Kind
  19978. * - BABYLON.VertexBuffer.UV4Kind
  19979. * - BABYLON.VertexBuffer.UV5Kind
  19980. * - BABYLON.VertexBuffer.UV6Kind
  19981. * - BABYLON.VertexBuffer.ColorKind
  19982. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19983. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19984. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19985. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19986. */
  19987. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19988. if (!this._geometry) {
  19989. if (this._delayInfo) {
  19990. return this._delayInfo.indexOf(kind) !== -1;
  19991. }
  19992. return false;
  19993. }
  19994. return this._geometry.isVerticesDataPresent(kind);
  19995. };
  19996. /**
  19997. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19998. * Possible `kind` values :
  19999. * - BABYLON.VertexBuffer.PositionKind
  20000. * - BABYLON.VertexBuffer.UVKind
  20001. * - BABYLON.VertexBuffer.UV2Kind
  20002. * - BABYLON.VertexBuffer.UV3Kind
  20003. * - BABYLON.VertexBuffer.UV4Kind
  20004. * - BABYLON.VertexBuffer.UV5Kind
  20005. * - BABYLON.VertexBuffer.UV6Kind
  20006. * - BABYLON.VertexBuffer.ColorKind
  20007. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20008. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20009. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20010. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20011. */
  20012. Mesh.prototype.getVerticesDataKinds = function () {
  20013. if (!this._geometry) {
  20014. var result = [];
  20015. if (this._delayInfo) {
  20016. this._delayInfo.forEach(function (kind, index, array) {
  20017. result.push(kind);
  20018. });
  20019. }
  20020. return result;
  20021. }
  20022. return this._geometry.getVerticesDataKinds();
  20023. };
  20024. /**
  20025. * Returns a positive integer : the total number of indices in this mesh geometry.
  20026. * Returns zero if the mesh has no geometry.
  20027. */
  20028. Mesh.prototype.getTotalIndices = function () {
  20029. if (!this._geometry) {
  20030. return 0;
  20031. }
  20032. return this._geometry.getTotalIndices();
  20033. };
  20034. /**
  20035. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20036. * 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.
  20037. * Returns an empty array if the mesh has no geometry.
  20038. */
  20039. Mesh.prototype.getIndices = function (copyWhenShared) {
  20040. if (!this._geometry) {
  20041. return [];
  20042. }
  20043. return this._geometry.getIndices(copyWhenShared);
  20044. };
  20045. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20046. get: function () {
  20047. return this._masterMesh !== null && this._masterMesh !== undefined;
  20048. },
  20049. enumerable: true,
  20050. configurable: true
  20051. });
  20052. /**
  20053. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20054. */
  20055. Mesh.prototype.isReady = function () {
  20056. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20057. return false;
  20058. }
  20059. return _super.prototype.isReady.call(this);
  20060. };
  20061. /**
  20062. * Boolean : true if the mesh has been disposed.
  20063. */
  20064. Mesh.prototype.isDisposed = function () {
  20065. return this._isDisposed;
  20066. };
  20067. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20068. get: function () {
  20069. return this._sideOrientation;
  20070. },
  20071. /**
  20072. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20073. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20074. */
  20075. set: function (sideO) {
  20076. this._sideOrientation = sideO;
  20077. },
  20078. enumerable: true,
  20079. configurable: true
  20080. });
  20081. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20082. /**
  20083. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20084. * This property is pertinent only for updatable parametric shapes.
  20085. */
  20086. get: function () {
  20087. return this._areNormalsFrozen;
  20088. },
  20089. enumerable: true,
  20090. configurable: true
  20091. });
  20092. /**
  20093. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20094. * It has no effect at all on other shapes.
  20095. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20096. * Returns the Mesh.
  20097. */
  20098. Mesh.prototype.freezeNormals = function () {
  20099. this._areNormalsFrozen = true;
  20100. return this;
  20101. };
  20102. /**
  20103. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20104. * It has no effect at all on other shapes.
  20105. * It reactivates the mesh normals computation if it was previously frozen.
  20106. * Returns the Mesh.
  20107. */
  20108. Mesh.prototype.unfreezeNormals = function () {
  20109. this._areNormalsFrozen = false;
  20110. return this;
  20111. };
  20112. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20113. /**
  20114. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20115. */
  20116. set: function (count) {
  20117. this._overridenInstanceCount = count;
  20118. },
  20119. enumerable: true,
  20120. configurable: true
  20121. });
  20122. // Methods
  20123. Mesh.prototype._preActivate = function () {
  20124. var sceneRenderId = this.getScene().getRenderId();
  20125. if (this._preActivateId === sceneRenderId) {
  20126. return this;
  20127. }
  20128. this._preActivateId = sceneRenderId;
  20129. this._visibleInstances = null;
  20130. return this;
  20131. };
  20132. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20133. if (this._visibleInstances) {
  20134. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20135. }
  20136. return this;
  20137. };
  20138. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20139. if (!this._visibleInstances) {
  20140. this._visibleInstances = {};
  20141. this._visibleInstances.defaultRenderId = renderId;
  20142. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20143. }
  20144. if (!this._visibleInstances[renderId]) {
  20145. this._visibleInstances[renderId] = new Array();
  20146. }
  20147. this._visibleInstances[renderId].push(instance);
  20148. return this;
  20149. };
  20150. /**
  20151. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20152. * This means the mesh underlying bounding box and sphere are recomputed.
  20153. * Returns the Mesh.
  20154. */
  20155. Mesh.prototype.refreshBoundingInfo = function () {
  20156. if (this._boundingInfo.isLocked) {
  20157. return;
  20158. }
  20159. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20160. if (data) {
  20161. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20162. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20163. }
  20164. if (this.subMeshes) {
  20165. for (var index = 0; index < this.subMeshes.length; index++) {
  20166. this.subMeshes[index].refreshBoundingInfo();
  20167. }
  20168. }
  20169. this._updateBoundingInfo();
  20170. return this;
  20171. };
  20172. Mesh.prototype._createGlobalSubMesh = function () {
  20173. var totalVertices = this.getTotalVertices();
  20174. if (!totalVertices || !this.getIndices()) {
  20175. return null;
  20176. }
  20177. // Check if we need to recreate the submeshes
  20178. if (this.subMeshes && this.subMeshes.length > 0) {
  20179. var totalIndices = this.getIndices().length;
  20180. var needToRecreate = false;
  20181. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20182. var submesh = _a[_i];
  20183. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  20184. needToRecreate = true;
  20185. break;
  20186. }
  20187. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  20188. needToRecreate = true;
  20189. break;
  20190. }
  20191. }
  20192. if (!needToRecreate) {
  20193. return;
  20194. }
  20195. }
  20196. this.releaseSubMeshes();
  20197. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20198. };
  20199. Mesh.prototype.subdivide = function (count) {
  20200. if (count < 1) {
  20201. return;
  20202. }
  20203. var totalIndices = this.getTotalIndices();
  20204. var subdivisionSize = (totalIndices / count) | 0;
  20205. var offset = 0;
  20206. // Ensure that subdivisionSize is a multiple of 3
  20207. while (subdivisionSize % 3 !== 0) {
  20208. subdivisionSize++;
  20209. }
  20210. this.releaseSubMeshes();
  20211. for (var index = 0; index < count; index++) {
  20212. if (offset >= totalIndices) {
  20213. break;
  20214. }
  20215. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20216. offset += subdivisionSize;
  20217. }
  20218. this.synchronizeInstances();
  20219. };
  20220. /**
  20221. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20222. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20223. * The `data` are either a numeric array either a Float32Array.
  20224. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20225. * 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).
  20226. * Note that a new underlying VertexBuffer object is created each call.
  20227. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20228. *
  20229. * Possible `kind` values :
  20230. * - BABYLON.VertexBuffer.PositionKind
  20231. * - BABYLON.VertexBuffer.UVKind
  20232. * - BABYLON.VertexBuffer.UV2Kind
  20233. * - BABYLON.VertexBuffer.UV3Kind
  20234. * - BABYLON.VertexBuffer.UV4Kind
  20235. * - BABYLON.VertexBuffer.UV5Kind
  20236. * - BABYLON.VertexBuffer.UV6Kind
  20237. * - BABYLON.VertexBuffer.ColorKind
  20238. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20239. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20240. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20241. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20242. *
  20243. * Returns the Mesh.
  20244. */
  20245. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20246. if (!this._geometry) {
  20247. var vertexData = new BABYLON.VertexData();
  20248. vertexData.set(data, kind);
  20249. var scene = this.getScene();
  20250. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20251. }
  20252. else {
  20253. this._geometry.setVerticesData(kind, data, updatable, stride);
  20254. }
  20255. return this;
  20256. };
  20257. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20258. if (updatable === void 0) { updatable = true; }
  20259. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20260. return;
  20261. }
  20262. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20263. };
  20264. /**
  20265. * Sets the mesh VertexBuffer.
  20266. * Returns the Mesh.
  20267. */
  20268. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20269. if (!this._geometry) {
  20270. var scene = this.getScene();
  20271. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20272. }
  20273. this._geometry.setVerticesBuffer(buffer);
  20274. return this;
  20275. };
  20276. /**
  20277. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20278. * If the mesh has no geometry, it is simply returned as it is.
  20279. * The `data` are either a numeric array either a Float32Array.
  20280. * No new underlying VertexBuffer object is created.
  20281. * 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.
  20282. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20283. *
  20284. * Possible `kind` values :
  20285. * - BABYLON.VertexBuffer.PositionKind
  20286. * - BABYLON.VertexBuffer.UVKind
  20287. * - BABYLON.VertexBuffer.UV2Kind
  20288. * - BABYLON.VertexBuffer.UV3Kind
  20289. * - BABYLON.VertexBuffer.UV4Kind
  20290. * - BABYLON.VertexBuffer.UV5Kind
  20291. * - BABYLON.VertexBuffer.UV6Kind
  20292. * - BABYLON.VertexBuffer.ColorKind
  20293. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20294. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20295. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20296. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20297. *
  20298. * Returns the Mesh.
  20299. */
  20300. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20301. if (!this._geometry) {
  20302. return;
  20303. }
  20304. if (!makeItUnique) {
  20305. this._geometry.updateVerticesData(kind, data, updateExtends);
  20306. }
  20307. else {
  20308. this.makeGeometryUnique();
  20309. this.updateVerticesData(kind, data, updateExtends, false);
  20310. }
  20311. return this;
  20312. };
  20313. /**
  20314. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20315. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20316. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20317. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20318. * Returns the Mesh.
  20319. */
  20320. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20321. if (computeNormals === void 0) { computeNormals = true; }
  20322. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20323. positionFunction(positions);
  20324. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20325. if (computeNormals) {
  20326. var indices = this.getIndices();
  20327. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20328. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20329. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20330. }
  20331. return this;
  20332. };
  20333. /**
  20334. * Creates a un-shared specific occurence of the geometry for the mesh.
  20335. * Returns the Mesh.
  20336. */
  20337. Mesh.prototype.makeGeometryUnique = function () {
  20338. if (!this._geometry) {
  20339. return;
  20340. }
  20341. var oldGeometry = this._geometry;
  20342. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20343. oldGeometry.releaseForMesh(this, true);
  20344. geometry.applyToMesh(this);
  20345. return this;
  20346. };
  20347. /**
  20348. * Sets the mesh indices.
  20349. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20350. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20351. * This method creates a new index buffer each call.
  20352. * Returns the Mesh.
  20353. */
  20354. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20355. if (!this._geometry) {
  20356. var vertexData = new BABYLON.VertexData();
  20357. vertexData.indices = indices;
  20358. var scene = this.getScene();
  20359. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20360. }
  20361. else {
  20362. this._geometry.setIndices(indices, totalVertices);
  20363. }
  20364. return this;
  20365. };
  20366. /**
  20367. * Invert the geometry to move from a right handed system to a left handed one.
  20368. * Returns the Mesh.
  20369. */
  20370. Mesh.prototype.toLeftHanded = function () {
  20371. if (!this._geometry) {
  20372. return;
  20373. }
  20374. this._geometry.toLeftHanded();
  20375. return this;
  20376. };
  20377. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20378. var engine = this.getScene().getEngine();
  20379. // Wireframe
  20380. var indexToBind;
  20381. if (this._unIndexed) {
  20382. indexToBind = null;
  20383. }
  20384. else {
  20385. switch (fillMode) {
  20386. case BABYLON.Material.PointFillMode:
  20387. indexToBind = null;
  20388. break;
  20389. case BABYLON.Material.WireFrameFillMode:
  20390. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20391. break;
  20392. default:
  20393. case BABYLON.Material.TriangleFillMode:
  20394. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20395. break;
  20396. }
  20397. }
  20398. // VBOs
  20399. this._geometry._bind(effect, indexToBind);
  20400. return this;
  20401. };
  20402. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20403. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20404. return this;
  20405. }
  20406. this.onBeforeDrawObservable.notifyObservers(this);
  20407. var engine = this.getScene().getEngine();
  20408. // Draw order
  20409. switch (fillMode) {
  20410. case BABYLON.Material.PointFillMode:
  20411. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20412. break;
  20413. case BABYLON.Material.WireFrameFillMode:
  20414. if (this._unIndexed) {
  20415. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20416. }
  20417. else {
  20418. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20419. }
  20420. break;
  20421. default:
  20422. if (this._unIndexed) {
  20423. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20424. }
  20425. else {
  20426. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20427. }
  20428. }
  20429. return this;
  20430. };
  20431. /**
  20432. * Registers for this mesh a javascript function called just before the rendering process.
  20433. * This function is passed the current mesh.
  20434. * Return the Mesh.
  20435. */
  20436. Mesh.prototype.registerBeforeRender = function (func) {
  20437. this.onBeforeRenderObservable.add(func);
  20438. return this;
  20439. };
  20440. /**
  20441. * Disposes a previously registered javascript function called before the rendering.
  20442. * This function is passed the current mesh.
  20443. * Returns the Mesh.
  20444. */
  20445. Mesh.prototype.unregisterBeforeRender = function (func) {
  20446. this.onBeforeRenderObservable.removeCallback(func);
  20447. return this;
  20448. };
  20449. /**
  20450. * Registers for this mesh a javascript function called just after the rendering is complete.
  20451. * This function is passed the current mesh.
  20452. * Returns the Mesh.
  20453. */
  20454. Mesh.prototype.registerAfterRender = function (func) {
  20455. this.onAfterRenderObservable.add(func);
  20456. return this;
  20457. };
  20458. /**
  20459. * Disposes a previously registered javascript function called after the rendering.
  20460. * This function is passed the current mesh.
  20461. * Return the Mesh.
  20462. */
  20463. Mesh.prototype.unregisterAfterRender = function (func) {
  20464. this.onAfterRenderObservable.removeCallback(func);
  20465. return this;
  20466. };
  20467. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20468. var scene = this.getScene();
  20469. this._batchCache.mustReturn = false;
  20470. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20471. this._batchCache.visibleInstances[subMeshId] = null;
  20472. if (this._visibleInstances) {
  20473. var currentRenderId = scene.getRenderId();
  20474. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20475. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20476. var selfRenderId = this._renderId;
  20477. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20478. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20479. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20480. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20481. }
  20482. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20483. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20484. this._batchCache.mustReturn = true;
  20485. return this._batchCache;
  20486. }
  20487. if (currentRenderId !== selfRenderId) {
  20488. this._batchCache.renderSelf[subMeshId] = false;
  20489. }
  20490. }
  20491. this._renderIdForInstances[subMeshId] = currentRenderId;
  20492. }
  20493. return this._batchCache;
  20494. };
  20495. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20496. var visibleInstances = batch.visibleInstances[subMesh._id];
  20497. var matricesCount = visibleInstances.length + 1;
  20498. var bufferSize = matricesCount * 16 * 4;
  20499. var currentInstancesBufferSize = this._instancesBufferSize;
  20500. var instancesBuffer = this._instancesBuffer;
  20501. while (this._instancesBufferSize < bufferSize) {
  20502. this._instancesBufferSize *= 2;
  20503. }
  20504. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20505. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20506. }
  20507. var offset = 0;
  20508. var instancesCount = 0;
  20509. var world = this.getWorldMatrix();
  20510. if (batch.renderSelf[subMesh._id]) {
  20511. world.copyToArray(this._instancesData, offset);
  20512. offset += 16;
  20513. instancesCount++;
  20514. }
  20515. if (visibleInstances) {
  20516. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20517. var instance = visibleInstances[instanceIndex];
  20518. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20519. offset += 16;
  20520. instancesCount++;
  20521. }
  20522. }
  20523. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20524. if (instancesBuffer) {
  20525. instancesBuffer.dispose();
  20526. }
  20527. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20528. this._instancesBuffer = instancesBuffer;
  20529. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20530. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20531. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20532. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20533. }
  20534. else {
  20535. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20536. }
  20537. this.geometry._bind(effect);
  20538. this._draw(subMesh, fillMode, instancesCount);
  20539. engine.unbindInstanceAttributes();
  20540. return this;
  20541. };
  20542. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20543. var scene = this.getScene();
  20544. var engine = scene.getEngine();
  20545. if (hardwareInstancedRendering) {
  20546. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20547. }
  20548. else {
  20549. if (batch.renderSelf[subMesh._id]) {
  20550. // Draw
  20551. if (onBeforeDraw) {
  20552. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20553. }
  20554. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20555. }
  20556. if (batch.visibleInstances[subMesh._id]) {
  20557. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20558. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20559. // World
  20560. var world = instance.getWorldMatrix();
  20561. if (onBeforeDraw) {
  20562. onBeforeDraw(true, world, effectiveMaterial);
  20563. }
  20564. // Draw
  20565. this._draw(subMesh, fillMode);
  20566. }
  20567. }
  20568. }
  20569. return this;
  20570. };
  20571. /**
  20572. * Triggers the draw call for the mesh.
  20573. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20574. * Returns the Mesh.
  20575. */
  20576. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20577. var scene = this.getScene();
  20578. // Managing instances
  20579. var batch = this._getInstancesRenderList(subMesh._id);
  20580. if (batch.mustReturn) {
  20581. return this;
  20582. }
  20583. // Checking geometry state
  20584. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20585. return this;
  20586. }
  20587. var callbackIndex;
  20588. this.onBeforeRenderObservable.notifyObservers(this);
  20589. var engine = scene.getEngine();
  20590. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20591. // Material
  20592. var effectiveMaterial = subMesh.getMaterial();
  20593. if (!effectiveMaterial) {
  20594. return this;
  20595. }
  20596. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20597. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20598. return this;
  20599. }
  20600. }
  20601. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20602. return this;
  20603. }
  20604. // Alpha mode
  20605. if (enableAlphaMode) {
  20606. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20607. }
  20608. // Outline - step 1
  20609. var savedDepthWrite = engine.getDepthWrite();
  20610. if (this.renderOutline) {
  20611. engine.setDepthWrite(false);
  20612. scene.getOutlineRenderer().render(subMesh, batch);
  20613. engine.setDepthWrite(savedDepthWrite);
  20614. }
  20615. var effect;
  20616. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20617. effect = subMesh.effect;
  20618. }
  20619. else {
  20620. effect = effectiveMaterial.getEffect();
  20621. }
  20622. effectiveMaterial._preBind(effect);
  20623. // Bind
  20624. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20625. this._bind(subMesh, effect, fillMode);
  20626. var world = this.getWorldMatrix();
  20627. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20628. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20629. }
  20630. else {
  20631. effectiveMaterial.bind(world, this);
  20632. }
  20633. // Draw
  20634. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20635. // Unbind
  20636. effectiveMaterial.unbind();
  20637. // Outline - step 2
  20638. if (this.renderOutline && savedDepthWrite) {
  20639. engine.setDepthWrite(true);
  20640. engine.setColorWrite(false);
  20641. scene.getOutlineRenderer().render(subMesh, batch);
  20642. engine.setColorWrite(true);
  20643. }
  20644. // Overlay
  20645. if (this.renderOverlay) {
  20646. var currentMode = engine.getAlphaMode();
  20647. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20648. scene.getOutlineRenderer().render(subMesh, batch, true);
  20649. engine.setAlphaMode(currentMode);
  20650. }
  20651. this.onAfterRenderObservable.notifyObservers(this);
  20652. return this;
  20653. };
  20654. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20655. if (isInstance) {
  20656. effectiveMaterial.bindOnlyWorldMatrix(world);
  20657. }
  20658. return this;
  20659. };
  20660. /**
  20661. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20662. */
  20663. Mesh.prototype.getEmittedParticleSystems = function () {
  20664. var results = new Array();
  20665. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20666. var particleSystem = this.getScene().particleSystems[index];
  20667. if (particleSystem.emitter === this) {
  20668. results.push(particleSystem);
  20669. }
  20670. }
  20671. return results;
  20672. };
  20673. /**
  20674. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20675. */
  20676. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20677. var results = new Array();
  20678. var descendants = this.getDescendants();
  20679. descendants.push(this);
  20680. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20681. var particleSystem = this.getScene().particleSystems[index];
  20682. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20683. results.push(particleSystem);
  20684. }
  20685. }
  20686. return results;
  20687. };
  20688. Mesh.prototype._checkDelayState = function () {
  20689. var scene = this.getScene();
  20690. if (this._geometry) {
  20691. this._geometry.load(scene);
  20692. }
  20693. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20695. this._queueLoad(this, scene);
  20696. }
  20697. return this;
  20698. };
  20699. Mesh.prototype._queueLoad = function (mesh, scene) {
  20700. var _this = this;
  20701. scene._addPendingData(mesh);
  20702. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20703. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20704. if (data instanceof ArrayBuffer) {
  20705. _this._delayLoadingFunction(data, _this);
  20706. }
  20707. else {
  20708. _this._delayLoadingFunction(JSON.parse(data), _this);
  20709. }
  20710. _this.instances.forEach(function (instance) {
  20711. instance._syncSubMeshes();
  20712. });
  20713. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20714. scene._removePendingData(_this);
  20715. }, function () { }, scene.database, getBinaryData);
  20716. return this;
  20717. };
  20718. /**
  20719. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20720. */
  20721. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20722. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20723. return false;
  20724. }
  20725. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20726. return false;
  20727. }
  20728. this._checkDelayState();
  20729. return true;
  20730. };
  20731. /**
  20732. * Sets the mesh material by the material or multiMaterial `id` property.
  20733. * The material `id` is a string identifying the material or the multiMaterial.
  20734. * This method returns the Mesh.
  20735. */
  20736. Mesh.prototype.setMaterialByID = function (id) {
  20737. var materials = this.getScene().materials;
  20738. var index;
  20739. for (index = materials.length - 1; index > -1; index--) {
  20740. if (materials[index].id === id) {
  20741. this.material = materials[index];
  20742. return this;
  20743. }
  20744. }
  20745. // Multi
  20746. var multiMaterials = this.getScene().multiMaterials;
  20747. for (index = multiMaterials.length - 1; index > -1; index--) {
  20748. if (multiMaterials[index].id === id) {
  20749. this.material = multiMaterials[index];
  20750. return this;
  20751. }
  20752. }
  20753. return this;
  20754. };
  20755. /**
  20756. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20757. */
  20758. Mesh.prototype.getAnimatables = function () {
  20759. var results = [];
  20760. if (this.material) {
  20761. results.push(this.material);
  20762. }
  20763. if (this.skeleton) {
  20764. results.push(this.skeleton);
  20765. }
  20766. return results;
  20767. };
  20768. /**
  20769. * Modifies the mesh geometry according to the passed transformation matrix.
  20770. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20771. * The mesh normals are modified accordingly the same transformation.
  20772. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20773. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20774. * Returns the Mesh.
  20775. */
  20776. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20777. // Position
  20778. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20779. return this;
  20780. }
  20781. var submeshes = this.subMeshes.splice(0);
  20782. this._resetPointsArrayCache();
  20783. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20784. var temp = [];
  20785. var index;
  20786. for (index = 0; index < data.length; index += 3) {
  20787. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20788. }
  20789. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20790. // Normals
  20791. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20792. return this;
  20793. }
  20794. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20795. temp = [];
  20796. for (index = 0; index < data.length; index += 3) {
  20797. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20798. }
  20799. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20800. // flip faces?
  20801. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20802. this.flipFaces();
  20803. }
  20804. // Restore submeshes
  20805. this.releaseSubMeshes();
  20806. this.subMeshes = submeshes;
  20807. return this;
  20808. };
  20809. /**
  20810. * Modifies the mesh geometry according to its own current World Matrix.
  20811. * The mesh World Matrix is then reset.
  20812. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20813. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20814. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20815. * Returns the Mesh.
  20816. */
  20817. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20818. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20819. this.scaling.copyFromFloats(1, 1, 1);
  20820. this.position.copyFromFloats(0, 0, 0);
  20821. this.rotation.copyFromFloats(0, 0, 0);
  20822. //only if quaternion is already set
  20823. if (this.rotationQuaternion) {
  20824. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20825. }
  20826. this._worldMatrix = BABYLON.Matrix.Identity();
  20827. return this;
  20828. };
  20829. Object.defineProperty(Mesh.prototype, "_positions", {
  20830. // Cache
  20831. get: function () {
  20832. if (this._geometry) {
  20833. return this._geometry._positions;
  20834. }
  20835. return null;
  20836. },
  20837. enumerable: true,
  20838. configurable: true
  20839. });
  20840. Mesh.prototype._resetPointsArrayCache = function () {
  20841. if (this._geometry) {
  20842. this._geometry._resetPointsArrayCache();
  20843. }
  20844. return this;
  20845. };
  20846. Mesh.prototype._generatePointsArray = function () {
  20847. if (this._geometry) {
  20848. return this._geometry._generatePointsArray();
  20849. }
  20850. return false;
  20851. };
  20852. /**
  20853. * Returns a new Mesh object generated from the current mesh properties.
  20854. * This method must not get confused with createInstance().
  20855. * The parameter `name` is a string, the name given to the new mesh.
  20856. * The optional parameter `newParent` can be any Node object (default `null`).
  20857. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20858. * 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.
  20859. */
  20860. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20861. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20862. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20863. };
  20864. /**
  20865. * Disposes the mesh.
  20866. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20867. */
  20868. Mesh.prototype.dispose = function (doNotRecurse) {
  20869. var _this = this;
  20870. this.morphTargetManager = undefined;
  20871. if (this._geometry) {
  20872. this._geometry.releaseForMesh(this, true);
  20873. }
  20874. // Sources
  20875. var meshes = this.getScene().meshes;
  20876. meshes.forEach(function (mesh) {
  20877. if (mesh._source && mesh._source === _this) {
  20878. mesh._source = null;
  20879. }
  20880. });
  20881. this._source = null;
  20882. // Instances
  20883. if (this._instancesBuffer) {
  20884. this._instancesBuffer.dispose();
  20885. this._instancesBuffer = null;
  20886. }
  20887. while (this.instances.length) {
  20888. this.instances[0].dispose();
  20889. }
  20890. // Highlight layers.
  20891. var highlightLayers = this.getScene().highlightLayers;
  20892. for (var i = 0; i < highlightLayers.length; i++) {
  20893. var highlightLayer = highlightLayers[i];
  20894. if (highlightLayer) {
  20895. highlightLayer.removeMesh(this);
  20896. highlightLayer.removeExcludedMesh(this);
  20897. }
  20898. }
  20899. _super.prototype.dispose.call(this, doNotRecurse);
  20900. };
  20901. /**
  20902. * Modifies the mesh geometry according to a displacement map.
  20903. * 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.
  20904. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20905. * This method returns nothing.
  20906. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20907. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20908. * 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.
  20909. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20910. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20911. *
  20912. * Returns the Mesh.
  20913. */
  20914. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20915. var _this = this;
  20916. var scene = this.getScene();
  20917. var onload = function (img) {
  20918. // Getting height map data
  20919. var canvas = document.createElement("canvas");
  20920. var context = canvas.getContext("2d");
  20921. var heightMapWidth = img.width;
  20922. var heightMapHeight = img.height;
  20923. canvas.width = heightMapWidth;
  20924. canvas.height = heightMapHeight;
  20925. context.drawImage(img, 0, 0);
  20926. // Create VertexData from map data
  20927. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20928. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20929. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20930. //execute success callback, if set
  20931. if (onSuccess) {
  20932. onSuccess(_this);
  20933. }
  20934. };
  20935. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20936. return this;
  20937. };
  20938. /**
  20939. * Modifies the mesh geometry according to a displacementMap buffer.
  20940. * 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.
  20941. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20942. * This method returns nothing.
  20943. * 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.
  20944. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20945. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20946. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20947. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20948. *
  20949. * Returns the Mesh.
  20950. */
  20951. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20952. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20953. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20954. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20955. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20956. return this;
  20957. }
  20958. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20959. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20960. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20961. var position = BABYLON.Vector3.Zero();
  20962. var normal = BABYLON.Vector3.Zero();
  20963. var uv = BABYLON.Vector2.Zero();
  20964. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20965. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20966. for (var index = 0; index < positions.length; index += 3) {
  20967. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20968. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20969. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20970. // Compute height
  20971. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20972. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20973. var pos = (u + v * heightMapWidth) * 4;
  20974. var r = buffer[pos] / 255.0;
  20975. var g = buffer[pos + 1] / 255.0;
  20976. var b = buffer[pos + 2] / 255.0;
  20977. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20978. normal.normalize();
  20979. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20980. position = position.add(normal);
  20981. position.toArray(positions, index);
  20982. }
  20983. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20984. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20985. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20986. return this;
  20987. };
  20988. /**
  20989. * Modify the mesh to get a flat shading rendering.
  20990. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20991. * This method returns the Mesh.
  20992. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20993. */
  20994. Mesh.prototype.convertToFlatShadedMesh = function () {
  20995. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20996. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20997. var kinds = this.getVerticesDataKinds();
  20998. var vbs = [];
  20999. var data = [];
  21000. var newdata = [];
  21001. var updatableNormals = false;
  21002. var kindIndex;
  21003. var kind;
  21004. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21005. kind = kinds[kindIndex];
  21006. var vertexBuffer = this.getVertexBuffer(kind);
  21007. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21008. updatableNormals = vertexBuffer.isUpdatable();
  21009. kinds.splice(kindIndex, 1);
  21010. kindIndex--;
  21011. continue;
  21012. }
  21013. vbs[kind] = vertexBuffer;
  21014. data[kind] = vbs[kind].getData();
  21015. newdata[kind] = [];
  21016. }
  21017. // Save previous submeshes
  21018. var previousSubmeshes = this.subMeshes.slice(0);
  21019. var indices = this.getIndices();
  21020. var totalIndices = this.getTotalIndices();
  21021. // Generating unique vertices per face
  21022. var index;
  21023. for (index = 0; index < totalIndices; index++) {
  21024. var vertexIndex = indices[index];
  21025. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21026. kind = kinds[kindIndex];
  21027. var stride = vbs[kind].getStrideSize();
  21028. for (var offset = 0; offset < stride; offset++) {
  21029. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21030. }
  21031. }
  21032. }
  21033. // Updating faces & normal
  21034. var normals = [];
  21035. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21036. for (index = 0; index < totalIndices; index += 3) {
  21037. indices[index] = index;
  21038. indices[index + 1] = index + 1;
  21039. indices[index + 2] = index + 2;
  21040. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21041. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21042. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21043. var p1p2 = p1.subtract(p2);
  21044. var p3p2 = p3.subtract(p2);
  21045. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21046. // Store same normals for every vertex
  21047. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21048. normals.push(normal.x);
  21049. normals.push(normal.y);
  21050. normals.push(normal.z);
  21051. }
  21052. }
  21053. this.setIndices(indices);
  21054. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21055. // Updating vertex buffers
  21056. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21057. kind = kinds[kindIndex];
  21058. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21059. }
  21060. // Updating submeshes
  21061. this.releaseSubMeshes();
  21062. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21063. var previousOne = previousSubmeshes[submeshIndex];
  21064. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21065. }
  21066. this.synchronizeInstances();
  21067. return this;
  21068. };
  21069. /**
  21070. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21071. * In other words, more vertices, no more indices and a single bigger VBO.
  21072. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21073. * Returns the Mesh.
  21074. */
  21075. Mesh.prototype.convertToUnIndexedMesh = function () {
  21076. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21077. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21078. var kinds = this.getVerticesDataKinds();
  21079. var vbs = [];
  21080. var data = [];
  21081. var newdata = [];
  21082. var updatableNormals = false;
  21083. var kindIndex;
  21084. var kind;
  21085. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21086. kind = kinds[kindIndex];
  21087. var vertexBuffer = this.getVertexBuffer(kind);
  21088. vbs[kind] = vertexBuffer;
  21089. data[kind] = vbs[kind].getData();
  21090. newdata[kind] = [];
  21091. }
  21092. // Save previous submeshes
  21093. var previousSubmeshes = this.subMeshes.slice(0);
  21094. var indices = this.getIndices();
  21095. var totalIndices = this.getTotalIndices();
  21096. // Generating unique vertices per face
  21097. var index;
  21098. for (index = 0; index < totalIndices; index++) {
  21099. var vertexIndex = indices[index];
  21100. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21101. kind = kinds[kindIndex];
  21102. var stride = vbs[kind].getStrideSize();
  21103. for (var offset = 0; offset < stride; offset++) {
  21104. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21105. }
  21106. }
  21107. }
  21108. // Updating indices
  21109. for (index = 0; index < totalIndices; index += 3) {
  21110. indices[index] = index;
  21111. indices[index + 1] = index + 1;
  21112. indices[index + 2] = index + 2;
  21113. }
  21114. this.setIndices(indices);
  21115. // Updating vertex buffers
  21116. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21117. kind = kinds[kindIndex];
  21118. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21119. }
  21120. // Updating submeshes
  21121. this.releaseSubMeshes();
  21122. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21123. var previousOne = previousSubmeshes[submeshIndex];
  21124. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21125. }
  21126. this._unIndexed = true;
  21127. this.synchronizeInstances();
  21128. return this;
  21129. };
  21130. /**
  21131. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21132. * This method returns the Mesh.
  21133. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21134. */
  21135. Mesh.prototype.flipFaces = function (flipNormals) {
  21136. if (flipNormals === void 0) { flipNormals = false; }
  21137. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21138. var i;
  21139. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21140. for (i = 0; i < vertex_data.normals.length; i++) {
  21141. vertex_data.normals[i] *= -1;
  21142. }
  21143. }
  21144. var temp;
  21145. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21146. // reassign indices
  21147. temp = vertex_data.indices[i + 1];
  21148. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21149. vertex_data.indices[i + 2] = temp;
  21150. }
  21151. vertex_data.applyToMesh(this);
  21152. return this;
  21153. };
  21154. // Instances
  21155. /**
  21156. * Creates a new InstancedMesh object from the mesh model.
  21157. * An instance shares the same properties and the same material than its model.
  21158. * Only these properties of each instance can then be set individually :
  21159. * - position
  21160. * - rotation
  21161. * - rotationQuaternion
  21162. * - setPivotMatrix
  21163. * - scaling
  21164. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21165. * Warning : this method is not supported for Line mesh and LineSystem
  21166. */
  21167. Mesh.prototype.createInstance = function (name) {
  21168. return new BABYLON.InstancedMesh(name, this);
  21169. };
  21170. /**
  21171. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21172. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21173. * This method returns the Mesh.
  21174. */
  21175. Mesh.prototype.synchronizeInstances = function () {
  21176. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21177. var instance = this.instances[instanceIndex];
  21178. instance._syncSubMeshes();
  21179. }
  21180. return this;
  21181. };
  21182. /**
  21183. * Simplify the mesh according to the given array of settings.
  21184. * Function will return immediately and will simplify async. It returns the Mesh.
  21185. * @param settings a collection of simplification settings.
  21186. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21187. * @param type the type of simplification to run.
  21188. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21189. */
  21190. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21191. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21192. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21193. this.getScene().simplificationQueue.addTask({
  21194. settings: settings,
  21195. parallelProcessing: parallelProcessing,
  21196. mesh: this,
  21197. simplificationType: simplificationType,
  21198. successCallback: successCallback
  21199. });
  21200. return this;
  21201. };
  21202. /**
  21203. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21204. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21205. * This should be used together with the simplification to avoid disappearing triangles.
  21206. * Returns the Mesh.
  21207. * @param successCallback an optional success callback to be called after the optimization finished.
  21208. */
  21209. Mesh.prototype.optimizeIndices = function (successCallback) {
  21210. var _this = this;
  21211. var indices = this.getIndices();
  21212. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21213. var vectorPositions = [];
  21214. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21215. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21216. }
  21217. var dupes = [];
  21218. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21219. var realPos = vectorPositions.length - 1 - iteration;
  21220. var testedPosition = vectorPositions[realPos];
  21221. for (var j = 0; j < realPos; ++j) {
  21222. var againstPosition = vectorPositions[j];
  21223. if (testedPosition.equals(againstPosition)) {
  21224. dupes[realPos] = j;
  21225. break;
  21226. }
  21227. }
  21228. }, function () {
  21229. for (var i = 0; i < indices.length; ++i) {
  21230. indices[i] = dupes[indices[i]] || indices[i];
  21231. }
  21232. //indices are now reordered
  21233. var originalSubMeshes = _this.subMeshes.slice(0);
  21234. _this.setIndices(indices);
  21235. _this.subMeshes = originalSubMeshes;
  21236. if (successCallback) {
  21237. successCallback(_this);
  21238. }
  21239. });
  21240. return this;
  21241. };
  21242. Mesh.prototype.serialize = function (serializationObject) {
  21243. serializationObject.name = this.name;
  21244. serializationObject.id = this.id;
  21245. serializationObject.type = this.getClassName();
  21246. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21247. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21248. }
  21249. serializationObject.position = this.position.asArray();
  21250. if (this.rotationQuaternion) {
  21251. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21252. }
  21253. else if (this.rotation) {
  21254. serializationObject.rotation = this.rotation.asArray();
  21255. }
  21256. serializationObject.scaling = this.scaling.asArray();
  21257. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21258. serializationObject.isEnabled = this.isEnabled();
  21259. serializationObject.isVisible = this.isVisible;
  21260. serializationObject.infiniteDistance = this.infiniteDistance;
  21261. serializationObject.pickable = this.isPickable;
  21262. serializationObject.receiveShadows = this.receiveShadows;
  21263. serializationObject.billboardMode = this.billboardMode;
  21264. serializationObject.visibility = this.visibility;
  21265. serializationObject.checkCollisions = this.checkCollisions;
  21266. serializationObject.isBlocker = this.isBlocker;
  21267. // Parent
  21268. if (this.parent) {
  21269. serializationObject.parentId = this.parent.id;
  21270. }
  21271. // Geometry
  21272. var geometry = this._geometry;
  21273. if (geometry) {
  21274. var geometryId = geometry.id;
  21275. serializationObject.geometryId = geometryId;
  21276. // SubMeshes
  21277. serializationObject.subMeshes = [];
  21278. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21279. var subMesh = this.subMeshes[subIndex];
  21280. serializationObject.subMeshes.push({
  21281. materialIndex: subMesh.materialIndex,
  21282. verticesStart: subMesh.verticesStart,
  21283. verticesCount: subMesh.verticesCount,
  21284. indexStart: subMesh.indexStart,
  21285. indexCount: subMesh.indexCount
  21286. });
  21287. }
  21288. }
  21289. // Material
  21290. if (this.material) {
  21291. serializationObject.materialId = this.material.id;
  21292. }
  21293. else {
  21294. this.material = null;
  21295. }
  21296. // Morph targets
  21297. if (this.morphTargetManager) {
  21298. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21299. }
  21300. // Skeleton
  21301. if (this.skeleton) {
  21302. serializationObject.skeletonId = this.skeleton.id;
  21303. }
  21304. // Physics
  21305. //TODO implement correct serialization for physics impostors.
  21306. if (this.getPhysicsImpostor()) {
  21307. var impostor = this.getPhysicsImpostor();
  21308. serializationObject.physicsMass = impostor.getParam("mass");
  21309. serializationObject.physicsFriction = impostor.getParam("friction");
  21310. serializationObject.physicsRestitution = impostor.getParam("mass");
  21311. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21312. }
  21313. // Metadata
  21314. if (this.metadata) {
  21315. serializationObject.metadata = this.metadata;
  21316. }
  21317. // Instances
  21318. serializationObject.instances = [];
  21319. for (var index = 0; index < this.instances.length; index++) {
  21320. var instance = this.instances[index];
  21321. var serializationInstance = {
  21322. name: instance.name,
  21323. position: instance.position.asArray(),
  21324. scaling: instance.scaling.asArray()
  21325. };
  21326. if (instance.rotationQuaternion) {
  21327. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21328. }
  21329. else if (instance.rotation) {
  21330. serializationInstance.rotation = instance.rotation.asArray();
  21331. }
  21332. serializationObject.instances.push(serializationInstance);
  21333. // Animations
  21334. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21335. serializationInstance.ranges = instance.serializeAnimationRanges();
  21336. }
  21337. //
  21338. // Animations
  21339. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21340. serializationObject.ranges = this.serializeAnimationRanges();
  21341. // Layer mask
  21342. serializationObject.layerMask = this.layerMask;
  21343. // Alpha
  21344. serializationObject.alphaIndex = this.alphaIndex;
  21345. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21346. // Overlay
  21347. serializationObject.overlayAlpha = this.overlayAlpha;
  21348. serializationObject.overlayColor = this.overlayColor.asArray();
  21349. serializationObject.renderOverlay = this.renderOverlay;
  21350. // Fog
  21351. serializationObject.applyFog = this.applyFog;
  21352. // Action Manager
  21353. if (this.actionManager) {
  21354. serializationObject.actions = this.actionManager.serialize(this.name);
  21355. }
  21356. };
  21357. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21358. if (!this.geometry) {
  21359. return;
  21360. }
  21361. this._markSubMeshesAsAttributesDirty();
  21362. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21363. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21364. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21365. this.morphTargetManager = undefined;
  21366. return;
  21367. }
  21368. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21369. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21370. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21371. if (morphTarget.hasNormals) {
  21372. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21373. }
  21374. if (morphTarget.hasTangents) {
  21375. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21376. }
  21377. }
  21378. }
  21379. else {
  21380. var index = 0;
  21381. // Positions
  21382. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21383. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21384. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21385. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21386. }
  21387. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21388. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21389. }
  21390. index++;
  21391. }
  21392. }
  21393. };
  21394. // Statics
  21395. /**
  21396. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21397. * The parameter `parsedMesh` is the mesh to be copied.
  21398. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21399. */
  21400. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21401. var mesh;
  21402. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21403. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21404. }
  21405. else {
  21406. mesh = new Mesh(parsedMesh.name, scene);
  21407. }
  21408. mesh.id = parsedMesh.id;
  21409. if (BABYLON.Tags) {
  21410. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21411. }
  21412. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21413. if (parsedMesh.metadata !== undefined) {
  21414. mesh.metadata = parsedMesh.metadata;
  21415. }
  21416. if (parsedMesh.rotationQuaternion) {
  21417. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21418. }
  21419. else if (parsedMesh.rotation) {
  21420. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21421. }
  21422. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21423. if (parsedMesh.localMatrix) {
  21424. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21425. }
  21426. else if (parsedMesh.pivotMatrix) {
  21427. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21428. }
  21429. mesh.setEnabled(parsedMesh.isEnabled);
  21430. mesh.isVisible = parsedMesh.isVisible;
  21431. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21432. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21433. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21434. if (parsedMesh.applyFog !== undefined) {
  21435. mesh.applyFog = parsedMesh.applyFog;
  21436. }
  21437. if (parsedMesh.pickable !== undefined) {
  21438. mesh.isPickable = parsedMesh.pickable;
  21439. }
  21440. if (parsedMesh.alphaIndex !== undefined) {
  21441. mesh.alphaIndex = parsedMesh.alphaIndex;
  21442. }
  21443. mesh.receiveShadows = parsedMesh.receiveShadows;
  21444. mesh.billboardMode = parsedMesh.billboardMode;
  21445. if (parsedMesh.visibility !== undefined) {
  21446. mesh.visibility = parsedMesh.visibility;
  21447. }
  21448. mesh.checkCollisions = parsedMesh.checkCollisions;
  21449. if (parsedMesh.isBlocker !== undefined) {
  21450. mesh.isBlocker = parsedMesh.isBlocker;
  21451. }
  21452. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21453. // freezeWorldMatrix
  21454. if (parsedMesh.freezeWorldMatrix) {
  21455. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21456. }
  21457. // Parent
  21458. if (parsedMesh.parentId) {
  21459. mesh._waitingParentId = parsedMesh.parentId;
  21460. }
  21461. // Actions
  21462. if (parsedMesh.actions !== undefined) {
  21463. mesh._waitingActions = parsedMesh.actions;
  21464. }
  21465. // Overlay
  21466. if (parsedMesh.overlayAlpha !== undefined) {
  21467. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21468. }
  21469. if (parsedMesh.overlayColor !== undefined) {
  21470. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21471. }
  21472. if (parsedMesh.renderOverlay !== undefined) {
  21473. mesh.renderOverlay = parsedMesh.renderOverlay;
  21474. }
  21475. // Geometry
  21476. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21477. if (parsedMesh.delayLoadingFile) {
  21478. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21479. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21480. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21481. if (parsedMesh._binaryInfo) {
  21482. mesh._binaryInfo = parsedMesh._binaryInfo;
  21483. }
  21484. mesh._delayInfo = [];
  21485. if (parsedMesh.hasUVs) {
  21486. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21487. }
  21488. if (parsedMesh.hasUVs2) {
  21489. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21490. }
  21491. if (parsedMesh.hasUVs3) {
  21492. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21493. }
  21494. if (parsedMesh.hasUVs4) {
  21495. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21496. }
  21497. if (parsedMesh.hasUVs5) {
  21498. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21499. }
  21500. if (parsedMesh.hasUVs6) {
  21501. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21502. }
  21503. if (parsedMesh.hasColors) {
  21504. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21505. }
  21506. if (parsedMesh.hasMatricesIndices) {
  21507. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21508. }
  21509. if (parsedMesh.hasMatricesWeights) {
  21510. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21511. }
  21512. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21513. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21514. mesh._checkDelayState();
  21515. }
  21516. }
  21517. else {
  21518. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21519. }
  21520. // Material
  21521. if (parsedMesh.materialId) {
  21522. mesh.setMaterialByID(parsedMesh.materialId);
  21523. }
  21524. else {
  21525. mesh.material = null;
  21526. }
  21527. // Morph targets
  21528. if (parsedMesh.morphTargetManagerId > -1) {
  21529. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21530. }
  21531. // Skeleton
  21532. if (parsedMesh.skeletonId > -1) {
  21533. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21534. if (parsedMesh.numBoneInfluencers) {
  21535. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21536. }
  21537. }
  21538. // Animations
  21539. if (parsedMesh.animations) {
  21540. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21541. var parsedAnimation = parsedMesh.animations[animationIndex];
  21542. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21543. }
  21544. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21545. }
  21546. if (parsedMesh.autoAnimate) {
  21547. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21548. }
  21549. // Layer Mask
  21550. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21551. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21552. }
  21553. else {
  21554. mesh.layerMask = 0x0FFFFFFF;
  21555. }
  21556. // Physics
  21557. if (parsedMesh.physicsImpostor) {
  21558. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21559. mass: parsedMesh.physicsMass,
  21560. friction: parsedMesh.physicsFriction,
  21561. restitution: parsedMesh.physicsRestitution
  21562. }, scene);
  21563. }
  21564. // Instances
  21565. if (parsedMesh.instances) {
  21566. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21567. var parsedInstance = parsedMesh.instances[index];
  21568. var instance = mesh.createInstance(parsedInstance.name);
  21569. if (BABYLON.Tags) {
  21570. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21571. }
  21572. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21573. if (parsedInstance.parentId) {
  21574. instance._waitingParentId = parsedInstance.parentId;
  21575. }
  21576. if (parsedInstance.rotationQuaternion) {
  21577. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21578. }
  21579. else if (parsedInstance.rotation) {
  21580. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21581. }
  21582. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21583. instance.checkCollisions = mesh.checkCollisions;
  21584. if (parsedMesh.animations) {
  21585. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21586. parsedAnimation = parsedMesh.animations[animationIndex];
  21587. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21588. }
  21589. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21590. }
  21591. }
  21592. }
  21593. return mesh;
  21594. };
  21595. /**
  21596. * Creates a ribbon mesh.
  21597. * Please consider using the same method from the MeshBuilder class instead.
  21598. * 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.
  21599. *
  21600. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21601. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21602. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21603. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21604. * 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.
  21605. * 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.
  21606. * 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
  21607. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21608. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21610. */
  21611. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21612. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21613. pathArray: pathArray,
  21614. closeArray: closeArray,
  21615. closePath: closePath,
  21616. offset: offset,
  21617. updatable: updatable,
  21618. sideOrientation: sideOrientation,
  21619. instance: instance
  21620. }, scene);
  21621. };
  21622. /**
  21623. * Creates a plane polygonal mesh. By default, this is a disc.
  21624. * Please consider using the same method from the MeshBuilder class instead.
  21625. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21626. * 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.
  21627. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21628. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21630. */
  21631. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21632. var options = {
  21633. radius: radius,
  21634. tessellation: tessellation,
  21635. sideOrientation: sideOrientation,
  21636. updatable: updatable
  21637. };
  21638. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21639. };
  21640. /**
  21641. * Creates a box mesh.
  21642. * Please consider using the same method from the MeshBuilder class instead.
  21643. * The parameter `size` sets the size (float) of each box side (default 1).
  21644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21647. */
  21648. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21649. var options = {
  21650. size: size,
  21651. sideOrientation: sideOrientation,
  21652. updatable: updatable
  21653. };
  21654. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21655. };
  21656. /**
  21657. * Creates a sphere mesh.
  21658. * Please consider using the same method from the MeshBuilder class instead.
  21659. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21660. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21661. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21662. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21663. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21664. */
  21665. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21666. var options = {
  21667. segments: segments,
  21668. diameterX: diameter,
  21669. diameterY: diameter,
  21670. diameterZ: diameter,
  21671. sideOrientation: sideOrientation,
  21672. updatable: updatable
  21673. };
  21674. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21675. };
  21676. /**
  21677. * Creates a cylinder or a cone mesh.
  21678. * Please consider using the same method from the MeshBuilder class instead.
  21679. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21680. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21681. * 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.
  21682. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21683. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21684. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21685. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21687. */
  21688. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21689. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21690. if (scene !== undefined) {
  21691. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21692. updatable = scene;
  21693. }
  21694. scene = subdivisions;
  21695. subdivisions = 1;
  21696. }
  21697. var options = {
  21698. height: height,
  21699. diameterTop: diameterTop,
  21700. diameterBottom: diameterBottom,
  21701. tessellation: tessellation,
  21702. subdivisions: subdivisions,
  21703. sideOrientation: sideOrientation,
  21704. updatable: updatable
  21705. };
  21706. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21707. };
  21708. // Torus (Code from SharpDX.org)
  21709. /**
  21710. * Creates a torus mesh.
  21711. * Please consider using the same method from the MeshBuilder class instead.
  21712. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21713. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21714. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21715. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21716. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21717. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21718. */
  21719. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21720. var options = {
  21721. diameter: diameter,
  21722. thickness: thickness,
  21723. tessellation: tessellation,
  21724. sideOrientation: sideOrientation,
  21725. updatable: updatable
  21726. };
  21727. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21728. };
  21729. /**
  21730. * Creates a torus knot mesh.
  21731. * Please consider using the same method from the MeshBuilder class instead.
  21732. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21733. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21734. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21735. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21736. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21737. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21739. */
  21740. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21741. var options = {
  21742. radius: radius,
  21743. tube: tube,
  21744. radialSegments: radialSegments,
  21745. tubularSegments: tubularSegments,
  21746. p: p,
  21747. q: q,
  21748. sideOrientation: sideOrientation,
  21749. updatable: updatable
  21750. };
  21751. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21752. };
  21753. /**
  21754. * Creates a line mesh.
  21755. * Please consider using the same method from the MeshBuilder class instead.
  21756. * 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.
  21757. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21758. * The parameter `points` is an array successive Vector3.
  21759. * 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
  21760. * When updating an instance, remember that only point positions can change, not the number of points.
  21761. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21762. */
  21763. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21764. var options = {
  21765. points: points,
  21766. updatable: updatable,
  21767. instance: instance
  21768. };
  21769. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21770. };
  21771. /**
  21772. * Creates a dashed line mesh.
  21773. * Please consider using the same method from the MeshBuilder class instead.
  21774. * 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.
  21775. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21776. * The parameter `points` is an array successive Vector3.
  21777. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21778. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21779. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21780. * 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
  21781. * When updating an instance, remember that only point positions can change, not the number of points.
  21782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21783. */
  21784. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21785. var options = {
  21786. points: points,
  21787. dashSize: dashSize,
  21788. gapSize: gapSize,
  21789. dashNb: dashNb,
  21790. updatable: updatable,
  21791. instance: instance
  21792. };
  21793. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21794. };
  21795. /**
  21796. * Creates a polygon mesh.
  21797. * Please consider using the same method from the MeshBuilder class instead.
  21798. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21799. * 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.
  21800. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21801. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21802. * Remember you can only change the shape positions, not their number when updating a polygon.
  21803. */
  21804. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21805. var options = {
  21806. shape: shape,
  21807. holes: holes,
  21808. updatable: updatable,
  21809. sideOrientation: sideOrientation
  21810. };
  21811. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21812. };
  21813. /**
  21814. * Creates an extruded polygon mesh, with depth in the Y direction.
  21815. * Please consider using the same method from the MeshBuilder class instead.
  21816. */
  21817. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21818. var options = {
  21819. shape: shape,
  21820. holes: holes,
  21821. depth: depth,
  21822. updatable: updatable,
  21823. sideOrientation: sideOrientation
  21824. };
  21825. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21826. };
  21827. /**
  21828. * Creates an extruded shape mesh.
  21829. * 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.
  21830. * Please consider using the same method from the MeshBuilder class instead.
  21831. *
  21832. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21833. * 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
  21834. * extruded along the Z axis.
  21835. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21836. * 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.
  21837. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21838. * 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
  21839. * 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
  21840. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21842. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21844. */
  21845. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21846. var options = {
  21847. shape: shape,
  21848. path: path,
  21849. scale: scale,
  21850. rotation: rotation,
  21851. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21852. sideOrientation: sideOrientation,
  21853. instance: instance,
  21854. updatable: updatable
  21855. };
  21856. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21857. };
  21858. /**
  21859. * Creates an custom extruded shape mesh.
  21860. * 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.
  21861. * Please consider using the same method from the MeshBuilder class instead.
  21862. *
  21863. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21864. * 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
  21865. * extruded along the Z axis.
  21866. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21867. * 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
  21868. * and the distance of this point from the begining of the path :
  21869. * ```javascript
  21870. * var rotationFunction = function(i, distance) {
  21871. * // do things
  21872. * return rotationValue; }
  21873. * ```
  21874. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21875. * 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
  21876. * and the distance of this point from the begining of the path :
  21877. * ```javascript
  21878. * var scaleFunction = function(i, distance) {
  21879. * // do things
  21880. * return scaleValue;}
  21881. * ```
  21882. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21883. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21884. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21885. * 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
  21886. * 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
  21887. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21888. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21889. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21891. */
  21892. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21893. var options = {
  21894. shape: shape,
  21895. path: path,
  21896. scaleFunction: scaleFunction,
  21897. rotationFunction: rotationFunction,
  21898. ribbonCloseArray: ribbonCloseArray,
  21899. ribbonClosePath: ribbonClosePath,
  21900. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21901. sideOrientation: sideOrientation,
  21902. instance: instance,
  21903. updatable: updatable
  21904. };
  21905. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21906. };
  21907. /**
  21908. * Creates lathe mesh.
  21909. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21910. * Please consider using the same method from the MeshBuilder class instead.
  21911. * 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
  21912. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21913. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21914. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21915. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21916. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21918. */
  21919. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21920. var options = {
  21921. shape: shape,
  21922. radius: radius,
  21923. tessellation: tessellation,
  21924. sideOrientation: sideOrientation,
  21925. updatable: updatable
  21926. };
  21927. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21928. };
  21929. /**
  21930. * Creates a plane mesh.
  21931. * Please consider using the same method from the MeshBuilder class instead.
  21932. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21936. */
  21937. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21938. var options = {
  21939. size: size,
  21940. width: size,
  21941. height: size,
  21942. sideOrientation: sideOrientation,
  21943. updatable: updatable
  21944. };
  21945. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21946. };
  21947. /**
  21948. * Creates a ground mesh.
  21949. * Please consider using the same method from the MeshBuilder class instead.
  21950. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21951. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21953. */
  21954. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21955. var options = {
  21956. width: width,
  21957. height: height,
  21958. subdivisions: subdivisions,
  21959. updatable: updatable
  21960. };
  21961. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21962. };
  21963. /**
  21964. * Creates a tiled ground mesh.
  21965. * Please consider using the same method from the MeshBuilder class instead.
  21966. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21967. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21968. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21969. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21970. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21971. * numbers of subdivisions on the ground width and height of each tile.
  21972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21973. */
  21974. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21975. var options = {
  21976. xmin: xmin,
  21977. zmin: zmin,
  21978. xmax: xmax,
  21979. zmax: zmax,
  21980. subdivisions: subdivisions,
  21981. precision: precision,
  21982. updatable: updatable
  21983. };
  21984. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21985. };
  21986. /**
  21987. * Creates a ground mesh from a height map.
  21988. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21989. * Please consider using the same method from the MeshBuilder class instead.
  21990. * The parameter `url` sets the URL of the height map image resource.
  21991. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21992. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21993. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21994. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21995. * 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).
  21996. * This function is passed the newly built mesh :
  21997. * ```javascript
  21998. * function(mesh) { // do things
  21999. * return; }
  22000. * ```
  22001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22002. */
  22003. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22004. var options = {
  22005. width: width,
  22006. height: height,
  22007. subdivisions: subdivisions,
  22008. minHeight: minHeight,
  22009. maxHeight: maxHeight,
  22010. updatable: updatable,
  22011. onReady: onReady
  22012. };
  22013. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22014. };
  22015. /**
  22016. * Creates a tube mesh.
  22017. * 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.
  22018. * Please consider using the same method from the MeshBuilder class instead.
  22019. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22020. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22021. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22022. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22023. * 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.
  22024. * It must return a radius value (positive float) :
  22025. * ```javascript
  22026. * var radiusFunction = function(i, distance) {
  22027. * // do things
  22028. * return radius; }
  22029. * ```
  22030. * 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
  22031. * 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
  22032. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22033. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22035. */
  22036. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22037. var options = {
  22038. path: path,
  22039. radius: radius,
  22040. tessellation: tessellation,
  22041. radiusFunction: radiusFunction,
  22042. arc: 1,
  22043. cap: cap,
  22044. updatable: updatable,
  22045. sideOrientation: sideOrientation,
  22046. instance: instance
  22047. };
  22048. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22049. };
  22050. /**
  22051. * Creates a polyhedron mesh.
  22052. * Please consider using the same method from the MeshBuilder class instead.
  22053. * 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
  22054. * to choose the wanted type.
  22055. * The parameter `size` (positive float, default 1) sets the polygon size.
  22056. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22057. * 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`.
  22058. * 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
  22059. * 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)`).
  22060. * 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
  22061. * 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.
  22062. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22063. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22064. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22065. */
  22066. Mesh.CreatePolyhedron = function (name, options, scene) {
  22067. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22068. };
  22069. /**
  22070. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22071. * Please consider using the same method from the MeshBuilder class instead.
  22072. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22073. * 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`).
  22074. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22075. * 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.
  22076. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22077. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22078. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22079. */
  22080. Mesh.CreateIcoSphere = function (name, options, scene) {
  22081. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22082. };
  22083. /**
  22084. * Creates a decal mesh.
  22085. * Please consider using the same method from the MeshBuilder class instead.
  22086. * 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.
  22087. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22088. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22089. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22090. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22091. */
  22092. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22093. var options = {
  22094. position: position,
  22095. normal: normal,
  22096. size: size,
  22097. angle: angle
  22098. };
  22099. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22100. };
  22101. // Skeletons
  22102. /**
  22103. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22104. */
  22105. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22106. var source;
  22107. if (!this._sourcePositions) {
  22108. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22109. this._sourcePositions = new Float32Array(source);
  22110. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22111. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22112. }
  22113. }
  22114. return this._sourcePositions;
  22115. };
  22116. /**
  22117. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22118. */
  22119. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22120. var source;
  22121. if (!this._sourceNormals) {
  22122. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22123. this._sourceNormals = new Float32Array(source);
  22124. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22125. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22126. }
  22127. }
  22128. return this._sourceNormals;
  22129. };
  22130. /**
  22131. * Updates the vertex buffer by applying transformation from the bones.
  22132. * Returns the Mesh.
  22133. *
  22134. * @param {skeleton} skeleton to apply
  22135. */
  22136. Mesh.prototype.applySkeleton = function (skeleton) {
  22137. if (!this.geometry) {
  22138. return this;
  22139. }
  22140. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22141. return this;
  22142. }
  22143. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22144. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22145. return this;
  22146. }
  22147. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22148. return this;
  22149. }
  22150. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22151. return this;
  22152. }
  22153. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22154. return this;
  22155. }
  22156. if (!this._sourcePositions) {
  22157. var submeshes = this.subMeshes.slice();
  22158. this.setPositionsForCPUSkinning();
  22159. this.subMeshes = submeshes;
  22160. }
  22161. if (!this._sourceNormals) {
  22162. this.setNormalsForCPUSkinning();
  22163. }
  22164. // positionsData checks for not being Float32Array will only pass at most once
  22165. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22166. if (!(positionsData instanceof Float32Array)) {
  22167. positionsData = new Float32Array(positionsData);
  22168. }
  22169. // normalsData checks for not being Float32Array will only pass at most once
  22170. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22171. if (!(normalsData instanceof Float32Array)) {
  22172. normalsData = new Float32Array(normalsData);
  22173. }
  22174. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22175. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22176. var needExtras = this.numBoneInfluencers > 4;
  22177. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22178. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22179. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22180. var tempVector3 = BABYLON.Vector3.Zero();
  22181. var finalMatrix = new BABYLON.Matrix();
  22182. var tempMatrix = new BABYLON.Matrix();
  22183. var matWeightIdx = 0;
  22184. var inf;
  22185. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22186. var weight;
  22187. for (inf = 0; inf < 4; inf++) {
  22188. weight = matricesWeightsData[matWeightIdx + inf];
  22189. if (weight > 0) {
  22190. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22191. finalMatrix.addToSelf(tempMatrix);
  22192. }
  22193. else
  22194. break;
  22195. }
  22196. if (needExtras) {
  22197. for (inf = 0; inf < 4; inf++) {
  22198. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22199. if (weight > 0) {
  22200. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22201. finalMatrix.addToSelf(tempMatrix);
  22202. }
  22203. else
  22204. break;
  22205. }
  22206. }
  22207. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22208. tempVector3.toArray(positionsData, index);
  22209. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22210. tempVector3.toArray(normalsData, index);
  22211. finalMatrix.reset();
  22212. }
  22213. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22214. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22215. return this;
  22216. };
  22217. // Tools
  22218. /**
  22219. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22220. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22221. */
  22222. Mesh.MinMax = function (meshes) {
  22223. var minVector = null;
  22224. var maxVector = null;
  22225. meshes.forEach(function (mesh, index, array) {
  22226. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22227. if (!minVector) {
  22228. minVector = boundingBox.minimumWorld;
  22229. maxVector = boundingBox.maximumWorld;
  22230. }
  22231. else {
  22232. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22233. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22234. }
  22235. });
  22236. return {
  22237. min: minVector,
  22238. max: maxVector
  22239. };
  22240. };
  22241. /**
  22242. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22243. */
  22244. Mesh.Center = function (meshesOrMinMaxVector) {
  22245. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22246. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22247. };
  22248. /**
  22249. * Merge the array of meshes into a single mesh for performance reasons.
  22250. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22251. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22252. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22253. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22254. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22255. */
  22256. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22257. if (disposeSource === void 0) { disposeSource = true; }
  22258. var index;
  22259. if (!allow32BitsIndices) {
  22260. var totalVertices = 0;
  22261. // Counting vertices
  22262. for (index = 0; index < meshes.length; index++) {
  22263. if (meshes[index]) {
  22264. totalVertices += meshes[index].getTotalVertices();
  22265. if (totalVertices > 65536) {
  22266. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22267. return null;
  22268. }
  22269. }
  22270. }
  22271. }
  22272. // Merge
  22273. var vertexData;
  22274. var otherVertexData;
  22275. var indiceArray = new Array();
  22276. var source;
  22277. for (index = 0; index < meshes.length; index++) {
  22278. if (meshes[index]) {
  22279. meshes[index].computeWorldMatrix(true);
  22280. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22281. otherVertexData.transform(meshes[index].getWorldMatrix());
  22282. if (vertexData) {
  22283. vertexData.merge(otherVertexData);
  22284. }
  22285. else {
  22286. vertexData = otherVertexData;
  22287. source = meshes[index];
  22288. }
  22289. if (subdivideWithSubMeshes) {
  22290. indiceArray.push(meshes[index].getTotalIndices());
  22291. }
  22292. }
  22293. }
  22294. if (!meshSubclass) {
  22295. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22296. }
  22297. vertexData.applyToMesh(meshSubclass);
  22298. // Setting properties
  22299. meshSubclass.material = source.material;
  22300. meshSubclass.checkCollisions = source.checkCollisions;
  22301. // Cleaning
  22302. if (disposeSource) {
  22303. for (index = 0; index < meshes.length; index++) {
  22304. if (meshes[index]) {
  22305. meshes[index].dispose();
  22306. }
  22307. }
  22308. }
  22309. // Subdivide
  22310. if (subdivideWithSubMeshes) {
  22311. //-- Suppresions du submesh global
  22312. meshSubclass.releaseSubMeshes();
  22313. index = 0;
  22314. var offset = 0;
  22315. //-- aplique la subdivision en fonction du tableau d'indices
  22316. while (index < indiceArray.length) {
  22317. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22318. offset += indiceArray[index];
  22319. index++;
  22320. }
  22321. }
  22322. return meshSubclass;
  22323. };
  22324. return Mesh;
  22325. }(BABYLON.AbstractMesh));
  22326. // Consts
  22327. Mesh._FRONTSIDE = 0;
  22328. Mesh._BACKSIDE = 1;
  22329. Mesh._DOUBLESIDE = 2;
  22330. Mesh._DEFAULTSIDE = 0;
  22331. Mesh._NO_CAP = 0;
  22332. Mesh._CAP_START = 1;
  22333. Mesh._CAP_END = 2;
  22334. Mesh._CAP_ALL = 3;
  22335. BABYLON.Mesh = Mesh;
  22336. })(BABYLON || (BABYLON = {}));
  22337. //# sourceMappingURL=babylon.mesh.js.map
  22338. var BABYLON;
  22339. (function (BABYLON) {
  22340. var BaseSubMesh = (function () {
  22341. function BaseSubMesh() {
  22342. }
  22343. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  22344. get: function () {
  22345. return this._materialEffect;
  22346. },
  22347. enumerable: true,
  22348. configurable: true
  22349. });
  22350. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  22351. if (this._materialEffect === effect) {
  22352. return;
  22353. }
  22354. this._materialDefines = defines;
  22355. this._materialEffect = effect;
  22356. };
  22357. return BaseSubMesh;
  22358. }());
  22359. BABYLON.BaseSubMesh = BaseSubMesh;
  22360. var SubMesh = (function (_super) {
  22361. __extends(SubMesh, _super);
  22362. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22363. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22364. var _this = _super.call(this) || this;
  22365. _this.materialIndex = materialIndex;
  22366. _this.verticesStart = verticesStart;
  22367. _this.verticesCount = verticesCount;
  22368. _this.indexStart = indexStart;
  22369. _this.indexCount = indexCount;
  22370. _this._renderId = 0;
  22371. _this._mesh = mesh;
  22372. _this._renderingMesh = renderingMesh || mesh;
  22373. mesh.subMeshes.push(_this);
  22374. _this._trianglePlanes = [];
  22375. _this._id = mesh.subMeshes.length - 1;
  22376. if (createBoundingBox) {
  22377. _this.refreshBoundingInfo();
  22378. mesh.computeWorldMatrix(true);
  22379. }
  22380. return _this;
  22381. }
  22382. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22383. get: function () {
  22384. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22385. },
  22386. enumerable: true,
  22387. configurable: true
  22388. });
  22389. /**
  22390. * Returns the submesh BoudingInfo object.
  22391. */
  22392. SubMesh.prototype.getBoundingInfo = function () {
  22393. if (this.IsGlobal) {
  22394. return this._mesh.getBoundingInfo();
  22395. }
  22396. return this._boundingInfo;
  22397. };
  22398. /**
  22399. * Sets the submesh BoundingInfo.
  22400. * Return the SubMesh.
  22401. */
  22402. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22403. this._boundingInfo = boundingInfo;
  22404. return this;
  22405. };
  22406. /**
  22407. * Returns the mesh of the current submesh.
  22408. */
  22409. SubMesh.prototype.getMesh = function () {
  22410. return this._mesh;
  22411. };
  22412. /**
  22413. * Returns the rendering mesh of the submesh.
  22414. */
  22415. SubMesh.prototype.getRenderingMesh = function () {
  22416. return this._renderingMesh;
  22417. };
  22418. /**
  22419. * Returns the submesh material.
  22420. */
  22421. SubMesh.prototype.getMaterial = function () {
  22422. var rootMaterial = this._renderingMesh.material;
  22423. if (rootMaterial && rootMaterial.getSubMaterial) {
  22424. var multiMaterial = rootMaterial;
  22425. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22426. if (this._currentMaterial !== effectiveMaterial) {
  22427. this._currentMaterial = effectiveMaterial;
  22428. if (this._materialDefines) {
  22429. this._materialDefines.markAllAsDirty();
  22430. }
  22431. }
  22432. return effectiveMaterial;
  22433. }
  22434. if (!rootMaterial) {
  22435. return this._mesh.getScene().defaultMaterial;
  22436. }
  22437. return rootMaterial;
  22438. };
  22439. // Methods
  22440. /**
  22441. * Sets a new updated BoundingInfo object to the submesh.
  22442. * Returns the SubMesh.
  22443. */
  22444. SubMesh.prototype.refreshBoundingInfo = function () {
  22445. this._lastColliderWorldVertices = null;
  22446. if (this.IsGlobal) {
  22447. return;
  22448. }
  22449. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22450. if (!data) {
  22451. this._boundingInfo = this._mesh._boundingInfo;
  22452. return;
  22453. }
  22454. var indices = this._renderingMesh.getIndices();
  22455. var extend;
  22456. //is this the only submesh?
  22457. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22458. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22459. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22460. }
  22461. else {
  22462. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22463. }
  22464. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22465. return this;
  22466. };
  22467. SubMesh.prototype._checkCollision = function (collider) {
  22468. return this.getBoundingInfo()._checkCollision(collider);
  22469. };
  22470. /**
  22471. * Updates the submesh BoundingInfo.
  22472. * Returns the Submesh.
  22473. */
  22474. SubMesh.prototype.updateBoundingInfo = function (world) {
  22475. if (!this.getBoundingInfo()) {
  22476. this.refreshBoundingInfo();
  22477. }
  22478. this.getBoundingInfo().update(world);
  22479. return this;
  22480. };
  22481. /**
  22482. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22483. * Boolean returned.
  22484. */
  22485. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22486. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22487. };
  22488. /**
  22489. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22490. * Boolean returned.
  22491. */
  22492. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22493. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22494. };
  22495. /**
  22496. * Renders the submesh.
  22497. * Returns it.
  22498. */
  22499. SubMesh.prototype.render = function (enableAlphaMode) {
  22500. this._renderingMesh.render(this, enableAlphaMode);
  22501. return this;
  22502. };
  22503. /**
  22504. * Returns a new Index Buffer.
  22505. * Type returned : WebGLBuffer.
  22506. */
  22507. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22508. if (!this._linesIndexBuffer) {
  22509. var linesIndices = [];
  22510. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22511. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22512. }
  22513. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22514. this.linesIndexCount = linesIndices.length;
  22515. }
  22516. return this._linesIndexBuffer;
  22517. };
  22518. /**
  22519. * True is the passed Ray intersects the submesh bounding box.
  22520. * Boolean returned.
  22521. */
  22522. SubMesh.prototype.canIntersects = function (ray) {
  22523. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22524. };
  22525. /**
  22526. * Returns an object IntersectionInfo.
  22527. */
  22528. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22529. var intersectInfo = null;
  22530. // LineMesh first as it's also a Mesh...
  22531. if (this._mesh instanceof BABYLON.LinesMesh) {
  22532. var lineMesh = this._mesh;
  22533. // Line test
  22534. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22535. var p0 = positions[indices[index]];
  22536. var p1 = positions[indices[index + 1]];
  22537. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22538. if (length < 0) {
  22539. continue;
  22540. }
  22541. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22542. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22543. if (fastCheck) {
  22544. break;
  22545. }
  22546. }
  22547. }
  22548. }
  22549. else {
  22550. // Triangles test
  22551. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22552. var p0 = positions[indices[index]];
  22553. var p1 = positions[indices[index + 1]];
  22554. var p2 = positions[indices[index + 2]];
  22555. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22556. if (currentIntersectInfo) {
  22557. if (currentIntersectInfo.distance < 0) {
  22558. continue;
  22559. }
  22560. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22561. intersectInfo = currentIntersectInfo;
  22562. intersectInfo.faceId = index / 3;
  22563. if (fastCheck) {
  22564. break;
  22565. }
  22566. }
  22567. }
  22568. }
  22569. }
  22570. return intersectInfo;
  22571. };
  22572. // Clone
  22573. /**
  22574. * Creates a new Submesh from the passed Mesh.
  22575. */
  22576. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22577. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22578. if (!this.IsGlobal) {
  22579. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22580. }
  22581. return result;
  22582. };
  22583. // Dispose
  22584. /**
  22585. * Disposes the Submesh.
  22586. * Returns nothing.
  22587. */
  22588. SubMesh.prototype.dispose = function () {
  22589. if (this._linesIndexBuffer) {
  22590. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22591. this._linesIndexBuffer = null;
  22592. }
  22593. // Remove from mesh
  22594. var index = this._mesh.subMeshes.indexOf(this);
  22595. this._mesh.subMeshes.splice(index, 1);
  22596. };
  22597. // Statics
  22598. /**
  22599. * Creates a new Submesh from the passed parameters :
  22600. * - materialIndex (integer) : the index of the main mesh material.
  22601. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22602. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22603. * - mesh (Mesh) : the main mesh to create the submesh from.
  22604. * - renderingMesh (optional Mesh) : rendering mesh.
  22605. */
  22606. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22607. var minVertexIndex = Number.MAX_VALUE;
  22608. var maxVertexIndex = -Number.MAX_VALUE;
  22609. renderingMesh = renderingMesh || mesh;
  22610. var indices = renderingMesh.getIndices();
  22611. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22612. var vertexIndex = indices[index];
  22613. if (vertexIndex < minVertexIndex)
  22614. minVertexIndex = vertexIndex;
  22615. if (vertexIndex > maxVertexIndex)
  22616. maxVertexIndex = vertexIndex;
  22617. }
  22618. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22619. };
  22620. return SubMesh;
  22621. }(BaseSubMesh));
  22622. BABYLON.SubMesh = SubMesh;
  22623. })(BABYLON || (BABYLON = {}));
  22624. //# sourceMappingURL=babylon.subMesh.js.map
  22625. var BABYLON;
  22626. (function (BABYLON) {
  22627. var EffectFallbacks = (function () {
  22628. function EffectFallbacks() {
  22629. this._defines = {};
  22630. this._currentRank = 32;
  22631. this._maxRank = -1;
  22632. }
  22633. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22634. if (!this._defines[rank]) {
  22635. if (rank < this._currentRank) {
  22636. this._currentRank = rank;
  22637. }
  22638. if (rank > this._maxRank) {
  22639. this._maxRank = rank;
  22640. }
  22641. this._defines[rank] = new Array();
  22642. }
  22643. this._defines[rank].push(define);
  22644. };
  22645. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22646. this._meshRank = rank;
  22647. this._mesh = mesh;
  22648. if (rank < this._currentRank) {
  22649. this._currentRank = rank;
  22650. }
  22651. if (rank > this._maxRank) {
  22652. this._maxRank = rank;
  22653. }
  22654. };
  22655. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22656. get: function () {
  22657. return this._currentRank <= this._maxRank;
  22658. },
  22659. enumerable: true,
  22660. configurable: true
  22661. });
  22662. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22663. // First we try to switch to CPU skinning
  22664. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22665. this._mesh.computeBonesUsingShaders = false;
  22666. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22667. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22668. var scene = this._mesh.getScene();
  22669. for (var index = 0; index < scene.meshes.length; index++) {
  22670. var otherMesh = scene.meshes[index];
  22671. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22672. otherMesh.computeBonesUsingShaders = false;
  22673. }
  22674. }
  22675. }
  22676. else {
  22677. var currentFallbacks = this._defines[this._currentRank];
  22678. if (currentFallbacks) {
  22679. for (var index = 0; index < currentFallbacks.length; index++) {
  22680. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22681. }
  22682. }
  22683. this._currentRank++;
  22684. }
  22685. return currentDefines;
  22686. };
  22687. return EffectFallbacks;
  22688. }());
  22689. BABYLON.EffectFallbacks = EffectFallbacks;
  22690. var EffectCreationOptions = (function () {
  22691. function EffectCreationOptions() {
  22692. }
  22693. return EffectCreationOptions;
  22694. }());
  22695. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22696. var Effect = (function () {
  22697. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22698. var _this = this;
  22699. this.uniqueId = 0;
  22700. this.onCompileObservable = new BABYLON.Observable();
  22701. this.onErrorObservable = new BABYLON.Observable();
  22702. this.onBindObservable = new BABYLON.Observable();
  22703. this._uniformBuffersNames = {};
  22704. this._isReady = false;
  22705. this._compilationError = "";
  22706. this._valueCache = {};
  22707. this.name = baseName;
  22708. if (attributesNamesOrOptions.attributes) {
  22709. var options = attributesNamesOrOptions;
  22710. this._engine = uniformsNamesOrEngine;
  22711. this._attributesNames = options.attributes;
  22712. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22713. this._samplers = options.samplers;
  22714. this.defines = options.defines;
  22715. this.onError = options.onError;
  22716. this.onCompiled = options.onCompiled;
  22717. this._fallbacks = options.fallbacks;
  22718. this._indexParameters = options.indexParameters;
  22719. if (options.uniformBuffersNames) {
  22720. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22721. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22722. }
  22723. }
  22724. }
  22725. else {
  22726. this._engine = engine;
  22727. this.defines = defines;
  22728. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22729. this._samplers = samplers;
  22730. this._attributesNames = attributesNamesOrOptions;
  22731. this.onError = onError;
  22732. this.onCompiled = onCompiled;
  22733. this._indexParameters = indexParameters;
  22734. this._fallbacks = fallbacks;
  22735. }
  22736. this.uniqueId = Effect._uniqueIdSeed++;
  22737. var vertexSource;
  22738. var fragmentSource;
  22739. if (baseName.vertexElement) {
  22740. vertexSource = document.getElementById(baseName.vertexElement);
  22741. if (!vertexSource) {
  22742. vertexSource = baseName.vertexElement;
  22743. }
  22744. }
  22745. else {
  22746. vertexSource = baseName.vertex || baseName;
  22747. }
  22748. if (baseName.fragmentElement) {
  22749. fragmentSource = document.getElementById(baseName.fragmentElement);
  22750. if (!fragmentSource) {
  22751. fragmentSource = baseName.fragmentElement;
  22752. }
  22753. }
  22754. else {
  22755. fragmentSource = baseName.fragment || baseName;
  22756. }
  22757. this._loadVertexShader(vertexSource, function (vertexCode) {
  22758. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22759. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22760. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22761. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22762. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22763. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22764. });
  22765. });
  22766. });
  22767. });
  22768. });
  22769. });
  22770. }
  22771. Object.defineProperty(Effect.prototype, "key", {
  22772. get: function () {
  22773. return this._key;
  22774. },
  22775. enumerable: true,
  22776. configurable: true
  22777. });
  22778. // Properties
  22779. Effect.prototype.isReady = function () {
  22780. return this._isReady;
  22781. };
  22782. Effect.prototype.getEngine = function () {
  22783. return this._engine;
  22784. };
  22785. Effect.prototype.getProgram = function () {
  22786. return this._program;
  22787. };
  22788. Effect.prototype.getAttributesNames = function () {
  22789. return this._attributesNames;
  22790. };
  22791. Effect.prototype.getAttributeLocation = function (index) {
  22792. return this._attributes[index];
  22793. };
  22794. Effect.prototype.getAttributeLocationByName = function (name) {
  22795. var index = this._attributesNames.indexOf(name);
  22796. return this._attributes[index];
  22797. };
  22798. Effect.prototype.getAttributesCount = function () {
  22799. return this._attributes.length;
  22800. };
  22801. Effect.prototype.getUniformIndex = function (uniformName) {
  22802. return this._uniformsNames.indexOf(uniformName);
  22803. };
  22804. Effect.prototype.getUniform = function (uniformName) {
  22805. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22806. };
  22807. Effect.prototype.getSamplers = function () {
  22808. return this._samplers;
  22809. };
  22810. Effect.prototype.getCompilationError = function () {
  22811. return this._compilationError;
  22812. };
  22813. Effect.prototype.getVertexShaderSource = function () {
  22814. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22815. };
  22816. Effect.prototype.getFragmentShaderSource = function () {
  22817. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22818. };
  22819. // Methods
  22820. Effect.prototype.executeWhenCompiled = function (func) {
  22821. var _this = this;
  22822. if (this.isReady()) {
  22823. func(this);
  22824. return;
  22825. }
  22826. var observer = this.onCompileObservable.add(function (effect) {
  22827. _this.onCompileObservable.remove(observer);
  22828. func(effect);
  22829. });
  22830. };
  22831. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22832. // DOM element ?
  22833. if (vertex instanceof HTMLElement) {
  22834. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22835. callback(vertexCode);
  22836. return;
  22837. }
  22838. // Base64 encoded ?
  22839. if (vertex.substr(0, 7) === "base64:") {
  22840. var vertexBinary = window.atob(vertex.substr(7));
  22841. callback(vertexBinary);
  22842. return;
  22843. }
  22844. // Is in local store ?
  22845. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22846. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22847. return;
  22848. }
  22849. var vertexShaderUrl;
  22850. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22851. vertexShaderUrl = vertex;
  22852. }
  22853. else {
  22854. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22855. }
  22856. // Vertex shader
  22857. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22858. };
  22859. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22860. // DOM element ?
  22861. if (fragment instanceof HTMLElement) {
  22862. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22863. callback(fragmentCode);
  22864. return;
  22865. }
  22866. // Base64 encoded ?
  22867. if (fragment.substr(0, 7) === "base64:") {
  22868. var fragmentBinary = window.atob(fragment.substr(7));
  22869. callback(fragmentBinary);
  22870. return;
  22871. }
  22872. // Is in local store ?
  22873. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22874. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22875. return;
  22876. }
  22877. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22878. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22879. return;
  22880. }
  22881. var fragmentShaderUrl;
  22882. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22883. fragmentShaderUrl = fragment;
  22884. }
  22885. else {
  22886. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22887. }
  22888. // Fragment shader
  22889. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22890. };
  22891. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22892. // Rebuild shaders source code
  22893. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22894. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22895. vertexCode = prefix + vertexCode;
  22896. fragmentCode = prefix + fragmentCode;
  22897. // Number lines of shaders source code
  22898. var i = 2;
  22899. var regex = /\n/gm;
  22900. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22901. i = 2;
  22902. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22903. // Dump shaders name and formatted source code
  22904. if (this.name.vertexElement) {
  22905. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22906. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22907. }
  22908. else if (this.name.vertex) {
  22909. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22910. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22911. }
  22912. else {
  22913. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22914. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22915. }
  22916. };
  22917. ;
  22918. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22919. var preparedSourceCode = this._processPrecision(sourceCode);
  22920. if (this._engine.webGLVersion == 1) {
  22921. callback(preparedSourceCode);
  22922. return;
  22923. }
  22924. // Already converted
  22925. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22926. callback(preparedSourceCode.replace("#version 300 es", ""));
  22927. return;
  22928. }
  22929. // Remove extensions
  22930. // #extension GL_OES_standard_derivatives : enable
  22931. // #extension GL_EXT_shader_texture_lod : enable
  22932. // #extension GL_EXT_frag_depth : enable
  22933. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22934. var result = preparedSourceCode.replace(regex, "");
  22935. // Migrate to GLSL v300
  22936. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22937. result = result.replace(/attribute[ \t]/g, "in ");
  22938. result = result.replace(/[ \t]attribute/g, " in");
  22939. if (isFragment) {
  22940. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22941. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22942. result = result.replace(/texture2D\(/g, "texture(");
  22943. result = result.replace(/textureCube\(/g, "texture(");
  22944. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22945. result = result.replace(/gl_FragColor/g, "glFragColor");
  22946. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22947. }
  22948. callback(result);
  22949. };
  22950. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22951. var _this = this;
  22952. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22953. var match = regex.exec(sourceCode);
  22954. var returnValue = new String(sourceCode);
  22955. while (match != null) {
  22956. var includeFile = match[1];
  22957. // Uniform declaration
  22958. if (includeFile.indexOf("__decl__") !== -1) {
  22959. includeFile = includeFile.replace(/__decl__/, "");
  22960. if (this._engine.webGLVersion != 1) {
  22961. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22962. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22963. }
  22964. includeFile = includeFile + "Declaration";
  22965. }
  22966. if (Effect.IncludesShadersStore[includeFile]) {
  22967. // Substitution
  22968. var includeContent = Effect.IncludesShadersStore[includeFile];
  22969. if (match[2]) {
  22970. var splits = match[3].split(",");
  22971. for (var index = 0; index < splits.length; index += 2) {
  22972. var source = new RegExp(splits[index], "g");
  22973. var dest = splits[index + 1];
  22974. includeContent = includeContent.replace(source, dest);
  22975. }
  22976. }
  22977. if (match[4]) {
  22978. var indexString = match[5];
  22979. if (indexString.indexOf("..") !== -1) {
  22980. var indexSplits = indexString.split("..");
  22981. var minIndex = parseInt(indexSplits[0]);
  22982. var maxIndex = parseInt(indexSplits[1]);
  22983. var sourceIncludeContent = includeContent.slice(0);
  22984. includeContent = "";
  22985. if (isNaN(maxIndex)) {
  22986. maxIndex = this._indexParameters[indexSplits[1]];
  22987. }
  22988. for (var i = minIndex; i < maxIndex; i++) {
  22989. if (this._engine.webGLVersion === 1) {
  22990. // Ubo replacement
  22991. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22992. return p1 + "{X}";
  22993. });
  22994. }
  22995. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22996. }
  22997. }
  22998. else {
  22999. if (this._engine.webGLVersion === 1) {
  23000. // Ubo replacement
  23001. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23002. return p1 + "{X}";
  23003. });
  23004. }
  23005. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23006. }
  23007. }
  23008. // Replace
  23009. returnValue = returnValue.replace(match[0], includeContent);
  23010. }
  23011. else {
  23012. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23013. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23014. Effect.IncludesShadersStore[includeFile] = fileContent;
  23015. _this._processIncludes(returnValue, callback);
  23016. });
  23017. return;
  23018. }
  23019. match = regex.exec(sourceCode);
  23020. }
  23021. callback(returnValue);
  23022. };
  23023. Effect.prototype._processPrecision = function (source) {
  23024. if (source.indexOf("precision highp float") === -1) {
  23025. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23026. source = "precision mediump float;\n" + source;
  23027. }
  23028. else {
  23029. source = "precision highp float;\n" + source;
  23030. }
  23031. }
  23032. else {
  23033. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23034. source = source.replace("precision highp float", "precision mediump float");
  23035. }
  23036. }
  23037. return source;
  23038. };
  23039. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23040. try {
  23041. var engine = this._engine;
  23042. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23043. if (engine.webGLVersion > 1) {
  23044. for (var name in this._uniformBuffersNames) {
  23045. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  23046. }
  23047. }
  23048. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23049. this._attributes = engine.getAttributes(this._program, attributesNames);
  23050. var index;
  23051. for (index = 0; index < this._samplers.length; index++) {
  23052. var sampler = this.getUniform(this._samplers[index]);
  23053. if (sampler == null) {
  23054. this._samplers.splice(index, 1);
  23055. index--;
  23056. }
  23057. }
  23058. engine.bindSamplers(this);
  23059. this._compilationError = "";
  23060. this._isReady = true;
  23061. if (this.onCompiled) {
  23062. this.onCompiled(this);
  23063. }
  23064. this.onCompileObservable.notifyObservers(this);
  23065. }
  23066. catch (e) {
  23067. this._compilationError = e.message;
  23068. // Let's go through fallbacks then
  23069. BABYLON.Tools.Error("Unable to compile effect:");
  23070. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23071. return " " + uniform;
  23072. }));
  23073. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23074. return " " + attribute;
  23075. }));
  23076. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23077. BABYLON.Tools.Error("Error: " + this._compilationError);
  23078. if (fallbacks && fallbacks.isMoreFallbacks) {
  23079. BABYLON.Tools.Error("Trying next fallback.");
  23080. defines = fallbacks.reduce(defines);
  23081. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23082. }
  23083. else {
  23084. if (this.onError) {
  23085. this.onError(this, this._compilationError);
  23086. }
  23087. this.onErrorObservable.notifyObservers(this);
  23088. }
  23089. }
  23090. };
  23091. Object.defineProperty(Effect.prototype, "isSupported", {
  23092. get: function () {
  23093. return this._compilationError === "";
  23094. },
  23095. enumerable: true,
  23096. configurable: true
  23097. });
  23098. Effect.prototype._bindTexture = function (channel, texture) {
  23099. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23100. };
  23101. Effect.prototype.setTexture = function (channel, texture) {
  23102. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23103. };
  23104. Effect.prototype.setTextureArray = function (channel, textures) {
  23105. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23106. var initialPos = this._samplers.indexOf(channel);
  23107. for (var index = 1; index < textures.length; index++) {
  23108. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23109. }
  23110. }
  23111. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23112. };
  23113. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23114. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23115. };
  23116. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23117. var cache = this._valueCache[uniformName];
  23118. var flag = matrix.updateFlag;
  23119. if (cache !== undefined && cache === flag) {
  23120. return false;
  23121. }
  23122. this._valueCache[uniformName] = flag;
  23123. return true;
  23124. };
  23125. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23126. var cache = this._valueCache[uniformName];
  23127. if (!cache) {
  23128. cache = [x, y];
  23129. this._valueCache[uniformName] = cache;
  23130. return true;
  23131. }
  23132. var changed = false;
  23133. if (cache[0] !== x) {
  23134. cache[0] = x;
  23135. changed = true;
  23136. }
  23137. if (cache[1] !== y) {
  23138. cache[1] = y;
  23139. changed = true;
  23140. }
  23141. return changed;
  23142. };
  23143. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23144. var cache = this._valueCache[uniformName];
  23145. if (!cache) {
  23146. cache = [x, y, z];
  23147. this._valueCache[uniformName] = cache;
  23148. return true;
  23149. }
  23150. var changed = false;
  23151. if (cache[0] !== x) {
  23152. cache[0] = x;
  23153. changed = true;
  23154. }
  23155. if (cache[1] !== y) {
  23156. cache[1] = y;
  23157. changed = true;
  23158. }
  23159. if (cache[2] !== z) {
  23160. cache[2] = z;
  23161. changed = true;
  23162. }
  23163. return changed;
  23164. };
  23165. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23166. var cache = this._valueCache[uniformName];
  23167. if (!cache) {
  23168. cache = [x, y, z, w];
  23169. this._valueCache[uniformName] = cache;
  23170. return true;
  23171. }
  23172. var changed = false;
  23173. if (cache[0] !== x) {
  23174. cache[0] = x;
  23175. changed = true;
  23176. }
  23177. if (cache[1] !== y) {
  23178. cache[1] = y;
  23179. changed = true;
  23180. }
  23181. if (cache[2] !== z) {
  23182. cache[2] = z;
  23183. changed = true;
  23184. }
  23185. if (cache[3] !== w) {
  23186. cache[3] = w;
  23187. changed = true;
  23188. }
  23189. return changed;
  23190. };
  23191. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23192. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23193. return;
  23194. }
  23195. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23196. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23197. };
  23198. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23199. this._engine.bindUniformBlock(this._program, blockName, index);
  23200. };
  23201. Effect.prototype.setIntArray = function (uniformName, array) {
  23202. this._valueCache[uniformName] = null;
  23203. this._engine.setIntArray(this.getUniform(uniformName), array);
  23204. return this;
  23205. };
  23206. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23207. this._valueCache[uniformName] = null;
  23208. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23209. return this;
  23210. };
  23211. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23212. this._valueCache[uniformName] = null;
  23213. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23214. return this;
  23215. };
  23216. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23217. this._valueCache[uniformName] = null;
  23218. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23219. return this;
  23220. };
  23221. Effect.prototype.setFloatArray = function (uniformName, array) {
  23222. this._valueCache[uniformName] = null;
  23223. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23224. return this;
  23225. };
  23226. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23227. this._valueCache[uniformName] = null;
  23228. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23229. return this;
  23230. };
  23231. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23232. this._valueCache[uniformName] = null;
  23233. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23234. return this;
  23235. };
  23236. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23237. this._valueCache[uniformName] = null;
  23238. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23239. return this;
  23240. };
  23241. Effect.prototype.setArray = function (uniformName, array) {
  23242. this._valueCache[uniformName] = null;
  23243. this._engine.setArray(this.getUniform(uniformName), array);
  23244. return this;
  23245. };
  23246. Effect.prototype.setArray2 = function (uniformName, array) {
  23247. this._valueCache[uniformName] = null;
  23248. this._engine.setArray2(this.getUniform(uniformName), array);
  23249. return this;
  23250. };
  23251. Effect.prototype.setArray3 = function (uniformName, array) {
  23252. this._valueCache[uniformName] = null;
  23253. this._engine.setArray3(this.getUniform(uniformName), array);
  23254. return this;
  23255. };
  23256. Effect.prototype.setArray4 = function (uniformName, array) {
  23257. this._valueCache[uniformName] = null;
  23258. this._engine.setArray4(this.getUniform(uniformName), array);
  23259. return this;
  23260. };
  23261. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23262. if (!matrices) {
  23263. return;
  23264. }
  23265. this._valueCache[uniformName] = null;
  23266. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23267. return this;
  23268. };
  23269. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23270. if (this._cacheMatrix(uniformName, matrix)) {
  23271. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23272. }
  23273. return this;
  23274. };
  23275. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23276. this._valueCache[uniformName] = null;
  23277. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23278. return this;
  23279. };
  23280. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23281. this._valueCache[uniformName] = null;
  23282. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23283. return this;
  23284. };
  23285. Effect.prototype.setFloat = function (uniformName, value) {
  23286. var cache = this._valueCache[uniformName];
  23287. if (cache !== undefined && cache === value)
  23288. return this;
  23289. this._valueCache[uniformName] = value;
  23290. this._engine.setFloat(this.getUniform(uniformName), value);
  23291. return this;
  23292. };
  23293. Effect.prototype.setBool = function (uniformName, bool) {
  23294. var cache = this._valueCache[uniformName];
  23295. if (cache !== undefined && cache === bool)
  23296. return this;
  23297. this._valueCache[uniformName] = bool;
  23298. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23299. return this;
  23300. };
  23301. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23302. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23303. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23304. }
  23305. return this;
  23306. };
  23307. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23308. if (this._cacheFloat2(uniformName, x, y)) {
  23309. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23310. }
  23311. return this;
  23312. };
  23313. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23314. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23315. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23316. }
  23317. return this;
  23318. };
  23319. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23320. if (this._cacheFloat3(uniformName, x, y, z)) {
  23321. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23322. }
  23323. return this;
  23324. };
  23325. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23326. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23327. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23328. }
  23329. return this;
  23330. };
  23331. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23332. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23333. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23334. }
  23335. return this;
  23336. };
  23337. Effect.prototype.setColor3 = function (uniformName, color3) {
  23338. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23339. this._engine.setColor3(this.getUniform(uniformName), color3);
  23340. }
  23341. return this;
  23342. };
  23343. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23344. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23345. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23346. }
  23347. return this;
  23348. };
  23349. Effect.prototype._recombineShader = function (node) {
  23350. if (node.define) {
  23351. if (node.condition) {
  23352. var defineIndex = this.defines.indexOf("#define " + node.define);
  23353. if (defineIndex === -1) {
  23354. return null;
  23355. }
  23356. var nextComma = this.defines.indexOf("\n", defineIndex);
  23357. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23358. var condition = defineValue + node.condition;
  23359. if (!eval(condition)) {
  23360. return null;
  23361. }
  23362. }
  23363. else if (node.ndef) {
  23364. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23365. return null;
  23366. }
  23367. }
  23368. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23369. return null;
  23370. }
  23371. }
  23372. var result = "";
  23373. for (var index = 0; index < node.children.length; index++) {
  23374. var line = node.children[index];
  23375. if (line.children) {
  23376. var combined = this._recombineShader(line);
  23377. if (combined !== null) {
  23378. result += combined + "\r\n";
  23379. }
  23380. continue;
  23381. }
  23382. if (line.length > 0) {
  23383. result += line + "\r\n";
  23384. }
  23385. }
  23386. return result;
  23387. };
  23388. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23389. var root = {
  23390. children: []
  23391. };
  23392. var currentNode = root;
  23393. var lines = shaderString.split("\n");
  23394. for (var index = 0; index < lines.length; index++) {
  23395. var line = lines[index].trim();
  23396. // #ifdef
  23397. var pos = line.indexOf("#ifdef ");
  23398. if (pos !== -1) {
  23399. var define = line.substr(pos + 7);
  23400. var newNode = {
  23401. condition: null,
  23402. ndef: false,
  23403. define: define,
  23404. children: [],
  23405. parent: currentNode
  23406. };
  23407. currentNode.children.push(newNode);
  23408. currentNode = newNode;
  23409. continue;
  23410. }
  23411. // #ifndef
  23412. var pos = line.indexOf("#ifndef ");
  23413. if (pos !== -1) {
  23414. var define = line.substr(pos + 8);
  23415. newNode = {
  23416. condition: null,
  23417. define: define,
  23418. ndef: true,
  23419. children: [],
  23420. parent: currentNode
  23421. };
  23422. currentNode.children.push(newNode);
  23423. currentNode = newNode;
  23424. continue;
  23425. }
  23426. // #if
  23427. var pos = line.indexOf("#if ");
  23428. if (pos !== -1) {
  23429. var define = line.substr(pos + 4).trim();
  23430. var conditionPos = define.indexOf(" ");
  23431. newNode = {
  23432. condition: define.substr(conditionPos + 1),
  23433. define: define.substr(0, conditionPos),
  23434. ndef: false,
  23435. children: [],
  23436. parent: currentNode
  23437. };
  23438. currentNode.children.push(newNode);
  23439. currentNode = newNode;
  23440. continue;
  23441. }
  23442. // #endif
  23443. pos = line.indexOf("#endif");
  23444. if (pos !== -1) {
  23445. currentNode = currentNode.parent;
  23446. continue;
  23447. }
  23448. currentNode.children.push(line);
  23449. }
  23450. // Recombine
  23451. return this._recombineShader(root);
  23452. };
  23453. return Effect;
  23454. }());
  23455. Effect._uniqueIdSeed = 0;
  23456. Effect._baseCache = {};
  23457. // Statics
  23458. Effect.ShadersStore = {};
  23459. Effect.IncludesShadersStore = {};
  23460. BABYLON.Effect = Effect;
  23461. })(BABYLON || (BABYLON = {}));
  23462. //# sourceMappingURL=babylon.effect.js.map
  23463. var BABYLON;
  23464. (function (BABYLON) {
  23465. var MaterialHelper = (function () {
  23466. function MaterialHelper() {
  23467. }
  23468. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23469. if (defines._areMiscDirty) {
  23470. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23471. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23472. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23473. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23474. }
  23475. };
  23476. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23477. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23478. var changed = false;
  23479. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23480. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23481. changed = true;
  23482. }
  23483. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23484. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23485. changed = true;
  23486. }
  23487. if (defines["INSTANCES"] !== useInstances) {
  23488. defines["INSTANCES"] = useInstances;
  23489. changed = true;
  23490. }
  23491. if (changed) {
  23492. defines.markAsUnprocessed();
  23493. }
  23494. };
  23495. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23496. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23497. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23498. return false;
  23499. }
  23500. defines._normals = defines._needNormals;
  23501. defines._uvs = defines._needUVs;
  23502. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23503. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23504. defines["TANGENT"] = true;
  23505. }
  23506. if (defines._needUVs) {
  23507. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23508. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23509. }
  23510. else {
  23511. defines["UV1"] = false;
  23512. defines["UV2"] = false;
  23513. }
  23514. if (useVertexColor) {
  23515. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23516. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23517. }
  23518. if (useBones) {
  23519. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23520. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23521. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23522. }
  23523. else {
  23524. defines["NUM_BONE_INFLUENCERS"] = 0;
  23525. defines["BonesPerMesh"] = 0;
  23526. }
  23527. }
  23528. if (useMorphTargets) {
  23529. if (mesh.morphTargetManager) {
  23530. var manager = mesh.morphTargetManager;
  23531. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23532. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23533. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23534. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23535. }
  23536. else {
  23537. defines["MORPHTARGETS_TANGENT"] = false;
  23538. defines["MORPHTARGETS_NORMAL"] = false;
  23539. defines["MORPHTARGETS"] = false;
  23540. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23541. }
  23542. }
  23543. return true;
  23544. };
  23545. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23546. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23547. if (disableLighting === void 0) { disableLighting = false; }
  23548. if (!defines._areLightsDirty) {
  23549. return defines._needNormals;
  23550. }
  23551. var lightIndex = 0;
  23552. var needNormals = false;
  23553. var needRebuild = false;
  23554. var lightmapMode = false;
  23555. var shadowEnabled = false;
  23556. var specularEnabled = false;
  23557. if (scene.lightsEnabled && !disableLighting) {
  23558. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23559. var light = _a[_i];
  23560. needNormals = true;
  23561. if (defines["LIGHT" + lightIndex] === undefined) {
  23562. needRebuild = true;
  23563. }
  23564. defines["LIGHT" + lightIndex] = true;
  23565. defines["SPOTLIGHT" + lightIndex] = false;
  23566. defines["HEMILIGHT" + lightIndex] = false;
  23567. defines["POINTLIGHT" + lightIndex] = false;
  23568. defines["DIRLIGHT" + lightIndex] = false;
  23569. var type;
  23570. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23571. type = "SPOTLIGHT" + lightIndex;
  23572. }
  23573. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23574. type = "HEMILIGHT" + lightIndex;
  23575. }
  23576. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23577. type = "POINTLIGHT" + lightIndex;
  23578. }
  23579. else {
  23580. type = "DIRLIGHT" + lightIndex;
  23581. }
  23582. defines[type] = true;
  23583. // Specular
  23584. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23585. specularEnabled = true;
  23586. }
  23587. // Shadows
  23588. defines["SHADOW" + lightIndex] = false;
  23589. defines["SHADOWPCF" + lightIndex] = false;
  23590. defines["SHADOWESM" + lightIndex] = false;
  23591. defines["SHADOWCUBE" + lightIndex] = false;
  23592. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23593. var shadowGenerator = light.getShadowGenerator();
  23594. if (shadowGenerator) {
  23595. shadowEnabled = true;
  23596. shadowGenerator.prepareDefines(defines, lightIndex);
  23597. }
  23598. }
  23599. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23600. lightmapMode = true;
  23601. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23602. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23603. }
  23604. else {
  23605. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23606. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23607. }
  23608. lightIndex++;
  23609. if (lightIndex === maxSimultaneousLights)
  23610. break;
  23611. }
  23612. }
  23613. defines["SPECULARTERM"] = specularEnabled;
  23614. defines["SHADOWS"] = shadowEnabled;
  23615. // Resetting all other lights if any
  23616. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23617. if (defines["LIGHT" + index] !== undefined) {
  23618. defines["LIGHT" + index] = false;
  23619. defines["HEMILIGHT" + lightIndex] = false;
  23620. defines["POINTLIGHT" + lightIndex] = false;
  23621. defines["DIRLIGHT" + lightIndex] = false;
  23622. defines["SPOTLIGHT" + lightIndex] = false;
  23623. defines["SHADOW" + lightIndex] = false;
  23624. }
  23625. }
  23626. var caps = scene.getEngine().getCaps();
  23627. if (defines["SHADOWFLOAT"] === undefined) {
  23628. needRebuild = true;
  23629. }
  23630. defines["SHADOWFLOAT"] = shadowEnabled &&
  23631. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23632. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23633. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23634. if (needRebuild) {
  23635. defines.rebuild();
  23636. }
  23637. return needNormals;
  23638. };
  23639. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23640. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23641. var uniformsList, uniformBuffersList, samplersList, defines;
  23642. if (uniformsListOrOptions.uniformsNames) {
  23643. var options = uniformsListOrOptions;
  23644. uniformsList = options.uniformsNames;
  23645. uniformBuffersList = options.uniformBuffersNames;
  23646. samplersList = options.samplers;
  23647. defines = options.defines;
  23648. maxSimultaneousLights = options.maxSimultaneousLights;
  23649. }
  23650. else {
  23651. uniformsList = uniformsListOrOptions;
  23652. }
  23653. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23654. if (!defines["LIGHT" + lightIndex]) {
  23655. break;
  23656. }
  23657. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  23658. if (uniformBuffersList) {
  23659. uniformBuffersList.push("Light" + lightIndex);
  23660. }
  23661. samplersList.push("shadowSampler" + lightIndex);
  23662. }
  23663. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23664. uniformsList.push("morphTargetInfluences");
  23665. }
  23666. };
  23667. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23668. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23669. if (!defines["SHADOWS"]) {
  23670. return;
  23671. }
  23672. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23673. if (!defines["LIGHT" + lightIndex]) {
  23674. break;
  23675. }
  23676. if (lightIndex > 0) {
  23677. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23678. }
  23679. if (defines["SHADOW" + lightIndex]) {
  23680. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23681. }
  23682. if (defines["SHADOWPCF" + lightIndex]) {
  23683. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23684. }
  23685. if (defines["SHADOWESM" + lightIndex]) {
  23686. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23687. }
  23688. }
  23689. };
  23690. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23691. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23692. if (influencers > 0) {
  23693. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23694. var manager = mesh.morphTargetManager;
  23695. var normal = manager.supportsNormals && defines["NORMAL"];
  23696. var tangent = manager.supportsTangents && defines["TANGENT"];
  23697. for (var index = 0; index < influencers; index++) {
  23698. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23699. if (normal) {
  23700. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23701. }
  23702. if (tangent) {
  23703. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23704. }
  23705. if (attribs.length > maxAttributesCount) {
  23706. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23707. }
  23708. }
  23709. }
  23710. };
  23711. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23712. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23713. fallbacks.addCPUSkinningFallback(0, mesh);
  23714. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23715. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23716. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23717. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23718. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23719. }
  23720. }
  23721. };
  23722. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23723. if (defines["INSTANCES"]) {
  23724. attribs.push("world0");
  23725. attribs.push("world1");
  23726. attribs.push("world2");
  23727. attribs.push("world3");
  23728. }
  23729. };
  23730. // Bindings
  23731. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  23732. if (light.shadowEnabled && mesh.receiveShadows) {
  23733. var shadowGenerator = light.getShadowGenerator();
  23734. if (shadowGenerator) {
  23735. shadowGenerator.bindShadowLight(lightIndex, effect);
  23736. }
  23737. }
  23738. };
  23739. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23740. light.transferToEffect(effect, lightIndex + "");
  23741. };
  23742. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  23743. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23744. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  23745. var lightIndex = 0;
  23746. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23747. var light = _a[_i];
  23748. var scaledIntensity = light.getScaledIntensity();
  23749. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23750. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23751. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  23752. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  23753. if (defines["SPECULARTERM"]) {
  23754. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  23755. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23756. }
  23757. // Shadows
  23758. if (scene.shadowsEnabled) {
  23759. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  23760. }
  23761. light._uniformBuffer.update();
  23762. lightIndex++;
  23763. if (lightIndex === maxSimultaneousLights)
  23764. break;
  23765. }
  23766. };
  23767. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23768. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23769. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23770. effect.setColor3("vFogColor", scene.fogColor);
  23771. }
  23772. };
  23773. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23774. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23775. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23776. if (matrices) {
  23777. effect.setMatrices("mBones", matrices);
  23778. }
  23779. }
  23780. };
  23781. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23782. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23783. return;
  23784. }
  23785. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23786. };
  23787. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23788. if (defines["LOGARITHMICDEPTH"]) {
  23789. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23790. }
  23791. };
  23792. MaterialHelper.BindClipPlane = function (effect, scene) {
  23793. if (scene.clipPlane) {
  23794. var clipPlane = scene.clipPlane;
  23795. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23796. }
  23797. };
  23798. return MaterialHelper;
  23799. }());
  23800. BABYLON.MaterialHelper = MaterialHelper;
  23801. })(BABYLON || (BABYLON = {}));
  23802. //# sourceMappingURL=babylon.materialHelper.js.map
  23803. var BABYLON;
  23804. (function (BABYLON) {
  23805. var MaterialDefines = (function () {
  23806. function MaterialDefines() {
  23807. this._isDirty = true;
  23808. this._areLightsDirty = true;
  23809. this._areAttributesDirty = true;
  23810. this._areTexturesDirty = true;
  23811. this._areFresnelDirty = true;
  23812. this._areMiscDirty = true;
  23813. this._areImageProcessingDirty = true;
  23814. this._normals = false;
  23815. this._uvs = false;
  23816. this._needNormals = false;
  23817. this._needUVs = false;
  23818. }
  23819. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23820. get: function () {
  23821. return this._isDirty;
  23822. },
  23823. enumerable: true,
  23824. configurable: true
  23825. });
  23826. MaterialDefines.prototype.markAsProcessed = function () {
  23827. this._isDirty = false;
  23828. this._areAttributesDirty = false;
  23829. this._areTexturesDirty = false;
  23830. this._areFresnelDirty = false;
  23831. this._areLightsDirty = false;
  23832. this._areMiscDirty = false;
  23833. this._areImageProcessingDirty = false;
  23834. };
  23835. MaterialDefines.prototype.markAsUnprocessed = function () {
  23836. this._isDirty = true;
  23837. };
  23838. MaterialDefines.prototype.markAllAsDirty = function () {
  23839. this._areTexturesDirty = true;
  23840. this._areAttributesDirty = true;
  23841. this._areLightsDirty = true;
  23842. this._areFresnelDirty = true;
  23843. this._areMiscDirty = true;
  23844. this._areImageProcessingDirty = true;
  23845. this._isDirty = true;
  23846. };
  23847. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  23848. this._areImageProcessingDirty = true;
  23849. this._isDirty = true;
  23850. };
  23851. MaterialDefines.prototype.markAsLightDirty = function () {
  23852. this._areLightsDirty = true;
  23853. this._isDirty = true;
  23854. };
  23855. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23856. this._areAttributesDirty = true;
  23857. this._isDirty = true;
  23858. };
  23859. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23860. this._areTexturesDirty = true;
  23861. this._isDirty = true;
  23862. };
  23863. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23864. this._areFresnelDirty = true;
  23865. this._isDirty = true;
  23866. };
  23867. MaterialDefines.prototype.markAsMiscDirty = function () {
  23868. this._areMiscDirty = true;
  23869. this._isDirty = true;
  23870. };
  23871. MaterialDefines.prototype.rebuild = function () {
  23872. if (this._keys) {
  23873. delete this._keys;
  23874. }
  23875. this._keys = [];
  23876. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23877. var key = _a[_i];
  23878. if (key[0] === "_") {
  23879. continue;
  23880. }
  23881. this._keys.push(key);
  23882. }
  23883. };
  23884. MaterialDefines.prototype.isEqual = function (other) {
  23885. if (this._keys.length !== other._keys.length) {
  23886. return false;
  23887. }
  23888. for (var index = 0; index < this._keys.length; index++) {
  23889. var prop = this._keys[index];
  23890. if (this[prop] !== other[prop]) {
  23891. return false;
  23892. }
  23893. }
  23894. return true;
  23895. };
  23896. MaterialDefines.prototype.cloneTo = function (other) {
  23897. if (this._keys.length !== other._keys.length) {
  23898. other._keys = this._keys.slice(0);
  23899. }
  23900. for (var index = 0; index < this._keys.length; index++) {
  23901. var prop = this._keys[index];
  23902. other[prop] = this[prop];
  23903. }
  23904. };
  23905. MaterialDefines.prototype.reset = function () {
  23906. for (var index = 0; index < this._keys.length; index++) {
  23907. var prop = this._keys[index];
  23908. if (typeof (this[prop]) === "number") {
  23909. this[prop] = 0;
  23910. }
  23911. else {
  23912. this[prop] = false;
  23913. }
  23914. }
  23915. };
  23916. MaterialDefines.prototype.toString = function () {
  23917. var result = "";
  23918. for (var index = 0; index < this._keys.length; index++) {
  23919. var prop = this._keys[index];
  23920. var value = this[prop];
  23921. if (typeof (value) === "number") {
  23922. result += "#define " + prop + " " + this[prop] + "\n";
  23923. }
  23924. else if (value) {
  23925. result += "#define " + prop + "\n";
  23926. }
  23927. }
  23928. return result;
  23929. };
  23930. return MaterialDefines;
  23931. }());
  23932. BABYLON.MaterialDefines = MaterialDefines;
  23933. var Material = (function () {
  23934. function Material(name, scene, doNotAdd) {
  23935. this.checkReadyOnEveryCall = false;
  23936. this.checkReadyOnlyOnce = false;
  23937. this.state = "";
  23938. this.alpha = 1.0;
  23939. this._backFaceCulling = true;
  23940. this.doNotSerialize = false;
  23941. this.storeEffectOnSubMeshes = false;
  23942. /**
  23943. * An event triggered when the material is disposed.
  23944. * @type {BABYLON.Observable}
  23945. */
  23946. this.onDisposeObservable = new BABYLON.Observable();
  23947. /**
  23948. * An event triggered when the material is bound.
  23949. * @type {BABYLON.Observable}
  23950. */
  23951. this.onBindObservable = new BABYLON.Observable();
  23952. /**
  23953. * An event triggered when the material is unbound.
  23954. * @type {BABYLON.Observable}
  23955. */
  23956. this.onUnBindObservable = new BABYLON.Observable();
  23957. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23958. this.disableDepthWrite = false;
  23959. this._fogEnabled = true;
  23960. this.pointSize = 1.0;
  23961. this.zOffset = 0;
  23962. this._wasPreviouslyReady = false;
  23963. this._fillMode = Material.TriangleFillMode;
  23964. this.name = name;
  23965. this.id = name;
  23966. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23967. if (this._scene.useRightHandedSystem) {
  23968. this.sideOrientation = Material.ClockWiseSideOrientation;
  23969. }
  23970. else {
  23971. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23972. }
  23973. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23974. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23975. if (!doNotAdd) {
  23976. this._scene.materials.push(this);
  23977. }
  23978. }
  23979. Object.defineProperty(Material, "TriangleFillMode", {
  23980. get: function () {
  23981. return Material._TriangleFillMode;
  23982. },
  23983. enumerable: true,
  23984. configurable: true
  23985. });
  23986. Object.defineProperty(Material, "WireFrameFillMode", {
  23987. get: function () {
  23988. return Material._WireFrameFillMode;
  23989. },
  23990. enumerable: true,
  23991. configurable: true
  23992. });
  23993. Object.defineProperty(Material, "PointFillMode", {
  23994. get: function () {
  23995. return Material._PointFillMode;
  23996. },
  23997. enumerable: true,
  23998. configurable: true
  23999. });
  24000. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24001. get: function () {
  24002. return Material._ClockWiseSideOrientation;
  24003. },
  24004. enumerable: true,
  24005. configurable: true
  24006. });
  24007. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24008. get: function () {
  24009. return Material._CounterClockWiseSideOrientation;
  24010. },
  24011. enumerable: true,
  24012. configurable: true
  24013. });
  24014. Object.defineProperty(Material, "TextureDirtyFlag", {
  24015. get: function () {
  24016. return Material._TextureDirtyFlag;
  24017. },
  24018. enumerable: true,
  24019. configurable: true
  24020. });
  24021. Object.defineProperty(Material, "LightDirtyFlag", {
  24022. get: function () {
  24023. return Material._LightDirtyFlag;
  24024. },
  24025. enumerable: true,
  24026. configurable: true
  24027. });
  24028. Object.defineProperty(Material, "FresnelDirtyFlag", {
  24029. get: function () {
  24030. return Material._FresnelDirtyFlag;
  24031. },
  24032. enumerable: true,
  24033. configurable: true
  24034. });
  24035. Object.defineProperty(Material, "AttributesDirtyFlag", {
  24036. get: function () {
  24037. return Material._AttributesDirtyFlag;
  24038. },
  24039. enumerable: true,
  24040. configurable: true
  24041. });
  24042. Object.defineProperty(Material, "MiscDirtyFlag", {
  24043. get: function () {
  24044. return Material._MiscDirtyFlag;
  24045. },
  24046. enumerable: true,
  24047. configurable: true
  24048. });
  24049. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24050. get: function () {
  24051. return this._backFaceCulling;
  24052. },
  24053. set: function (value) {
  24054. if (this._backFaceCulling === value) {
  24055. return;
  24056. }
  24057. this._backFaceCulling = value;
  24058. this.markAsDirty(Material.TextureDirtyFlag);
  24059. },
  24060. enumerable: true,
  24061. configurable: true
  24062. });
  24063. Object.defineProperty(Material.prototype, "onDispose", {
  24064. set: function (callback) {
  24065. if (this._onDisposeObserver) {
  24066. this.onDisposeObservable.remove(this._onDisposeObserver);
  24067. }
  24068. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24069. },
  24070. enumerable: true,
  24071. configurable: true
  24072. });
  24073. Object.defineProperty(Material.prototype, "onBind", {
  24074. set: function (callback) {
  24075. if (this._onBindObserver) {
  24076. this.onBindObservable.remove(this._onBindObserver);
  24077. }
  24078. this._onBindObserver = this.onBindObservable.add(callback);
  24079. },
  24080. enumerable: true,
  24081. configurable: true
  24082. });
  24083. Object.defineProperty(Material.prototype, "fogEnabled", {
  24084. get: function () {
  24085. return this._fogEnabled;
  24086. },
  24087. set: function (value) {
  24088. if (this._fogEnabled === value) {
  24089. return;
  24090. }
  24091. this._fogEnabled = value;
  24092. this.markAsDirty(Material.MiscDirtyFlag);
  24093. },
  24094. enumerable: true,
  24095. configurable: true
  24096. });
  24097. Object.defineProperty(Material.prototype, "wireframe", {
  24098. get: function () {
  24099. return this._fillMode === Material.WireFrameFillMode;
  24100. },
  24101. set: function (value) {
  24102. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24103. },
  24104. enumerable: true,
  24105. configurable: true
  24106. });
  24107. Object.defineProperty(Material.prototype, "pointsCloud", {
  24108. get: function () {
  24109. return this._fillMode === Material.PointFillMode;
  24110. },
  24111. set: function (value) {
  24112. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24113. },
  24114. enumerable: true,
  24115. configurable: true
  24116. });
  24117. Object.defineProperty(Material.prototype, "fillMode", {
  24118. get: function () {
  24119. return this._fillMode;
  24120. },
  24121. set: function (value) {
  24122. if (this._fillMode === value) {
  24123. return;
  24124. }
  24125. this._fillMode = value;
  24126. this.markAsDirty(Material.MiscDirtyFlag);
  24127. },
  24128. enumerable: true,
  24129. configurable: true
  24130. });
  24131. /**
  24132. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24133. * subclasses should override adding information pertainent to themselves
  24134. */
  24135. Material.prototype.toString = function (fullDetails) {
  24136. var ret = "Name: " + this.name;
  24137. if (fullDetails) {
  24138. }
  24139. return ret;
  24140. };
  24141. /**
  24142. * Child classes can use it to update shaders
  24143. */
  24144. Material.prototype.getClassName = function () {
  24145. return "Material";
  24146. };
  24147. Object.defineProperty(Material.prototype, "isFrozen", {
  24148. get: function () {
  24149. return this.checkReadyOnlyOnce;
  24150. },
  24151. enumerable: true,
  24152. configurable: true
  24153. });
  24154. Material.prototype.freeze = function () {
  24155. this.checkReadyOnlyOnce = true;
  24156. };
  24157. Material.prototype.unfreeze = function () {
  24158. this.checkReadyOnlyOnce = false;
  24159. };
  24160. Material.prototype.isReady = function (mesh, useInstances) {
  24161. return true;
  24162. };
  24163. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24164. return false;
  24165. };
  24166. Material.prototype.getEffect = function () {
  24167. return this._effect;
  24168. };
  24169. Material.prototype.getScene = function () {
  24170. return this._scene;
  24171. };
  24172. Material.prototype.needAlphaBlending = function () {
  24173. return (this.alpha < 1.0);
  24174. };
  24175. Material.prototype.needAlphaTesting = function () {
  24176. return false;
  24177. };
  24178. Material.prototype.getAlphaTestTexture = function () {
  24179. return null;
  24180. };
  24181. Material.prototype.markDirty = function () {
  24182. this._wasPreviouslyReady = false;
  24183. };
  24184. Material.prototype._preBind = function (effect) {
  24185. var engine = this._scene.getEngine();
  24186. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24187. engine.enableEffect(effect ? effect : this._effect);
  24188. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24189. };
  24190. Material.prototype.bind = function (world, mesh) {
  24191. };
  24192. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  24193. };
  24194. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24195. };
  24196. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  24197. sceneUbo.bindToEffect(effect, "Scene");
  24198. };
  24199. Material.prototype.bindView = function (effect) {
  24200. if (!this._useUBO) {
  24201. effect.setMatrix("view", this.getScene().getViewMatrix());
  24202. }
  24203. else {
  24204. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24205. }
  24206. };
  24207. Material.prototype.bindViewProjection = function (effect) {
  24208. if (!this._useUBO) {
  24209. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24210. }
  24211. else {
  24212. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24213. }
  24214. };
  24215. Material.prototype._afterBind = function (mesh) {
  24216. this._scene._cachedMaterial = this;
  24217. this.onBindObservable.notifyObservers(mesh);
  24218. if (this.disableDepthWrite) {
  24219. var engine = this._scene.getEngine();
  24220. this._cachedDepthWriteState = engine.getDepthWrite();
  24221. engine.setDepthWrite(false);
  24222. }
  24223. };
  24224. Material.prototype.unbind = function () {
  24225. this.onUnBindObservable.notifyObservers(this);
  24226. if (this.disableDepthWrite) {
  24227. var engine = this._scene.getEngine();
  24228. engine.setDepthWrite(this._cachedDepthWriteState);
  24229. }
  24230. };
  24231. Material.prototype.getActiveTextures = function () {
  24232. return [];
  24233. };
  24234. Material.prototype.clone = function (name) {
  24235. return null;
  24236. };
  24237. Material.prototype.getBindedMeshes = function () {
  24238. var result = new Array();
  24239. for (var index = 0; index < this._scene.meshes.length; index++) {
  24240. var mesh = this._scene.meshes[index];
  24241. if (mesh.material === this) {
  24242. result.push(mesh);
  24243. }
  24244. }
  24245. return result;
  24246. };
  24247. // Force shader compilation including textures ready check
  24248. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  24249. var _this = this;
  24250. var subMesh = new BABYLON.BaseSubMesh();
  24251. var scene = this.getScene();
  24252. var engine = scene.getEngine();
  24253. var beforeRenderCallback = function () {
  24254. if (subMesh._materialDefines) {
  24255. subMesh._materialDefines._renderId = -1;
  24256. }
  24257. var alphaTestState = engine.getAlphaTesting();
  24258. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  24259. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  24260. scene.unregisterBeforeRender(beforeRenderCallback);
  24261. if (onCompiled) {
  24262. onCompiled(_this);
  24263. }
  24264. }
  24265. engine.setAlphaTesting(alphaTestState);
  24266. };
  24267. scene.registerBeforeRender(beforeRenderCallback);
  24268. };
  24269. Material.prototype.markAsDirty = function (flag) {
  24270. if (flag & Material.TextureDirtyFlag) {
  24271. this._markAllSubMeshesAsTexturesDirty();
  24272. }
  24273. if (flag & Material.LightDirtyFlag) {
  24274. this._markAllSubMeshesAsLightsDirty();
  24275. }
  24276. if (flag & Material.FresnelDirtyFlag) {
  24277. this._markAllSubMeshesAsFresnelDirty();
  24278. }
  24279. if (flag & Material.AttributesDirtyFlag) {
  24280. this._markAllSubMeshesAsAttributesDirty();
  24281. }
  24282. if (flag & Material.MiscDirtyFlag) {
  24283. this._markAllSubMeshesAsMiscDirty();
  24284. }
  24285. this.getScene().resetCachedMaterial();
  24286. };
  24287. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  24288. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24289. var mesh = _a[_i];
  24290. if (!mesh.subMeshes) {
  24291. continue;
  24292. }
  24293. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24294. var subMesh = _c[_b];
  24295. if (subMesh.getMaterial() !== this) {
  24296. continue;
  24297. }
  24298. if (!subMesh._materialDefines) {
  24299. return;
  24300. }
  24301. func(subMesh._materialDefines);
  24302. }
  24303. }
  24304. };
  24305. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  24306. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  24307. };
  24308. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24309. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24310. };
  24311. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24312. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24313. };
  24314. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  24315. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24316. };
  24317. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24318. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24319. };
  24320. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  24321. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24322. };
  24323. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24324. // Animations
  24325. this.getScene().stopAnimation(this);
  24326. // Remove from scene
  24327. var index = this._scene.materials.indexOf(this);
  24328. if (index >= 0) {
  24329. this._scene.materials.splice(index, 1);
  24330. }
  24331. // Remove from meshes
  24332. for (index = 0; index < this._scene.meshes.length; index++) {
  24333. var mesh = this._scene.meshes[index];
  24334. if (mesh.material === this) {
  24335. mesh.material = null;
  24336. if (mesh.geometry) {
  24337. var geometry = mesh.geometry;
  24338. if (this.storeEffectOnSubMeshes) {
  24339. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24340. var subMesh = _a[_i];
  24341. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24342. }
  24343. }
  24344. else {
  24345. geometry._releaseVertexArrayObject(this._effect);
  24346. }
  24347. }
  24348. }
  24349. }
  24350. this._uniformBuffer.dispose();
  24351. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24352. if (forceDisposeEffect && this._effect) {
  24353. if (this.storeEffectOnSubMeshes) {
  24354. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24355. var subMesh = _c[_b];
  24356. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24357. }
  24358. }
  24359. else {
  24360. this._scene.getEngine()._releaseEffect(this._effect);
  24361. }
  24362. this._effect = null;
  24363. }
  24364. // Callback
  24365. this.onDisposeObservable.notifyObservers(this);
  24366. this.onDisposeObservable.clear();
  24367. this.onBindObservable.clear();
  24368. this.onUnBindObservable.clear();
  24369. };
  24370. Material.prototype.serialize = function () {
  24371. return BABYLON.SerializationHelper.Serialize(this);
  24372. };
  24373. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24374. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24375. multiMaterial.id = parsedMultiMaterial.id;
  24376. if (BABYLON.Tags) {
  24377. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24378. }
  24379. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24380. var subMatId = parsedMultiMaterial.materials[matIndex];
  24381. if (subMatId) {
  24382. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24383. }
  24384. else {
  24385. multiMaterial.subMaterials.push(null);
  24386. }
  24387. }
  24388. return multiMaterial;
  24389. };
  24390. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24391. if (!parsedMaterial.customType) {
  24392. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24393. }
  24394. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  24395. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24396. if (!BABYLON.LegacyPBRMaterial) {
  24397. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24398. return;
  24399. }
  24400. }
  24401. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24402. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24403. ;
  24404. };
  24405. return Material;
  24406. }());
  24407. Material._TriangleFillMode = 0;
  24408. Material._WireFrameFillMode = 1;
  24409. Material._PointFillMode = 2;
  24410. Material._ClockWiseSideOrientation = 0;
  24411. Material._CounterClockWiseSideOrientation = 1;
  24412. Material._TextureDirtyFlag = 1;
  24413. Material._LightDirtyFlag = 2;
  24414. Material._FresnelDirtyFlag = 4;
  24415. Material._AttributesDirtyFlag = 8;
  24416. Material._MiscDirtyFlag = 16;
  24417. __decorate([
  24418. BABYLON.serialize()
  24419. ], Material.prototype, "id", void 0);
  24420. __decorate([
  24421. BABYLON.serialize()
  24422. ], Material.prototype, "name", void 0);
  24423. __decorate([
  24424. BABYLON.serialize()
  24425. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24426. __decorate([
  24427. BABYLON.serialize()
  24428. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24429. __decorate([
  24430. BABYLON.serialize()
  24431. ], Material.prototype, "state", void 0);
  24432. __decorate([
  24433. BABYLON.serialize()
  24434. ], Material.prototype, "alpha", void 0);
  24435. __decorate([
  24436. BABYLON.serialize("backFaceCulling")
  24437. ], Material.prototype, "_backFaceCulling", void 0);
  24438. __decorate([
  24439. BABYLON.serialize()
  24440. ], Material.prototype, "sideOrientation", void 0);
  24441. __decorate([
  24442. BABYLON.serialize()
  24443. ], Material.prototype, "alphaMode", void 0);
  24444. __decorate([
  24445. BABYLON.serialize()
  24446. ], Material.prototype, "disableDepthWrite", void 0);
  24447. __decorate([
  24448. BABYLON.serialize("fogEnabled")
  24449. ], Material.prototype, "_fogEnabled", void 0);
  24450. __decorate([
  24451. BABYLON.serialize()
  24452. ], Material.prototype, "pointSize", void 0);
  24453. __decorate([
  24454. BABYLON.serialize()
  24455. ], Material.prototype, "zOffset", void 0);
  24456. __decorate([
  24457. BABYLON.serialize()
  24458. ], Material.prototype, "wireframe", null);
  24459. __decorate([
  24460. BABYLON.serialize()
  24461. ], Material.prototype, "pointsCloud", null);
  24462. __decorate([
  24463. BABYLON.serialize()
  24464. ], Material.prototype, "fillMode", null);
  24465. BABYLON.Material = Material;
  24466. })(BABYLON || (BABYLON = {}));
  24467. //# sourceMappingURL=babylon.material.js.map
  24468. var BABYLON;
  24469. (function (BABYLON) {
  24470. var UniformBuffer = (function () {
  24471. /**
  24472. * Uniform buffer objects.
  24473. *
  24474. * Handles blocks of uniform on the GPU.
  24475. *
  24476. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24477. *
  24478. * For more information, please refer to :
  24479. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24480. */
  24481. function UniformBuffer(engine, data, dynamic) {
  24482. this._engine = engine;
  24483. this._noUBO = engine.webGLVersion === 1;
  24484. this._dynamic = dynamic;
  24485. this._data = data || [];
  24486. this._uniformLocations = {};
  24487. this._uniformSizes = {};
  24488. this._uniformLocationPointer = 0;
  24489. this._needSync = false;
  24490. if (this._noUBO) {
  24491. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24492. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24493. this.updateFloat = this._updateFloatForEffect;
  24494. this.updateFloat2 = this._updateFloat2ForEffect;
  24495. this.updateFloat3 = this._updateFloat3ForEffect;
  24496. this.updateFloat4 = this._updateFloat4ForEffect;
  24497. this.updateMatrix = this._updateMatrixForEffect;
  24498. this.updateVector3 = this._updateVector3ForEffect;
  24499. this.updateVector4 = this._updateVector4ForEffect;
  24500. this.updateColor3 = this._updateColor3ForEffect;
  24501. this.updateColor4 = this._updateColor4ForEffect;
  24502. }
  24503. else {
  24504. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24505. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24506. this.updateFloat = this._updateFloatForUniform;
  24507. this.updateFloat2 = this._updateFloat2ForUniform;
  24508. this.updateFloat3 = this._updateFloat3ForUniform;
  24509. this.updateFloat4 = this._updateFloat4ForUniform;
  24510. this.updateMatrix = this._updateMatrixForUniform;
  24511. this.updateVector3 = this._updateVector3ForUniform;
  24512. this.updateVector4 = this._updateVector4ForUniform;
  24513. this.updateColor3 = this._updateColor3ForUniform;
  24514. this.updateColor4 = this._updateColor4ForUniform;
  24515. }
  24516. }
  24517. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24518. // Properties
  24519. /**
  24520. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24521. * or just falling back on setUniformXXX calls.
  24522. */
  24523. get: function () {
  24524. return !this._noUBO;
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24530. /**
  24531. * Indicates if the WebGL underlying uniform buffer is in sync
  24532. * with the javascript cache data.
  24533. */
  24534. get: function () {
  24535. return !this._needSync;
  24536. },
  24537. enumerable: true,
  24538. configurable: true
  24539. });
  24540. /**
  24541. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24542. * Also, a dynamic UniformBuffer will disable cache verification and always
  24543. * update the underlying WebGL uniform buffer to the GPU.
  24544. */
  24545. UniformBuffer.prototype.isDynamic = function () {
  24546. return this._dynamic;
  24547. };
  24548. /**
  24549. * The data cache on JS side.
  24550. */
  24551. UniformBuffer.prototype.getData = function () {
  24552. return this._bufferData;
  24553. };
  24554. /**
  24555. * The underlying WebGL Uniform buffer.
  24556. */
  24557. UniformBuffer.prototype.getBuffer = function () {
  24558. return this._buffer;
  24559. };
  24560. /**
  24561. * std140 layout specifies how to align data within an UBO structure.
  24562. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24563. * for specs.
  24564. */
  24565. UniformBuffer.prototype._fillAlignment = function (size) {
  24566. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24567. // and 4x4 matrices
  24568. // TODO : change if other types are used
  24569. var alignment;
  24570. if (size <= 2) {
  24571. alignment = size;
  24572. }
  24573. else {
  24574. alignment = 4;
  24575. }
  24576. if ((this._uniformLocationPointer % alignment) !== 0) {
  24577. var oldPointer = this._uniformLocationPointer;
  24578. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24579. var diff = this._uniformLocationPointer - oldPointer;
  24580. for (var i = 0; i < diff; i++) {
  24581. this._data.push(0);
  24582. }
  24583. }
  24584. };
  24585. /**
  24586. * Adds an uniform in the buffer.
  24587. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24588. * for the layout to be correct !
  24589. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24590. * @param {number|number[]} size Data size, or data directly.
  24591. */
  24592. UniformBuffer.prototype.addUniform = function (name, size) {
  24593. if (this._noUBO) {
  24594. return;
  24595. }
  24596. if (this._uniformLocations[name] !== undefined) {
  24597. // Already existing uniform
  24598. return;
  24599. }
  24600. // This function must be called in the order of the shader layout !
  24601. // size can be the size of the uniform, or data directly
  24602. var data;
  24603. if (size instanceof Array) {
  24604. data = size;
  24605. size = data.length;
  24606. }
  24607. else {
  24608. size = size;
  24609. data = [];
  24610. // Fill with zeros
  24611. for (var i = 0; i < size; i++) {
  24612. data.push(0);
  24613. }
  24614. }
  24615. this._fillAlignment(size);
  24616. this._uniformSizes[name] = size;
  24617. this._uniformLocations[name] = this._uniformLocationPointer;
  24618. this._uniformLocationPointer += size;
  24619. for (var i = 0; i < size; i++) {
  24620. this._data.push(data[i]);
  24621. }
  24622. this._needSync = true;
  24623. };
  24624. /**
  24625. * Wrapper for addUniform.
  24626. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24627. * @param {Matrix} mat A 4x4 matrix.
  24628. */
  24629. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24630. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24631. };
  24632. /**
  24633. * Wrapper for addUniform.
  24634. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24635. * @param {number} x
  24636. * @param {number} y
  24637. */
  24638. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24639. var temp = [x, y];
  24640. this.addUniform(name, temp);
  24641. };
  24642. /**
  24643. * Wrapper for addUniform.
  24644. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24645. * @param {number} x
  24646. * @param {number} y
  24647. * @param {number} z
  24648. */
  24649. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24650. var temp = [x, y, z];
  24651. this.addUniform(name, temp);
  24652. };
  24653. /**
  24654. * Wrapper for addUniform.
  24655. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24656. * @param {Color3} color
  24657. */
  24658. UniformBuffer.prototype.addColor3 = function (name, color) {
  24659. var temp = [];
  24660. color.toArray(temp);
  24661. this.addUniform(name, temp);
  24662. };
  24663. /**
  24664. * Wrapper for addUniform.
  24665. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24666. * @param {Color3} color
  24667. * @param {number} alpha
  24668. */
  24669. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24670. var temp = [];
  24671. color.toArray(temp);
  24672. temp.push(alpha);
  24673. this.addUniform(name, temp);
  24674. };
  24675. /**
  24676. * Wrapper for addUniform.
  24677. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24678. * @param {Vector3} vector
  24679. */
  24680. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24681. var temp = [];
  24682. vector.toArray(temp);
  24683. this.addUniform(name, temp);
  24684. };
  24685. /**
  24686. * Wrapper for addUniform.
  24687. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24688. */
  24689. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24690. this.addUniform(name, 12);
  24691. };
  24692. /**
  24693. * Wrapper for addUniform.
  24694. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24695. */
  24696. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24697. this.addUniform(name, 8);
  24698. };
  24699. /**
  24700. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24701. */
  24702. UniformBuffer.prototype.create = function () {
  24703. if (this._noUBO) {
  24704. return;
  24705. }
  24706. if (this._buffer) {
  24707. return; // nothing to do
  24708. }
  24709. // See spec, alignment must be filled as a vec4
  24710. this._fillAlignment(4);
  24711. this._bufferData = new Float32Array(this._data);
  24712. if (this._dynamic) {
  24713. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24714. }
  24715. else {
  24716. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24717. }
  24718. this._needSync = true;
  24719. };
  24720. /**
  24721. * Updates the WebGL Uniform Buffer on the GPU.
  24722. * If the `dynamic` flag is set to true, no cache comparison is done.
  24723. * Otherwise, the buffer will be updated only if the cache differs.
  24724. */
  24725. UniformBuffer.prototype.update = function () {
  24726. if (!this._buffer) {
  24727. this.create();
  24728. return;
  24729. }
  24730. if (!this._dynamic && !this._needSync) {
  24731. return;
  24732. }
  24733. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24734. this._needSync = false;
  24735. };
  24736. /**
  24737. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24738. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24739. * @param {number[]|Float32Array} data Flattened data
  24740. * @param {number} size Size of the data.
  24741. */
  24742. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24743. var location = this._uniformLocations[uniformName];
  24744. if (location === undefined) {
  24745. if (this._buffer) {
  24746. // Cannot add an uniform if the buffer is already created
  24747. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24748. return;
  24749. }
  24750. this.addUniform(uniformName, size);
  24751. location = this._uniformLocations[uniformName];
  24752. }
  24753. if (!this._buffer) {
  24754. this.create();
  24755. }
  24756. if (!this._dynamic) {
  24757. // Cache for static uniform buffers
  24758. var changed = false;
  24759. for (var i = 0; i < size; i++) {
  24760. if (this._bufferData[location + i] !== data[i]) {
  24761. changed = true;
  24762. this._bufferData[location + i] = data[i];
  24763. }
  24764. }
  24765. this._needSync = this._needSync || changed;
  24766. }
  24767. else {
  24768. // No cache for dynamic
  24769. for (var i = 0; i < size; i++) {
  24770. this._bufferData[location + i] = data[i];
  24771. }
  24772. }
  24773. };
  24774. // Update methods
  24775. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24776. // To match std140, matrix must be realigned
  24777. for (var i = 0; i < 3; i++) {
  24778. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24779. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24780. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24781. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24782. }
  24783. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24784. };
  24785. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24786. this._currentEffect.setMatrix3x3(name, matrix);
  24787. };
  24788. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24789. this._currentEffect.setMatrix2x2(name, matrix);
  24790. };
  24791. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24792. // To match std140, matrix must be realigned
  24793. for (var i = 0; i < 2; i++) {
  24794. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24795. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24796. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24797. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24798. }
  24799. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24800. };
  24801. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24802. this._currentEffect.setFloat(name, x);
  24803. };
  24804. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24805. UniformBuffer._tempBuffer[0] = x;
  24806. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24807. };
  24808. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  24809. if (suffix === void 0) { suffix = ""; }
  24810. this._currentEffect.setFloat2(name + suffix, x, y);
  24811. };
  24812. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  24813. if (suffix === void 0) { suffix = ""; }
  24814. UniformBuffer._tempBuffer[0] = x;
  24815. UniformBuffer._tempBuffer[1] = y;
  24816. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24817. };
  24818. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24819. if (suffix === void 0) { suffix = ""; }
  24820. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24821. };
  24822. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24823. if (suffix === void 0) { suffix = ""; }
  24824. UniformBuffer._tempBuffer[0] = x;
  24825. UniformBuffer._tempBuffer[1] = y;
  24826. UniformBuffer._tempBuffer[2] = z;
  24827. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24828. };
  24829. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24830. if (suffix === void 0) { suffix = ""; }
  24831. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24832. };
  24833. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24834. if (suffix === void 0) { suffix = ""; }
  24835. UniformBuffer._tempBuffer[0] = x;
  24836. UniformBuffer._tempBuffer[1] = y;
  24837. UniformBuffer._tempBuffer[2] = z;
  24838. UniformBuffer._tempBuffer[3] = w;
  24839. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24840. };
  24841. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24842. this._currentEffect.setMatrix(name, mat);
  24843. };
  24844. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24845. this.updateUniform(name, mat.toArray(), 16);
  24846. };
  24847. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24848. this._currentEffect.setVector3(name, vector);
  24849. };
  24850. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24851. vector.toArray(UniformBuffer._tempBuffer);
  24852. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24853. };
  24854. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24855. this._currentEffect.setVector4(name, vector);
  24856. };
  24857. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24858. vector.toArray(UniformBuffer._tempBuffer);
  24859. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24860. };
  24861. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24862. if (suffix === void 0) { suffix = ""; }
  24863. this._currentEffect.setColor3(name + suffix, color);
  24864. };
  24865. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24866. if (suffix === void 0) { suffix = ""; }
  24867. color.toArray(UniformBuffer._tempBuffer);
  24868. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24869. };
  24870. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24871. if (suffix === void 0) { suffix = ""; }
  24872. this._currentEffect.setColor4(name + suffix, color, alpha);
  24873. };
  24874. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24875. if (suffix === void 0) { suffix = ""; }
  24876. color.toArray(UniformBuffer._tempBuffer);
  24877. UniformBuffer._tempBuffer[3] = alpha;
  24878. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24879. };
  24880. /**
  24881. * Sets a sampler uniform on the effect.
  24882. * @param {string} name Name of the sampler.
  24883. * @param {Texture} texture
  24884. */
  24885. UniformBuffer.prototype.setTexture = function (name, texture) {
  24886. this._currentEffect.setTexture(name, texture);
  24887. };
  24888. /**
  24889. * Directly updates the value of the uniform in the cache AND on the GPU.
  24890. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24891. * @param {number[]|Float32Array} data Flattened data
  24892. */
  24893. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24894. this.updateUniform(uniformName, data, data.length);
  24895. this.update();
  24896. };
  24897. /**
  24898. * Binds this uniform buffer to an effect.
  24899. * @param {Effect} effect
  24900. * @param {string} name Name of the uniform block in the shader.
  24901. */
  24902. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24903. this._currentEffect = effect;
  24904. if (this._noUBO) {
  24905. return;
  24906. }
  24907. effect.bindUniformBuffer(this._buffer, name);
  24908. };
  24909. /**
  24910. * Disposes the uniform buffer.
  24911. */
  24912. UniformBuffer.prototype.dispose = function () {
  24913. if (!this._buffer) {
  24914. return;
  24915. }
  24916. if (this._engine._releaseBuffer(this._buffer)) {
  24917. this._buffer = null;
  24918. }
  24919. };
  24920. return UniformBuffer;
  24921. }());
  24922. // Pool for avoiding memory leaks
  24923. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24924. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24925. BABYLON.UniformBuffer = UniformBuffer;
  24926. })(BABYLON || (BABYLON = {}));
  24927. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24928. var BABYLON;
  24929. (function (BABYLON) {
  24930. var PushMaterial = (function (_super) {
  24931. __extends(PushMaterial, _super);
  24932. function PushMaterial(name, scene) {
  24933. var _this = _super.call(this, name, scene) || this;
  24934. _this.storeEffectOnSubMeshes = true;
  24935. return _this;
  24936. }
  24937. PushMaterial.prototype.getEffect = function () {
  24938. return this._activeEffect;
  24939. };
  24940. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24941. if (!mesh) {
  24942. return false;
  24943. }
  24944. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24945. return true;
  24946. }
  24947. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24948. };
  24949. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24950. this._activeEffect.setMatrix("world", world);
  24951. };
  24952. PushMaterial.prototype.bind = function (world, mesh) {
  24953. if (!mesh) {
  24954. return;
  24955. }
  24956. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24957. };
  24958. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24959. _super.prototype._afterBind.call(this, mesh);
  24960. this.getScene()._cachedEffect = effect;
  24961. };
  24962. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24963. if (visibility === void 0) { visibility = 0; }
  24964. return scene.isCachedMaterialValid(this, effect, visibility);
  24965. };
  24966. return PushMaterial;
  24967. }(BABYLON.Material));
  24968. BABYLON.PushMaterial = PushMaterial;
  24969. })(BABYLON || (BABYLON = {}));
  24970. //# sourceMappingURL=babylon.pushMaterial.js.map
  24971. var BABYLON;
  24972. (function (BABYLON) {
  24973. var VertexData = (function () {
  24974. function VertexData() {
  24975. }
  24976. VertexData.prototype.set = function (data, kind) {
  24977. switch (kind) {
  24978. case BABYLON.VertexBuffer.PositionKind:
  24979. this.positions = data;
  24980. break;
  24981. case BABYLON.VertexBuffer.NormalKind:
  24982. this.normals = data;
  24983. break;
  24984. case BABYLON.VertexBuffer.TangentKind:
  24985. this.tangents = data;
  24986. break;
  24987. case BABYLON.VertexBuffer.UVKind:
  24988. this.uvs = data;
  24989. break;
  24990. case BABYLON.VertexBuffer.UV2Kind:
  24991. this.uvs2 = data;
  24992. break;
  24993. case BABYLON.VertexBuffer.UV3Kind:
  24994. this.uvs3 = data;
  24995. break;
  24996. case BABYLON.VertexBuffer.UV4Kind:
  24997. this.uvs4 = data;
  24998. break;
  24999. case BABYLON.VertexBuffer.UV5Kind:
  25000. this.uvs5 = data;
  25001. break;
  25002. case BABYLON.VertexBuffer.UV6Kind:
  25003. this.uvs6 = data;
  25004. break;
  25005. case BABYLON.VertexBuffer.ColorKind:
  25006. this.colors = data;
  25007. break;
  25008. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25009. this.matricesIndices = data;
  25010. break;
  25011. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25012. this.matricesWeights = data;
  25013. break;
  25014. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  25015. this.matricesIndicesExtra = data;
  25016. break;
  25017. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  25018. this.matricesWeightsExtra = data;
  25019. break;
  25020. }
  25021. };
  25022. /**
  25023. * Associates the vertexData to the passed Mesh.
  25024. * Sets it as updatable or not (default `false`).
  25025. * Returns the VertexData.
  25026. */
  25027. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25028. this._applyTo(mesh, updatable);
  25029. return this;
  25030. };
  25031. /**
  25032. * Associates the vertexData to the passed Geometry.
  25033. * Sets it as updatable or not (default `false`).
  25034. * Returns the VertexData.
  25035. */
  25036. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25037. this._applyTo(geometry, updatable);
  25038. return this;
  25039. };
  25040. /**
  25041. * Updates the associated mesh.
  25042. * Returns the VertexData.
  25043. */
  25044. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25045. this._update(mesh);
  25046. return this;
  25047. };
  25048. /**
  25049. * Updates the associated geometry.
  25050. * Returns the VertexData.
  25051. */
  25052. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25053. this._update(geometry);
  25054. return this;
  25055. };
  25056. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25057. if (this.positions) {
  25058. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25059. }
  25060. if (this.normals) {
  25061. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25062. }
  25063. if (this.tangents) {
  25064. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25065. }
  25066. if (this.uvs) {
  25067. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25068. }
  25069. if (this.uvs2) {
  25070. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25071. }
  25072. if (this.uvs3) {
  25073. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25074. }
  25075. if (this.uvs4) {
  25076. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25077. }
  25078. if (this.uvs5) {
  25079. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25080. }
  25081. if (this.uvs6) {
  25082. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25083. }
  25084. if (this.colors) {
  25085. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25086. }
  25087. if (this.matricesIndices) {
  25088. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25089. }
  25090. if (this.matricesWeights) {
  25091. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25092. }
  25093. if (this.matricesIndicesExtra) {
  25094. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25095. }
  25096. if (this.matricesWeightsExtra) {
  25097. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25098. }
  25099. if (this.indices) {
  25100. meshOrGeometry.setIndices(this.indices);
  25101. }
  25102. return this;
  25103. };
  25104. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25105. if (this.positions) {
  25106. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25107. }
  25108. if (this.normals) {
  25109. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25110. }
  25111. if (this.tangents) {
  25112. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25113. }
  25114. if (this.uvs) {
  25115. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25116. }
  25117. if (this.uvs2) {
  25118. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25119. }
  25120. if (this.uvs3) {
  25121. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25122. }
  25123. if (this.uvs4) {
  25124. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25125. }
  25126. if (this.uvs5) {
  25127. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25128. }
  25129. if (this.uvs6) {
  25130. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25131. }
  25132. if (this.colors) {
  25133. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25134. }
  25135. if (this.matricesIndices) {
  25136. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25137. }
  25138. if (this.matricesWeights) {
  25139. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25140. }
  25141. if (this.matricesIndicesExtra) {
  25142. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25143. }
  25144. if (this.matricesWeightsExtra) {
  25145. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25146. }
  25147. if (this.indices) {
  25148. meshOrGeometry.setIndices(this.indices);
  25149. }
  25150. return this;
  25151. };
  25152. /**
  25153. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  25154. * Returns the VertexData.
  25155. */
  25156. VertexData.prototype.transform = function (matrix) {
  25157. var transformed = BABYLON.Vector3.Zero();
  25158. var index;
  25159. if (this.positions) {
  25160. var position = BABYLON.Vector3.Zero();
  25161. for (index = 0; index < this.positions.length; index += 3) {
  25162. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25163. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25164. this.positions[index] = transformed.x;
  25165. this.positions[index + 1] = transformed.y;
  25166. this.positions[index + 2] = transformed.z;
  25167. }
  25168. }
  25169. if (this.normals) {
  25170. var normal = BABYLON.Vector3.Zero();
  25171. for (index = 0; index < this.normals.length; index += 3) {
  25172. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25173. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25174. this.normals[index] = transformed.x;
  25175. this.normals[index + 1] = transformed.y;
  25176. this.normals[index + 2] = transformed.z;
  25177. }
  25178. }
  25179. if (this.tangents) {
  25180. var tangent = BABYLON.Vector4.Zero();
  25181. var tangentTransformed = BABYLON.Vector4.Zero();
  25182. for (index = 0; index < this.tangents.length; index += 4) {
  25183. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  25184. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  25185. this.tangents[index] = tangentTransformed.x;
  25186. this.tangents[index + 1] = tangentTransformed.y;
  25187. this.tangents[index + 2] = tangentTransformed.z;
  25188. this.tangents[index + 3] = tangentTransformed.w;
  25189. }
  25190. }
  25191. return this;
  25192. };
  25193. /**
  25194. * Merges the passed VertexData into the current one.
  25195. * Returns the modified VertexData.
  25196. */
  25197. VertexData.prototype.merge = function (other) {
  25198. if (other.indices) {
  25199. if (!this.indices) {
  25200. this.indices = [];
  25201. }
  25202. var offset = this.positions ? this.positions.length / 3 : 0;
  25203. for (var index = 0; index < other.indices.length; index++) {
  25204. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  25205. this.indices.push(other.indices[index] + offset);
  25206. }
  25207. }
  25208. this.positions = this._mergeElement(this.positions, other.positions);
  25209. this.normals = this._mergeElement(this.normals, other.normals);
  25210. this.tangents = this._mergeElement(this.tangents, other.tangents);
  25211. this.uvs = this._mergeElement(this.uvs, other.uvs);
  25212. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  25213. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  25214. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  25215. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  25216. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  25217. this.colors = this._mergeElement(this.colors, other.colors);
  25218. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  25219. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  25220. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  25221. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  25222. return this;
  25223. };
  25224. VertexData.prototype._mergeElement = function (source, other) {
  25225. if (!other)
  25226. return source;
  25227. if (!source)
  25228. return other;
  25229. var len = other.length + source.length;
  25230. var isSrcTypedArray = source instanceof Float32Array;
  25231. var isOthTypedArray = other instanceof Float32Array;
  25232. // use non-loop method when the source is Float32Array
  25233. if (isSrcTypedArray) {
  25234. var ret32 = new Float32Array(len);
  25235. ret32.set(source);
  25236. ret32.set(other, source.length);
  25237. return ret32;
  25238. // source is number[], when other is also use concat
  25239. }
  25240. else if (!isOthTypedArray) {
  25241. return source.concat(other);
  25242. // source is a number[], but other is a Float32Array, loop required
  25243. }
  25244. else {
  25245. var ret = source.slice(0); // copy source to a separate array
  25246. for (var i = 0, len = other.length; i < len; i++) {
  25247. ret.push(other[i]);
  25248. }
  25249. return ret;
  25250. }
  25251. };
  25252. /**
  25253. * Serializes the VertexData.
  25254. * Returns a serialized object.
  25255. */
  25256. VertexData.prototype.serialize = function () {
  25257. var serializationObject = this.serialize();
  25258. if (this.positions) {
  25259. serializationObject.positions = this.positions;
  25260. }
  25261. if (this.normals) {
  25262. serializationObject.normals = this.normals;
  25263. }
  25264. if (this.tangents) {
  25265. serializationObject.tangents = this.tangents;
  25266. }
  25267. if (this.uvs) {
  25268. serializationObject.uvs = this.uvs;
  25269. }
  25270. if (this.uvs2) {
  25271. serializationObject.uvs2 = this.uvs2;
  25272. }
  25273. if (this.uvs3) {
  25274. serializationObject.uvs3 = this.uvs3;
  25275. }
  25276. if (this.uvs4) {
  25277. serializationObject.uvs4 = this.uvs4;
  25278. }
  25279. if (this.uvs5) {
  25280. serializationObject.uvs5 = this.uvs5;
  25281. }
  25282. if (this.uvs6) {
  25283. serializationObject.uvs6 = this.uvs6;
  25284. }
  25285. if (this.colors) {
  25286. serializationObject.colors = this.colors;
  25287. }
  25288. if (this.matricesIndices) {
  25289. serializationObject.matricesIndices = this.matricesIndices;
  25290. serializationObject.matricesIndices._isExpanded = true;
  25291. }
  25292. if (this.matricesWeights) {
  25293. serializationObject.matricesWeights = this.matricesWeights;
  25294. }
  25295. if (this.matricesIndicesExtra) {
  25296. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25297. serializationObject.matricesIndicesExtra._isExpanded = true;
  25298. }
  25299. if (this.matricesWeightsExtra) {
  25300. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25301. }
  25302. serializationObject.indices = this.indices;
  25303. return serializationObject;
  25304. };
  25305. // Statics
  25306. /**
  25307. * Returns the object VertexData associated to the passed mesh.
  25308. */
  25309. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25310. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25311. };
  25312. /**
  25313. * Returns the object VertexData associated to the passed geometry.
  25314. */
  25315. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25316. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25317. };
  25318. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25319. var result = new VertexData();
  25320. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25321. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25322. }
  25323. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25324. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25325. }
  25326. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25327. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25328. }
  25329. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25330. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25331. }
  25332. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25333. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25334. }
  25335. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25336. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25337. }
  25338. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25339. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25340. }
  25341. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25342. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25343. }
  25344. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25345. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25346. }
  25347. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25348. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25349. }
  25350. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25351. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25352. }
  25353. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25354. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25355. }
  25356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25357. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25358. }
  25359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25360. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25361. }
  25362. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25363. return result;
  25364. };
  25365. /**
  25366. * Creates the vertexData of the Ribbon.
  25367. */
  25368. VertexData.CreateRibbon = function (options) {
  25369. var pathArray = options.pathArray;
  25370. var closeArray = options.closeArray || false;
  25371. var closePath = options.closePath || false;
  25372. var invertUV = options.invertUV || false;
  25373. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25374. var offset = options.offset || defaultOffset;
  25375. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25376. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25377. var customUV = options.uvs;
  25378. var customColors = options.colors;
  25379. var positions = [];
  25380. var indices = [];
  25381. var normals = [];
  25382. var uvs = [];
  25383. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25384. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25385. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25386. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25387. var minlg; // minimal length among all paths from pathArray
  25388. var lg = []; // array of path lengths : nb of vertex per path
  25389. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25390. var p; // path iterator
  25391. var i; // point iterator
  25392. var j; // point iterator
  25393. // if single path in pathArray
  25394. if (pathArray.length < 2) {
  25395. var ar1 = [];
  25396. var ar2 = [];
  25397. for (i = 0; i < pathArray[0].length - offset; i++) {
  25398. ar1.push(pathArray[0][i]);
  25399. ar2.push(pathArray[0][i + offset]);
  25400. }
  25401. pathArray = [ar1, ar2];
  25402. }
  25403. // positions and horizontal distances (u)
  25404. var idc = 0;
  25405. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25406. var path;
  25407. var l;
  25408. minlg = pathArray[0].length;
  25409. var vectlg;
  25410. var dist;
  25411. for (p = 0; p < pathArray.length; p++) {
  25412. uTotalDistance[p] = 0;
  25413. us[p] = [0];
  25414. path = pathArray[p];
  25415. l = path.length;
  25416. minlg = (minlg < l) ? minlg : l;
  25417. j = 0;
  25418. while (j < l) {
  25419. positions.push(path[j].x, path[j].y, path[j].z);
  25420. if (j > 0) {
  25421. vectlg = path[j].subtract(path[j - 1]).length();
  25422. dist = vectlg + uTotalDistance[p];
  25423. us[p].push(dist);
  25424. uTotalDistance[p] = dist;
  25425. }
  25426. j++;
  25427. }
  25428. if (closePath) {
  25429. j--;
  25430. positions.push(path[0].x, path[0].y, path[0].z);
  25431. vectlg = path[j].subtract(path[0]).length();
  25432. dist = vectlg + uTotalDistance[p];
  25433. us[p].push(dist);
  25434. uTotalDistance[p] = dist;
  25435. }
  25436. lg[p] = l + closePathCorr;
  25437. idx[p] = idc;
  25438. idc += (l + closePathCorr);
  25439. }
  25440. // vertical distances (v)
  25441. var path1;
  25442. var path2;
  25443. var vertex1;
  25444. var vertex2;
  25445. for (i = 0; i < minlg + closePathCorr; i++) {
  25446. vTotalDistance[i] = 0;
  25447. vs[i] = [0];
  25448. for (p = 0; p < pathArray.length - 1; p++) {
  25449. path1 = pathArray[p];
  25450. path2 = pathArray[p + 1];
  25451. if (i === minlg) {
  25452. vertex1 = path1[0];
  25453. vertex2 = path2[0];
  25454. }
  25455. else {
  25456. vertex1 = path1[i];
  25457. vertex2 = path2[i];
  25458. }
  25459. vectlg = vertex2.subtract(vertex1).length();
  25460. dist = vectlg + vTotalDistance[i];
  25461. vs[i].push(dist);
  25462. vTotalDistance[i] = dist;
  25463. }
  25464. if (closeArray) {
  25465. path1 = pathArray[p];
  25466. path2 = pathArray[0];
  25467. if (i === minlg) {
  25468. vertex2 = path2[0];
  25469. }
  25470. vectlg = vertex2.subtract(vertex1).length();
  25471. dist = vectlg + vTotalDistance[i];
  25472. vTotalDistance[i] = dist;
  25473. }
  25474. }
  25475. // uvs
  25476. var u;
  25477. var v;
  25478. if (customUV) {
  25479. for (p = 0; p < customUV.length; p++) {
  25480. uvs.push(customUV[p].x, customUV[p].y);
  25481. }
  25482. }
  25483. else {
  25484. for (p = 0; p < pathArray.length; p++) {
  25485. for (i = 0; i < minlg + closePathCorr; i++) {
  25486. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25487. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25488. if (invertUV) {
  25489. uvs.push(v, u);
  25490. }
  25491. else {
  25492. uvs.push(u, v);
  25493. }
  25494. }
  25495. }
  25496. }
  25497. // indices
  25498. p = 0; // path index
  25499. var pi = 0; // positions array index
  25500. var l1 = lg[p] - 1; // path1 length
  25501. var l2 = lg[p + 1] - 1; // path2 length
  25502. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25503. var shft = idx[1] - idx[0]; // shift
  25504. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25505. while (pi <= min && p < path1nb) {
  25506. // 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
  25507. indices.push(pi, pi + shft, pi + 1);
  25508. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25509. pi += 1;
  25510. if (pi === min) {
  25511. p++;
  25512. if (p === lg.length - 1) {
  25513. shft = idx[0] - idx[p];
  25514. l1 = lg[p] - 1;
  25515. l2 = lg[0] - 1;
  25516. }
  25517. else {
  25518. shft = idx[p + 1] - idx[p];
  25519. l1 = lg[p] - 1;
  25520. l2 = lg[p + 1] - 1;
  25521. }
  25522. pi = idx[p];
  25523. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25524. }
  25525. }
  25526. // normals
  25527. VertexData.ComputeNormals(positions, indices, normals);
  25528. if (closePath) {
  25529. var indexFirst = 0;
  25530. var indexLast = 0;
  25531. for (p = 0; p < pathArray.length; p++) {
  25532. indexFirst = idx[p] * 3;
  25533. if (p + 1 < pathArray.length) {
  25534. indexLast = (idx[p + 1] - 1) * 3;
  25535. }
  25536. else {
  25537. indexLast = normals.length - 3;
  25538. }
  25539. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25540. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25541. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25542. normals[indexLast] = normals[indexFirst];
  25543. normals[indexLast + 1] = normals[indexFirst + 1];
  25544. normals[indexLast + 2] = normals[indexFirst + 2];
  25545. }
  25546. }
  25547. // sides
  25548. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25549. // Colors
  25550. if (customColors) {
  25551. var colors = new Float32Array(customColors.length * 4);
  25552. for (var c = 0; c < customColors.length; c++) {
  25553. colors[c * 4] = customColors[c].r;
  25554. colors[c * 4 + 1] = customColors[c].g;
  25555. colors[c * 4 + 2] = customColors[c].b;
  25556. colors[c * 4 + 3] = customColors[c].a;
  25557. }
  25558. }
  25559. // Result
  25560. var vertexData = new VertexData();
  25561. var positions32 = new Float32Array(positions);
  25562. var normals32 = new Float32Array(normals);
  25563. var uvs32 = new Float32Array(uvs);
  25564. vertexData.indices = indices;
  25565. vertexData.positions = positions32;
  25566. vertexData.normals = normals32;
  25567. vertexData.uvs = uvs32;
  25568. if (customColors) {
  25569. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25570. }
  25571. if (closePath) {
  25572. vertexData._idx = idx;
  25573. }
  25574. return vertexData;
  25575. };
  25576. /**
  25577. * Creates the VertexData of the Box.
  25578. */
  25579. VertexData.CreateBox = function (options) {
  25580. var normalsSource = [
  25581. new BABYLON.Vector3(0, 0, 1),
  25582. new BABYLON.Vector3(0, 0, -1),
  25583. new BABYLON.Vector3(1, 0, 0),
  25584. new BABYLON.Vector3(-1, 0, 0),
  25585. new BABYLON.Vector3(0, 1, 0),
  25586. new BABYLON.Vector3(0, -1, 0)
  25587. ];
  25588. var indices = [];
  25589. var positions = [];
  25590. var normals = [];
  25591. var uvs = [];
  25592. var width = options.width || options.size || 1;
  25593. var height = options.height || options.size || 1;
  25594. var depth = options.depth || options.size || 1;
  25595. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25596. var faceUV = options.faceUV || new Array(6);
  25597. var faceColors = options.faceColors;
  25598. var colors = [];
  25599. // default face colors and UV if undefined
  25600. for (var f = 0; f < 6; f++) {
  25601. if (faceUV[f] === undefined) {
  25602. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25603. }
  25604. if (faceColors && faceColors[f] === undefined) {
  25605. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25606. }
  25607. }
  25608. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25609. // Create each face in turn.
  25610. for (var index = 0; index < normalsSource.length; index++) {
  25611. var normal = normalsSource[index];
  25612. // Get two vectors perpendicular to the face normal and to each other.
  25613. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25614. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25615. // Six indices (two triangles) per face.
  25616. var verticesLength = positions.length / 3;
  25617. indices.push(verticesLength);
  25618. indices.push(verticesLength + 1);
  25619. indices.push(verticesLength + 2);
  25620. indices.push(verticesLength);
  25621. indices.push(verticesLength + 2);
  25622. indices.push(verticesLength + 3);
  25623. // Four vertices per face.
  25624. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25625. positions.push(vertex.x, vertex.y, vertex.z);
  25626. normals.push(normal.x, normal.y, normal.z);
  25627. uvs.push(faceUV[index].z, faceUV[index].w);
  25628. if (faceColors) {
  25629. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25630. }
  25631. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25632. positions.push(vertex.x, vertex.y, vertex.z);
  25633. normals.push(normal.x, normal.y, normal.z);
  25634. uvs.push(faceUV[index].x, faceUV[index].w);
  25635. if (faceColors) {
  25636. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25637. }
  25638. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25639. positions.push(vertex.x, vertex.y, vertex.z);
  25640. normals.push(normal.x, normal.y, normal.z);
  25641. uvs.push(faceUV[index].x, faceUV[index].y);
  25642. if (faceColors) {
  25643. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25644. }
  25645. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25646. positions.push(vertex.x, vertex.y, vertex.z);
  25647. normals.push(normal.x, normal.y, normal.z);
  25648. uvs.push(faceUV[index].z, faceUV[index].y);
  25649. if (faceColors) {
  25650. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25651. }
  25652. }
  25653. // sides
  25654. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25655. // Result
  25656. var vertexData = new VertexData();
  25657. vertexData.indices = indices;
  25658. vertexData.positions = positions;
  25659. vertexData.normals = normals;
  25660. vertexData.uvs = uvs;
  25661. if (faceColors) {
  25662. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25663. vertexData.colors = totalColors;
  25664. }
  25665. return vertexData;
  25666. };
  25667. /**
  25668. * Creates the VertexData of the Sphere.
  25669. */
  25670. VertexData.CreateSphere = function (options) {
  25671. var segments = options.segments || 32;
  25672. var diameterX = options.diameterX || options.diameter || 1;
  25673. var diameterY = options.diameterY || options.diameter || 1;
  25674. var diameterZ = options.diameterZ || options.diameter || 1;
  25675. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25676. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25677. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25678. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25679. var totalZRotationSteps = 2 + segments;
  25680. var totalYRotationSteps = 2 * totalZRotationSteps;
  25681. var indices = [];
  25682. var positions = [];
  25683. var normals = [];
  25684. var uvs = [];
  25685. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25686. var normalizedZ = zRotationStep / totalZRotationSteps;
  25687. var angleZ = normalizedZ * Math.PI * slice;
  25688. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25689. var normalizedY = yRotationStep / totalYRotationSteps;
  25690. var angleY = normalizedY * Math.PI * 2 * arc;
  25691. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25692. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25693. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25694. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25695. var vertex = complete.multiply(radius);
  25696. var normal = complete.divide(radius).normalize();
  25697. positions.push(vertex.x, vertex.y, vertex.z);
  25698. normals.push(normal.x, normal.y, normal.z);
  25699. uvs.push(normalizedY, normalizedZ);
  25700. }
  25701. if (zRotationStep > 0) {
  25702. var verticesCount = positions.length / 3;
  25703. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25704. indices.push((firstIndex));
  25705. indices.push((firstIndex + 1));
  25706. indices.push(firstIndex + totalYRotationSteps + 1);
  25707. indices.push((firstIndex + totalYRotationSteps + 1));
  25708. indices.push((firstIndex + 1));
  25709. indices.push((firstIndex + totalYRotationSteps + 2));
  25710. }
  25711. }
  25712. }
  25713. // Sides
  25714. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25715. // Result
  25716. var vertexData = new VertexData();
  25717. vertexData.indices = indices;
  25718. vertexData.positions = positions;
  25719. vertexData.normals = normals;
  25720. vertexData.uvs = uvs;
  25721. return vertexData;
  25722. };
  25723. /**
  25724. * Creates the VertexData of the Cylinder or Cone.
  25725. */
  25726. VertexData.CreateCylinder = function (options) {
  25727. var height = options.height || 2;
  25728. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25729. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25730. var tessellation = options.tessellation || 24;
  25731. var subdivisions = options.subdivisions || 1;
  25732. var hasRings = options.hasRings;
  25733. var enclose = options.enclose;
  25734. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25735. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25736. var faceUV = options.faceUV || new Array(3);
  25737. var faceColors = options.faceColors;
  25738. // default face colors and UV if undefined
  25739. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25740. var ringNb = (hasRings) ? subdivisions : 1;
  25741. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25742. var f;
  25743. for (f = 0; f < surfaceNb; f++) {
  25744. if (faceColors && faceColors[f] === undefined) {
  25745. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25746. }
  25747. }
  25748. for (f = 0; f < surfaceNb; f++) {
  25749. if (faceUV && faceUV[f] === undefined) {
  25750. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25751. }
  25752. }
  25753. var indices = [];
  25754. var positions = [];
  25755. var normals = [];
  25756. var uvs = [];
  25757. var colors = [];
  25758. var angle_step = Math.PI * 2 * arc / tessellation;
  25759. var angle;
  25760. var h;
  25761. var radius;
  25762. var tan = (diameterBottom - diameterTop) / 2 / height;
  25763. var ringVertex = BABYLON.Vector3.Zero();
  25764. var ringNormal = BABYLON.Vector3.Zero();
  25765. var ringFirstVertex = BABYLON.Vector3.Zero();
  25766. var ringFirstNormal = BABYLON.Vector3.Zero();
  25767. var quadNormal = BABYLON.Vector3.Zero();
  25768. var Y = BABYLON.Axis.Y;
  25769. // positions, normals, uvs
  25770. var i;
  25771. var j;
  25772. var r;
  25773. var ringIdx = 1;
  25774. var s = 1; // surface index
  25775. var cs = 0;
  25776. var v = 0;
  25777. for (i = 0; i <= subdivisions; i++) {
  25778. h = i / subdivisions;
  25779. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25780. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25781. for (r = 0; r < ringIdx; r++) {
  25782. if (hasRings) {
  25783. s += r;
  25784. }
  25785. if (enclose) {
  25786. s += 2 * r;
  25787. }
  25788. for (j = 0; j <= tessellation; j++) {
  25789. angle = j * angle_step;
  25790. // position
  25791. ringVertex.x = Math.cos(-angle) * radius;
  25792. ringVertex.y = -height / 2 + h * height;
  25793. ringVertex.z = Math.sin(-angle) * radius;
  25794. // normal
  25795. if (diameterTop === 0 && i === subdivisions) {
  25796. // if no top cap, reuse former normals
  25797. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25798. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25799. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25800. }
  25801. else {
  25802. ringNormal.x = ringVertex.x;
  25803. ringNormal.z = ringVertex.z;
  25804. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25805. ringNormal.normalize();
  25806. }
  25807. // keep first ring vertex values for enclose
  25808. if (j === 0) {
  25809. ringFirstVertex.copyFrom(ringVertex);
  25810. ringFirstNormal.copyFrom(ringNormal);
  25811. }
  25812. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25813. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25814. if (hasRings) {
  25815. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25816. }
  25817. else {
  25818. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25819. }
  25820. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25821. if (faceColors) {
  25822. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25823. }
  25824. }
  25825. // if enclose, add four vertices and their dedicated normals
  25826. if (arc !== 1 && enclose) {
  25827. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25828. positions.push(0, ringVertex.y, 0);
  25829. positions.push(0, ringVertex.y, 0);
  25830. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25831. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25832. quadNormal.normalize();
  25833. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25834. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25835. quadNormal.normalize();
  25836. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25837. if (hasRings) {
  25838. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25839. }
  25840. else {
  25841. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25842. }
  25843. uvs.push(faceUV[s + 1].x, v);
  25844. uvs.push(faceUV[s + 1].z, v);
  25845. if (hasRings) {
  25846. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25847. }
  25848. else {
  25849. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25850. }
  25851. uvs.push(faceUV[s + 2].x, v);
  25852. uvs.push(faceUV[s + 2].z, v);
  25853. if (faceColors) {
  25854. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25855. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25856. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25857. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25858. }
  25859. }
  25860. if (cs !== s) {
  25861. cs = s;
  25862. }
  25863. }
  25864. }
  25865. // indices
  25866. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25867. var s;
  25868. i = 0;
  25869. for (s = 0; s < subdivisions; s++) {
  25870. for (j = 0; j < tessellation; j++) {
  25871. var i0 = i * (e + 1) + j;
  25872. var i1 = (i + 1) * (e + 1) + j;
  25873. var i2 = i * (e + 1) + (j + 1);
  25874. var i3 = (i + 1) * (e + 1) + (j + 1);
  25875. indices.push(i0, i1, i2);
  25876. indices.push(i3, i2, i1);
  25877. }
  25878. if (arc !== 1 && enclose) {
  25879. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25880. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25881. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25882. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25883. }
  25884. i = (hasRings) ? (i + 2) : (i + 1);
  25885. }
  25886. // Caps
  25887. var createCylinderCap = function (isTop) {
  25888. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25889. if (radius === 0) {
  25890. return;
  25891. }
  25892. // Cap positions, normals & uvs
  25893. var angle;
  25894. var circleVector;
  25895. var i;
  25896. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25897. var c;
  25898. if (faceColors) {
  25899. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25900. }
  25901. // cap center
  25902. var vbase = positions.length / 3;
  25903. var offset = isTop ? height / 2 : -height / 2;
  25904. var center = new BABYLON.Vector3(0, offset, 0);
  25905. positions.push(center.x, center.y, center.z);
  25906. normals.push(0, isTop ? 1 : -1, 0);
  25907. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25908. if (faceColors) {
  25909. colors.push(c.r, c.g, c.b, c.a);
  25910. }
  25911. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25912. for (i = 0; i <= tessellation; i++) {
  25913. angle = Math.PI * 2 * i * arc / tessellation;
  25914. var cos = Math.cos(-angle);
  25915. var sin = Math.sin(-angle);
  25916. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25917. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25918. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25919. normals.push(0, isTop ? 1 : -1, 0);
  25920. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25921. if (faceColors) {
  25922. colors.push(c.r, c.g, c.b, c.a);
  25923. }
  25924. }
  25925. // Cap indices
  25926. for (i = 0; i < tessellation; i++) {
  25927. if (!isTop) {
  25928. indices.push(vbase);
  25929. indices.push(vbase + (i + 1));
  25930. indices.push(vbase + (i + 2));
  25931. }
  25932. else {
  25933. indices.push(vbase);
  25934. indices.push(vbase + (i + 2));
  25935. indices.push(vbase + (i + 1));
  25936. }
  25937. }
  25938. };
  25939. // add caps to geometry
  25940. createCylinderCap(false);
  25941. createCylinderCap(true);
  25942. // Sides
  25943. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25944. var vertexData = new VertexData();
  25945. vertexData.indices = indices;
  25946. vertexData.positions = positions;
  25947. vertexData.normals = normals;
  25948. vertexData.uvs = uvs;
  25949. if (faceColors) {
  25950. vertexData.colors = colors;
  25951. }
  25952. return vertexData;
  25953. };
  25954. /**
  25955. * Creates the VertexData of the Torus.
  25956. */
  25957. VertexData.CreateTorus = function (options) {
  25958. var indices = [];
  25959. var positions = [];
  25960. var normals = [];
  25961. var uvs = [];
  25962. var diameter = options.diameter || 1;
  25963. var thickness = options.thickness || 0.5;
  25964. var tessellation = options.tessellation || 16;
  25965. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25966. var stride = tessellation + 1;
  25967. for (var i = 0; i <= tessellation; i++) {
  25968. var u = i / tessellation;
  25969. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25970. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25971. for (var j = 0; j <= tessellation; j++) {
  25972. var v = 1 - j / tessellation;
  25973. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25974. var dx = Math.cos(innerAngle);
  25975. var dy = Math.sin(innerAngle);
  25976. // Create a vertex.
  25977. var normal = new BABYLON.Vector3(dx, dy, 0);
  25978. var position = normal.scale(thickness / 2);
  25979. var textureCoordinate = new BABYLON.Vector2(u, v);
  25980. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25981. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25982. positions.push(position.x, position.y, position.z);
  25983. normals.push(normal.x, normal.y, normal.z);
  25984. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25985. // And create indices for two triangles.
  25986. var nextI = (i + 1) % stride;
  25987. var nextJ = (j + 1) % stride;
  25988. indices.push(i * stride + j);
  25989. indices.push(i * stride + nextJ);
  25990. indices.push(nextI * stride + j);
  25991. indices.push(i * stride + nextJ);
  25992. indices.push(nextI * stride + nextJ);
  25993. indices.push(nextI * stride + j);
  25994. }
  25995. }
  25996. // Sides
  25997. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25998. // Result
  25999. var vertexData = new VertexData();
  26000. vertexData.indices = indices;
  26001. vertexData.positions = positions;
  26002. vertexData.normals = normals;
  26003. vertexData.uvs = uvs;
  26004. return vertexData;
  26005. };
  26006. /**
  26007. * Creates the VertexData of the LineSystem.
  26008. */
  26009. VertexData.CreateLineSystem = function (options) {
  26010. var indices = [];
  26011. var positions = [];
  26012. var lines = options.lines;
  26013. var idx = 0;
  26014. for (var l = 0; l < lines.length; l++) {
  26015. var points = lines[l];
  26016. for (var index = 0; index < points.length; index++) {
  26017. positions.push(points[index].x, points[index].y, points[index].z);
  26018. if (index > 0) {
  26019. indices.push(idx - 1);
  26020. indices.push(idx);
  26021. }
  26022. idx++;
  26023. }
  26024. }
  26025. var vertexData = new VertexData();
  26026. vertexData.indices = indices;
  26027. vertexData.positions = positions;
  26028. return vertexData;
  26029. };
  26030. /**
  26031. * Create the VertexData of the DashedLines.
  26032. */
  26033. VertexData.CreateDashedLines = function (options) {
  26034. var dashSize = options.dashSize || 3;
  26035. var gapSize = options.gapSize || 1;
  26036. var dashNb = options.dashNb || 200;
  26037. var points = options.points;
  26038. var positions = new Array();
  26039. var indices = new Array();
  26040. var curvect = BABYLON.Vector3.Zero();
  26041. var lg = 0;
  26042. var nb = 0;
  26043. var shft = 0;
  26044. var dashshft = 0;
  26045. var curshft = 0;
  26046. var idx = 0;
  26047. var i = 0;
  26048. for (i = 0; i < points.length - 1; i++) {
  26049. points[i + 1].subtractToRef(points[i], curvect);
  26050. lg += curvect.length();
  26051. }
  26052. shft = lg / dashNb;
  26053. dashshft = dashSize * shft / (dashSize + gapSize);
  26054. for (i = 0; i < points.length - 1; i++) {
  26055. points[i + 1].subtractToRef(points[i], curvect);
  26056. nb = Math.floor(curvect.length() / shft);
  26057. curvect.normalize();
  26058. for (var j = 0; j < nb; j++) {
  26059. curshft = shft * j;
  26060. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26061. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26062. indices.push(idx, idx + 1);
  26063. idx += 2;
  26064. }
  26065. }
  26066. // Result
  26067. var vertexData = new VertexData();
  26068. vertexData.positions = positions;
  26069. vertexData.indices = indices;
  26070. return vertexData;
  26071. };
  26072. /**
  26073. * Creates the VertexData of the Ground.
  26074. */
  26075. VertexData.CreateGround = function (options) {
  26076. var indices = [];
  26077. var positions = [];
  26078. var normals = [];
  26079. var uvs = [];
  26080. var row, col;
  26081. var width = options.width || 1;
  26082. var height = options.height || 1;
  26083. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26084. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26085. for (row = 0; row <= subdivisionsY; row++) {
  26086. for (col = 0; col <= subdivisionsX; col++) {
  26087. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26088. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26089. positions.push(position.x, position.y, position.z);
  26090. normals.push(normal.x, normal.y, normal.z);
  26091. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26092. }
  26093. }
  26094. for (row = 0; row < subdivisionsY; row++) {
  26095. for (col = 0; col < subdivisionsX; col++) {
  26096. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26097. indices.push(col + 1 + row * (subdivisionsX + 1));
  26098. indices.push(col + row * (subdivisionsX + 1));
  26099. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26100. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26101. indices.push(col + row * (subdivisionsX + 1));
  26102. }
  26103. }
  26104. // Result
  26105. var vertexData = new VertexData();
  26106. vertexData.indices = indices;
  26107. vertexData.positions = positions;
  26108. vertexData.normals = normals;
  26109. vertexData.uvs = uvs;
  26110. return vertexData;
  26111. };
  26112. /**
  26113. * Creates the VertexData of the TiledGround.
  26114. */
  26115. VertexData.CreateTiledGround = function (options) {
  26116. var xmin = options.xmin || -1.0;
  26117. var zmin = options.zmin || -1.0;
  26118. var xmax = options.xmax || 1.0;
  26119. var zmax = options.zmax || 1.0;
  26120. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26121. var precision = options.precision || { w: 1, h: 1 };
  26122. var indices = [];
  26123. var positions = [];
  26124. var normals = [];
  26125. var uvs = [];
  26126. var row, col, tileRow, tileCol;
  26127. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26128. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26129. precision.w = (precision.w < 1) ? 1 : precision.w;
  26130. precision.h = (precision.h < 1) ? 1 : precision.h;
  26131. var tileSize = {
  26132. 'w': (xmax - xmin) / subdivisions.w,
  26133. 'h': (zmax - zmin) / subdivisions.h
  26134. };
  26135. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26136. // Indices
  26137. var base = positions.length / 3;
  26138. var rowLength = precision.w + 1;
  26139. for (row = 0; row < precision.h; row++) {
  26140. for (col = 0; col < precision.w; col++) {
  26141. var square = [
  26142. base + col + row * rowLength,
  26143. base + (col + 1) + row * rowLength,
  26144. base + (col + 1) + (row + 1) * rowLength,
  26145. base + col + (row + 1) * rowLength
  26146. ];
  26147. indices.push(square[1]);
  26148. indices.push(square[2]);
  26149. indices.push(square[3]);
  26150. indices.push(square[0]);
  26151. indices.push(square[1]);
  26152. indices.push(square[3]);
  26153. }
  26154. }
  26155. // Position, normals and uvs
  26156. var position = BABYLON.Vector3.Zero();
  26157. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26158. for (row = 0; row <= precision.h; row++) {
  26159. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26160. for (col = 0; col <= precision.w; col++) {
  26161. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26162. position.y = 0;
  26163. positions.push(position.x, position.y, position.z);
  26164. normals.push(normal.x, normal.y, normal.z);
  26165. uvs.push(col / precision.w, row / precision.h);
  26166. }
  26167. }
  26168. }
  26169. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26170. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26171. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26172. }
  26173. }
  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 Ground designed from a heightmap.
  26184. */
  26185. VertexData.CreateGroundFromHeightMap = function (options) {
  26186. var indices = [];
  26187. var positions = [];
  26188. var normals = [];
  26189. var uvs = [];
  26190. var row, col;
  26191. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26192. // Vertices
  26193. for (row = 0; row <= options.subdivisions; row++) {
  26194. for (col = 0; col <= options.subdivisions; col++) {
  26195. 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));
  26196. // Compute height
  26197. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26198. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26199. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26200. var r = options.buffer[pos] / 255.0;
  26201. var g = options.buffer[pos + 1] / 255.0;
  26202. var b = options.buffer[pos + 2] / 255.0;
  26203. var gradient = r * filter.r + g * filter.g + b * filter.b;
  26204. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26205. // Add vertex
  26206. positions.push(position.x, position.y, position.z);
  26207. normals.push(0, 0, 0);
  26208. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26209. }
  26210. }
  26211. // Indices
  26212. for (row = 0; row < options.subdivisions; row++) {
  26213. for (col = 0; col < options.subdivisions; col++) {
  26214. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26215. indices.push(col + 1 + row * (options.subdivisions + 1));
  26216. indices.push(col + row * (options.subdivisions + 1));
  26217. indices.push(col + (row + 1) * (options.subdivisions + 1));
  26218. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26219. indices.push(col + row * (options.subdivisions + 1));
  26220. }
  26221. }
  26222. // Normals
  26223. VertexData.ComputeNormals(positions, indices, normals);
  26224. // Result
  26225. var vertexData = new VertexData();
  26226. vertexData.indices = indices;
  26227. vertexData.positions = positions;
  26228. vertexData.normals = normals;
  26229. vertexData.uvs = uvs;
  26230. return vertexData;
  26231. };
  26232. /**
  26233. * Creates the VertexData of the Plane.
  26234. */
  26235. VertexData.CreatePlane = function (options) {
  26236. var indices = [];
  26237. var positions = [];
  26238. var normals = [];
  26239. var uvs = [];
  26240. var width = options.width || options.size || 1;
  26241. var height = options.height || options.size || 1;
  26242. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26243. // Vertices
  26244. var halfWidth = width / 2.0;
  26245. var halfHeight = height / 2.0;
  26246. positions.push(-halfWidth, -halfHeight, 0);
  26247. normals.push(0, 0, -1.0);
  26248. uvs.push(0.0, 0.0);
  26249. positions.push(halfWidth, -halfHeight, 0);
  26250. normals.push(0, 0, -1.0);
  26251. uvs.push(1.0, 0.0);
  26252. positions.push(halfWidth, halfHeight, 0);
  26253. normals.push(0, 0, -1.0);
  26254. uvs.push(1.0, 1.0);
  26255. positions.push(-halfWidth, halfHeight, 0);
  26256. normals.push(0, 0, -1.0);
  26257. uvs.push(0.0, 1.0);
  26258. // Indices
  26259. indices.push(0);
  26260. indices.push(1);
  26261. indices.push(2);
  26262. indices.push(0);
  26263. indices.push(2);
  26264. indices.push(3);
  26265. // Sides
  26266. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26267. // Result
  26268. var vertexData = new VertexData();
  26269. vertexData.indices = indices;
  26270. vertexData.positions = positions;
  26271. vertexData.normals = normals;
  26272. vertexData.uvs = uvs;
  26273. return vertexData;
  26274. };
  26275. /**
  26276. * Creates the VertexData of the Disc or regular Polygon.
  26277. */
  26278. VertexData.CreateDisc = function (options) {
  26279. var positions = [];
  26280. var indices = [];
  26281. var normals = [];
  26282. var uvs = [];
  26283. var radius = options.radius || 0.5;
  26284. var tessellation = options.tessellation || 64;
  26285. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26286. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26287. // positions and uvs
  26288. positions.push(0, 0, 0); // disc center first
  26289. uvs.push(0.5, 0.5);
  26290. var theta = Math.PI * 2 * arc;
  26291. var step = theta / tessellation;
  26292. for (var a = 0; a < theta; a += step) {
  26293. var x = Math.cos(a);
  26294. var y = Math.sin(a);
  26295. var u = (x + 1) / 2;
  26296. var v = (1 - y) / 2;
  26297. positions.push(radius * x, radius * y, 0);
  26298. uvs.push(u, v);
  26299. }
  26300. if (arc === 1) {
  26301. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26302. uvs.push(uvs[2], uvs[3]);
  26303. }
  26304. //indices
  26305. var vertexNb = positions.length / 3;
  26306. for (var i = 1; i < vertexNb - 1; i++) {
  26307. indices.push(i + 1, 0, i);
  26308. }
  26309. // result
  26310. VertexData.ComputeNormals(positions, indices, normals);
  26311. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26312. var vertexData = new VertexData();
  26313. vertexData.indices = indices;
  26314. vertexData.positions = positions;
  26315. vertexData.normals = normals;
  26316. vertexData.uvs = uvs;
  26317. return vertexData;
  26318. };
  26319. /**
  26320. * Re-creates the VertexData of the Polygon for sideOrientation.
  26321. */
  26322. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26323. var faceUV = fUV || new Array(3);
  26324. var faceColors = fColors;
  26325. var colors = [];
  26326. // default face colors and UV if undefined
  26327. for (var f = 0; f < 3; f++) {
  26328. if (faceUV[f] === undefined) {
  26329. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26330. }
  26331. if (faceColors && faceColors[f] === undefined) {
  26332. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26333. }
  26334. }
  26335. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26336. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26337. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26338. var indices = polygon.getIndices();
  26339. // set face colours and textures
  26340. var idx = 0;
  26341. var face = 0;
  26342. for (var index = 0; index < normals.length; index += 3) {
  26343. //Edge Face no. 1
  26344. if (Math.abs(normals[index + 1]) == 0) {
  26345. face = 1;
  26346. }
  26347. //Top Face no. 0
  26348. if (normals[index + 1] == 1) {
  26349. face = 0;
  26350. }
  26351. //Bottom Face no. 2
  26352. if (normals[index + 1] == -1) {
  26353. face = 2;
  26354. }
  26355. idx = index / 3;
  26356. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26357. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26358. if (faceColors) {
  26359. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26360. }
  26361. }
  26362. // sides
  26363. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26364. // Result
  26365. var vertexData = new VertexData();
  26366. vertexData.indices = indices;
  26367. vertexData.positions = positions;
  26368. vertexData.normals = normals;
  26369. vertexData.uvs = uvs;
  26370. if (faceColors) {
  26371. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26372. vertexData.colors = totalColors;
  26373. }
  26374. return vertexData;
  26375. };
  26376. /**
  26377. * Creates the VertexData of the IcoSphere.
  26378. */
  26379. VertexData.CreateIcoSphere = function (options) {
  26380. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26381. var radius = options.radius || 1;
  26382. var flat = (options.flat === undefined) ? true : options.flat;
  26383. var subdivisions = options.subdivisions || 4;
  26384. var radiusX = options.radiusX || radius;
  26385. var radiusY = options.radiusY || radius;
  26386. var radiusZ = options.radiusZ || radius;
  26387. var t = (1 + Math.sqrt(5)) / 2;
  26388. // 12 vertex x,y,z
  26389. var ico_vertices = [
  26390. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26391. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26392. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26393. ];
  26394. // index of 3 vertex makes a face of icopshere
  26395. var ico_indices = [
  26396. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26397. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26398. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26399. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26400. ];
  26401. // vertex for uv have aliased position, not for UV
  26402. var vertices_unalias_id = [
  26403. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26404. // vertex alias
  26405. 0,
  26406. 2,
  26407. 3,
  26408. 3,
  26409. 3,
  26410. 4,
  26411. 7,
  26412. 8,
  26413. 9,
  26414. 9,
  26415. 10,
  26416. 11 // 23: B + 12
  26417. ];
  26418. // uv as integer step (not pixels !)
  26419. var ico_vertexuv = [
  26420. 5, 1, 3, 1, 6, 4, 0, 0,
  26421. 5, 3, 4, 2, 2, 2, 4, 0,
  26422. 2, 0, 1, 1, 6, 0, 6, 2,
  26423. // vertex alias (for same vertex on different faces)
  26424. 0, 4,
  26425. 3, 3,
  26426. 4, 4,
  26427. 3, 1,
  26428. 4, 2,
  26429. 4, 4,
  26430. 0, 2,
  26431. 1, 1,
  26432. 2, 2,
  26433. 3, 3,
  26434. 1, 3,
  26435. 2, 4 // 23: B + 12
  26436. ];
  26437. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26438. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26439. // First island of uv mapping
  26440. // v = 4h 3+ 2
  26441. // v = 3h 9+ 4
  26442. // v = 2h 9+ 5 B
  26443. // v = 1h 9 1 0
  26444. // v = 0h 3 8 7 A
  26445. // u = 0 1 2 3 4 5 6 *a
  26446. // Second island of uv mapping
  26447. // v = 4h 0+ B+ 4+
  26448. // v = 3h A+ 2+
  26449. // v = 2h 7+ 6 3+
  26450. // v = 1h 8+ 3+
  26451. // v = 0h
  26452. // u = 0 1 2 3 4 5 6 *a
  26453. // Face layout on texture UV mapping
  26454. // ============
  26455. // \ 4 /\ 16 / ======
  26456. // \ / \ / /\ 11 /
  26457. // \/ 7 \/ / \ /
  26458. // ======= / 10 \/
  26459. // /\ 17 /\ =======
  26460. // / \ / \ \ 15 /\
  26461. // / 8 \/ 12 \ \ / \
  26462. // ============ \/ 6 \
  26463. // \ 18 /\ ============
  26464. // \ / \ \ 5 /\ 0 /
  26465. // \/ 13 \ \ / \ /
  26466. // ======= \/ 1 \/
  26467. // =============
  26468. // /\ 19 /\ 2 /\
  26469. // / \ / \ / \
  26470. // / 14 \/ 9 \/ 3 \
  26471. // ===================
  26472. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26473. var ustep = 138 / 1024;
  26474. var vstep = 239 / 1024;
  26475. var uoffset = 60 / 1024;
  26476. var voffset = 26 / 1024;
  26477. // Second island should have margin, not to touch the first island
  26478. // avoid any borderline artefact in pixel rounding
  26479. var island_u_offset = -40 / 1024;
  26480. var island_v_offset = +20 / 1024;
  26481. // face is either island 0 or 1 :
  26482. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26483. var island = [
  26484. 0, 0, 0, 0, 1,
  26485. 0, 0, 1, 1, 0,
  26486. 0, 0, 1, 1, 0,
  26487. 0, 1, 1, 1, 0 // 15 - 19
  26488. ];
  26489. var indices = [];
  26490. var positions = [];
  26491. var normals = [];
  26492. var uvs = [];
  26493. var current_indice = 0;
  26494. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26495. var face_vertex_pos = new Array(3);
  26496. var face_vertex_uv = new Array(3);
  26497. var v012;
  26498. for (v012 = 0; v012 < 3; v012++) {
  26499. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26500. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26501. }
  26502. // create all with normals
  26503. for (var face = 0; face < 20; face++) {
  26504. // 3 vertex per face
  26505. for (v012 = 0; v012 < 3; v012++) {
  26506. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26507. var v_id = ico_indices[3 * face + v012];
  26508. // vertex have 3D position (x,y,z)
  26509. 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]);
  26510. // Normalize to get normal, then scale to radius
  26511. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26512. // uv Coordinates from vertex ID
  26513. 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);
  26514. }
  26515. // Subdivide the face (interpolate pos, norm, uv)
  26516. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26517. // - norm is linear interpolation of vertex corner normal
  26518. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26519. // - uv is linear interpolation
  26520. //
  26521. // Topology is as below for sub-divide by 2
  26522. // vertex shown as v0,v1,v2
  26523. // interp index is i1 to progress in range [v0,v1[
  26524. // interp index is i2 to progress in range [v0,v2[
  26525. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26526. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26527. //
  26528. //
  26529. // i2 v2
  26530. // ^ ^
  26531. // / / \
  26532. // / / \
  26533. // / / \
  26534. // / / (0,1) \
  26535. // / #---------\
  26536. // / / \ (0,0)'/ \
  26537. // / / \ / \
  26538. // / / \ / \
  26539. // / / (0,0) \ / (1,0) \
  26540. // / #---------#---------\
  26541. // v0 v1
  26542. //
  26543. // --------------------> i1
  26544. //
  26545. // interp of (i1,i2):
  26546. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26547. // along i1 : lerp(x0,x1, i1/(S-i2))
  26548. //
  26549. // centroid of triangle is needed to get help normal computation
  26550. // (c1,c2) are used for centroid location
  26551. var interp_vertex = function (i1, i2, c1, c2) {
  26552. // vertex is interpolated from
  26553. // - face_vertex_pos[0..2]
  26554. // - face_vertex_uv[0..2]
  26555. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26556. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26557. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26558. pos_interp.normalize();
  26559. var vertex_normal;
  26560. if (flat) {
  26561. // in flat mode, recalculate normal as face centroid normal
  26562. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26563. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26564. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26565. }
  26566. else {
  26567. // in smooth mode, recalculate normal from each single vertex position
  26568. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26569. }
  26570. // Vertex normal need correction due to X,Y,Z radius scaling
  26571. vertex_normal.x /= radiusX;
  26572. vertex_normal.y /= radiusY;
  26573. vertex_normal.z /= radiusZ;
  26574. vertex_normal.normalize();
  26575. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26576. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26577. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26578. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26579. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26580. uvs.push(uv_interp.x, uv_interp.y);
  26581. // push each vertex has member of a face
  26582. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26583. indices.push(current_indice);
  26584. current_indice++;
  26585. };
  26586. for (var i2 = 0; i2 < subdivisions; i2++) {
  26587. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26588. // face : (i1,i2) for /\ :
  26589. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26590. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26591. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26592. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26593. if (i1 + i2 + 1 < subdivisions) {
  26594. // face : (i1,i2)' for \/ :
  26595. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26596. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26597. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26598. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26599. }
  26600. }
  26601. }
  26602. }
  26603. // Sides
  26604. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26605. // Result
  26606. var vertexData = new VertexData();
  26607. vertexData.indices = indices;
  26608. vertexData.positions = positions;
  26609. vertexData.normals = normals;
  26610. vertexData.uvs = uvs;
  26611. return vertexData;
  26612. };
  26613. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26614. /**
  26615. * Creates the VertexData of the Polyhedron.
  26616. */
  26617. VertexData.CreatePolyhedron = function (options) {
  26618. // provided polyhedron types :
  26619. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26620. // 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)
  26621. var polyhedra = [];
  26622. 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]] };
  26623. 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]] };
  26624. polyhedra[2] = {
  26625. 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]],
  26626. 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]]
  26627. };
  26628. polyhedra[3] = {
  26629. 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]],
  26630. 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]]
  26631. };
  26632. polyhedra[4] = {
  26633. 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]],
  26634. 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]]
  26635. };
  26636. 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]] };
  26637. 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]] };
  26638. 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]] };
  26639. 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]] };
  26640. 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]] };
  26641. 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]] };
  26642. 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]] };
  26643. 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]] };
  26644. 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]] };
  26645. polyhedra[14] = {
  26646. 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]],
  26647. 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]]
  26648. };
  26649. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26650. var size = options.size;
  26651. var sizeX = options.sizeX || size || 1;
  26652. var sizeY = options.sizeY || size || 1;
  26653. var sizeZ = options.sizeZ || size || 1;
  26654. var data = options.custom || polyhedra[type];
  26655. var nbfaces = data.face.length;
  26656. var faceUV = options.faceUV || new Array(nbfaces);
  26657. var faceColors = options.faceColors;
  26658. var flat = (options.flat === undefined) ? true : options.flat;
  26659. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26660. var positions = [];
  26661. var indices = [];
  26662. var normals = [];
  26663. var uvs = [];
  26664. var colors = [];
  26665. var index = 0;
  26666. var faceIdx = 0; // face cursor in the array "indexes"
  26667. var indexes = [];
  26668. var i = 0;
  26669. var f = 0;
  26670. var u, v, ang, x, y, tmp;
  26671. // default face colors and UV if undefined
  26672. if (flat) {
  26673. for (f = 0; f < nbfaces; f++) {
  26674. if (faceColors && faceColors[f] === undefined) {
  26675. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26676. }
  26677. if (faceUV && faceUV[f] === undefined) {
  26678. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26679. }
  26680. }
  26681. }
  26682. if (!flat) {
  26683. for (i = 0; i < data.vertex.length; i++) {
  26684. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26685. uvs.push(0, 0);
  26686. }
  26687. for (f = 0; f < nbfaces; f++) {
  26688. for (i = 0; i < data.face[f].length - 2; i++) {
  26689. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26690. }
  26691. }
  26692. }
  26693. else {
  26694. for (f = 0; f < nbfaces; f++) {
  26695. var fl = data.face[f].length; // number of vertices of the current face
  26696. ang = 2 * Math.PI / fl;
  26697. x = 0.5 * Math.tan(ang / 2);
  26698. y = 0.5;
  26699. // positions, uvs, colors
  26700. for (i = 0; i < fl; i++) {
  26701. // positions
  26702. 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);
  26703. indexes.push(index);
  26704. index++;
  26705. // uvs
  26706. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26707. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26708. uvs.push(u, v);
  26709. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26710. y = x * Math.sin(ang) + y * Math.cos(ang);
  26711. x = tmp;
  26712. // colors
  26713. if (faceColors) {
  26714. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26715. }
  26716. }
  26717. // indices from indexes
  26718. for (i = 0; i < fl - 2; i++) {
  26719. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26720. }
  26721. faceIdx += fl;
  26722. }
  26723. }
  26724. VertexData.ComputeNormals(positions, indices, normals);
  26725. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26726. var vertexData = new VertexData();
  26727. vertexData.positions = positions;
  26728. vertexData.indices = indices;
  26729. vertexData.normals = normals;
  26730. vertexData.uvs = uvs;
  26731. if (faceColors && flat) {
  26732. vertexData.colors = colors;
  26733. }
  26734. return vertexData;
  26735. };
  26736. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26737. /**
  26738. * Creates the VertexData of the Torus Knot.
  26739. */
  26740. VertexData.CreateTorusKnot = function (options) {
  26741. var indices = [];
  26742. var positions = [];
  26743. var normals = [];
  26744. var uvs = [];
  26745. var radius = options.radius || 2;
  26746. var tube = options.tube || 0.5;
  26747. var radialSegments = options.radialSegments || 32;
  26748. var tubularSegments = options.tubularSegments || 32;
  26749. var p = options.p || 2;
  26750. var q = options.q || 3;
  26751. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26752. // Helper
  26753. var getPos = function (angle) {
  26754. var cu = Math.cos(angle);
  26755. var su = Math.sin(angle);
  26756. var quOverP = q / p * angle;
  26757. var cs = Math.cos(quOverP);
  26758. var tx = radius * (2 + cs) * 0.5 * cu;
  26759. var ty = radius * (2 + cs) * su * 0.5;
  26760. var tz = radius * Math.sin(quOverP) * 0.5;
  26761. return new BABYLON.Vector3(tx, ty, tz);
  26762. };
  26763. // Vertices
  26764. var i;
  26765. var j;
  26766. for (i = 0; i <= radialSegments; i++) {
  26767. var modI = i % radialSegments;
  26768. var u = modI / radialSegments * 2 * p * Math.PI;
  26769. var p1 = getPos(u);
  26770. var p2 = getPos(u + 0.01);
  26771. var tang = p2.subtract(p1);
  26772. var n = p2.add(p1);
  26773. var bitan = BABYLON.Vector3.Cross(tang, n);
  26774. n = BABYLON.Vector3.Cross(bitan, tang);
  26775. bitan.normalize();
  26776. n.normalize();
  26777. for (j = 0; j < tubularSegments; j++) {
  26778. var modJ = j % tubularSegments;
  26779. var v = modJ / tubularSegments * 2 * Math.PI;
  26780. var cx = -tube * Math.cos(v);
  26781. var cy = tube * Math.sin(v);
  26782. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26783. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26784. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26785. uvs.push(i / radialSegments);
  26786. uvs.push(j / tubularSegments);
  26787. }
  26788. }
  26789. for (i = 0; i < radialSegments; i++) {
  26790. for (j = 0; j < tubularSegments; j++) {
  26791. var jNext = (j + 1) % tubularSegments;
  26792. var a = i * tubularSegments + j;
  26793. var b = (i + 1) * tubularSegments + j;
  26794. var c = (i + 1) * tubularSegments + jNext;
  26795. var d = i * tubularSegments + jNext;
  26796. indices.push(d);
  26797. indices.push(b);
  26798. indices.push(a);
  26799. indices.push(d);
  26800. indices.push(c);
  26801. indices.push(b);
  26802. }
  26803. }
  26804. // Normals
  26805. VertexData.ComputeNormals(positions, indices, normals);
  26806. // Sides
  26807. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26808. // Result
  26809. var vertexData = new VertexData();
  26810. vertexData.indices = indices;
  26811. vertexData.positions = positions;
  26812. vertexData.normals = normals;
  26813. vertexData.uvs = uvs;
  26814. return vertexData;
  26815. };
  26816. // Tools
  26817. /**
  26818. * @param {any} - positions (number[] or Float32Array)
  26819. * @param {any} - indices (number[] or Uint16Array)
  26820. * @param {any} - normals (number[] or Float32Array)
  26821. * options (optional) :
  26822. * facetPositions : optional array of facet positions (vector3)
  26823. * facetNormals : optional array of facet normals (vector3)
  26824. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26825. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26826. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26827. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26828. * bInfo : optional bounding info, required for facetPartitioning computation
  26829. */
  26830. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26831. // temporary scalar variables
  26832. var index = 0; // facet index
  26833. var p1p2x = 0.0; // p1p2 vector x coordinate
  26834. var p1p2y = 0.0; // p1p2 vector y coordinate
  26835. var p1p2z = 0.0; // p1p2 vector z coordinate
  26836. var p3p2x = 0.0; // p3p2 vector x coordinate
  26837. var p3p2y = 0.0; // p3p2 vector y coordinate
  26838. var p3p2z = 0.0; // p3p2 vector z coordinate
  26839. var faceNormalx = 0.0; // facet normal x coordinate
  26840. var faceNormaly = 0.0; // facet normal y coordinate
  26841. var faceNormalz = 0.0; // facet normal z coordinate
  26842. var length = 0.0; // facet normal length before normalization
  26843. var v1x = 0; // vector1 x index in the positions array
  26844. var v1y = 0; // vector1 y index in the positions array
  26845. var v1z = 0; // vector1 z index in the positions array
  26846. var v2x = 0; // vector2 x index in the positions array
  26847. var v2y = 0; // vector2 y index in the positions array
  26848. var v2z = 0; // vector2 z index in the positions array
  26849. var v3x = 0; // vector3 x index in the positions array
  26850. var v3y = 0; // vector3 y index in the positions array
  26851. var v3z = 0; // vector3 z index in the positions array
  26852. var computeFacetNormals = false;
  26853. var computeFacetPositions = false;
  26854. var computeFacetPartitioning = false;
  26855. var faceNormalSign = 1;
  26856. if (options) {
  26857. computeFacetNormals = (options.facetNormals) ? true : false;
  26858. computeFacetPositions = (options.facetPositions) ? true : false;
  26859. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26860. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26861. }
  26862. // facetPartitioning reinit if needed
  26863. if (computeFacetPartitioning) {
  26864. var ox = 0; // X partitioning index for facet position
  26865. var oy = 0; // Y partinioning index for facet position
  26866. var oz = 0; // Z partinioning index for facet position
  26867. var b1x = 0; // X partitioning index for facet v1 vertex
  26868. var b1y = 0; // Y partitioning index for facet v1 vertex
  26869. var b1z = 0; // z partitioning index for facet v1 vertex
  26870. var b2x = 0; // X partitioning index for facet v2 vertex
  26871. var b2y = 0; // Y partitioning index for facet v2 vertex
  26872. var b2z = 0; // Z partitioning index for facet v2 vertex
  26873. var b3x = 0; // X partitioning index for facet v3 vertex
  26874. var b3y = 0; // Y partitioning index for facet v3 vertex
  26875. var b3z = 0; // Z partitioning index for facet v3 vertex
  26876. var block_idx_o = 0; // facet barycenter block index
  26877. var block_idx_v1 = 0; // v1 vertex block index
  26878. var block_idx_v2 = 0; // v2 vertex block index
  26879. var block_idx_v3 = 0; // v3 vertex block index
  26880. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26881. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26882. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26883. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26884. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26885. var subSq = options.subDiv.max * options.subDiv.max;
  26886. options.facetPartitioning.length = 0;
  26887. }
  26888. // reset the normals
  26889. for (index = 0; index < positions.length; index++) {
  26890. normals[index] = 0.0;
  26891. }
  26892. // Loop : 1 indice triplet = 1 facet
  26893. var nbFaces = indices.length / 3;
  26894. for (index = 0; index < nbFaces; index++) {
  26895. // get the indexes of the coordinates of each vertex of the facet
  26896. v1x = indices[index * 3] * 3;
  26897. v1y = v1x + 1;
  26898. v1z = v1x + 2;
  26899. v2x = indices[index * 3 + 1] * 3;
  26900. v2y = v2x + 1;
  26901. v2z = v2x + 2;
  26902. v3x = indices[index * 3 + 2] * 3;
  26903. v3y = v3x + 1;
  26904. v3z = v3x + 2;
  26905. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26906. p1p2y = positions[v1y] - positions[v2y];
  26907. p1p2z = positions[v1z] - positions[v2z];
  26908. p3p2x = positions[v3x] - positions[v2x];
  26909. p3p2y = positions[v3y] - positions[v2y];
  26910. p3p2z = positions[v3z] - positions[v2z];
  26911. // compute the face normal with the cross product
  26912. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26913. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26914. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26915. // normalize this normal and store it in the array facetData
  26916. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26917. length = (length === 0) ? 1.0 : length;
  26918. faceNormalx /= length;
  26919. faceNormaly /= length;
  26920. faceNormalz /= length;
  26921. if (computeFacetNormals) {
  26922. options.facetNormals[index].x = faceNormalx;
  26923. options.facetNormals[index].y = faceNormaly;
  26924. options.facetNormals[index].z = faceNormalz;
  26925. }
  26926. if (computeFacetPositions) {
  26927. // compute and the facet barycenter coordinates in the array facetPositions
  26928. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26929. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26930. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26931. }
  26932. if (computeFacetPartitioning) {
  26933. // store the facet indexes in arrays in the main facetPartitioning array :
  26934. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26935. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26936. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26937. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26938. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26939. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26940. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26941. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26942. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26943. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26944. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26945. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26946. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26947. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26948. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26949. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26950. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26951. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26952. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26953. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26954. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26955. // push each facet index in each block containing the vertex
  26956. options.facetPartitioning[block_idx_v1].push(index);
  26957. if (block_idx_v2 != block_idx_v1) {
  26958. options.facetPartitioning[block_idx_v2].push(index);
  26959. }
  26960. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26961. options.facetPartitioning[block_idx_v3].push(index);
  26962. }
  26963. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26964. options.facetPartitioning[block_idx_o].push(index);
  26965. }
  26966. }
  26967. // compute the normals anyway
  26968. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26969. normals[v1y] += faceNormaly;
  26970. normals[v1z] += faceNormalz;
  26971. normals[v2x] += faceNormalx;
  26972. normals[v2y] += faceNormaly;
  26973. normals[v2z] += faceNormalz;
  26974. normals[v3x] += faceNormalx;
  26975. normals[v3y] += faceNormaly;
  26976. normals[v3z] += faceNormalz;
  26977. }
  26978. // last normalization of each normal
  26979. for (index = 0; index < normals.length / 3; index++) {
  26980. faceNormalx = normals[index * 3];
  26981. faceNormaly = normals[index * 3 + 1];
  26982. faceNormalz = normals[index * 3 + 2];
  26983. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26984. length = (length === 0) ? 1.0 : length;
  26985. faceNormalx /= length;
  26986. faceNormaly /= length;
  26987. faceNormalz /= length;
  26988. normals[index * 3] = faceNormalx;
  26989. normals[index * 3 + 1] = faceNormaly;
  26990. normals[index * 3 + 2] = faceNormalz;
  26991. }
  26992. };
  26993. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26994. var li = indices.length;
  26995. var ln = normals.length;
  26996. var i;
  26997. var n;
  26998. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26999. switch (sideOrientation) {
  27000. case BABYLON.Mesh.FRONTSIDE:
  27001. // nothing changed
  27002. break;
  27003. case BABYLON.Mesh.BACKSIDE:
  27004. var tmp;
  27005. // indices
  27006. for (i = 0; i < li; i += 3) {
  27007. tmp = indices[i];
  27008. indices[i] = indices[i + 2];
  27009. indices[i + 2] = tmp;
  27010. }
  27011. // normals
  27012. for (n = 0; n < ln; n++) {
  27013. normals[n] = -normals[n];
  27014. }
  27015. break;
  27016. case BABYLON.Mesh.DOUBLESIDE:
  27017. // positions
  27018. var lp = positions.length;
  27019. var l = lp / 3;
  27020. for (var p = 0; p < lp; p++) {
  27021. positions[lp + p] = positions[p];
  27022. }
  27023. // indices
  27024. for (i = 0; i < li; i += 3) {
  27025. indices[i + li] = indices[i + 2] + l;
  27026. indices[i + 1 + li] = indices[i + 1] + l;
  27027. indices[i + 2 + li] = indices[i] + l;
  27028. }
  27029. // normals
  27030. for (n = 0; n < ln; n++) {
  27031. normals[ln + n] = -normals[n];
  27032. }
  27033. // uvs
  27034. var lu = uvs.length;
  27035. var u = 0;
  27036. for (u = 0; u < lu; u++) {
  27037. uvs[u + lu] = uvs[u];
  27038. }
  27039. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27040. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27041. u = 0;
  27042. for (i = 0; i < lu / 2; i++) {
  27043. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  27044. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  27045. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  27046. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  27047. u += 2;
  27048. }
  27049. break;
  27050. }
  27051. };
  27052. /**
  27053. * Creates a new VertexData from the imported parameters.
  27054. */
  27055. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27056. var vertexData = new VertexData();
  27057. // positions
  27058. var positions = parsedVertexData.positions;
  27059. if (positions) {
  27060. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27061. }
  27062. // normals
  27063. var normals = parsedVertexData.normals;
  27064. if (normals) {
  27065. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27066. }
  27067. // tangents
  27068. var tangents = parsedVertexData.tangents;
  27069. if (tangents) {
  27070. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27071. }
  27072. // uvs
  27073. var uvs = parsedVertexData.uvs;
  27074. if (uvs) {
  27075. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27076. }
  27077. // uv2s
  27078. var uv2s = parsedVertexData.uv2s;
  27079. if (uv2s) {
  27080. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27081. }
  27082. // uv3s
  27083. var uv3s = parsedVertexData.uv3s;
  27084. if (uv3s) {
  27085. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27086. }
  27087. // uv4s
  27088. var uv4s = parsedVertexData.uv4s;
  27089. if (uv4s) {
  27090. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27091. }
  27092. // uv5s
  27093. var uv5s = parsedVertexData.uv5s;
  27094. if (uv5s) {
  27095. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27096. }
  27097. // uv6s
  27098. var uv6s = parsedVertexData.uv6s;
  27099. if (uv6s) {
  27100. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27101. }
  27102. // colors
  27103. var colors = parsedVertexData.colors;
  27104. if (colors) {
  27105. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27106. }
  27107. // matricesIndices
  27108. var matricesIndices = parsedVertexData.matricesIndices;
  27109. if (matricesIndices) {
  27110. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27111. }
  27112. // matricesWeights
  27113. var matricesWeights = parsedVertexData.matricesWeights;
  27114. if (matricesWeights) {
  27115. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27116. }
  27117. // indices
  27118. var indices = parsedVertexData.indices;
  27119. if (indices) {
  27120. vertexData.indices = indices;
  27121. }
  27122. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27123. };
  27124. return VertexData;
  27125. }());
  27126. BABYLON.VertexData = VertexData;
  27127. })(BABYLON || (BABYLON = {}));
  27128. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27129. var BABYLON;
  27130. (function (BABYLON) {
  27131. var Geometry = (function () {
  27132. function Geometry(id, scene, vertexData, updatable, mesh) {
  27133. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27134. this._totalVertices = 0;
  27135. this._isDisposed = false;
  27136. this.id = id;
  27137. this._engine = scene.getEngine();
  27138. this._meshes = [];
  27139. this._scene = scene;
  27140. //Init vertex buffer cache
  27141. this._vertexBuffers = {};
  27142. this._indices = [];
  27143. // vertexData
  27144. if (vertexData) {
  27145. this.setAllVerticesData(vertexData, updatable);
  27146. }
  27147. else {
  27148. this._totalVertices = 0;
  27149. this._indices = [];
  27150. }
  27151. if (this._engine.getCaps().vertexArrayObject) {
  27152. this._vertexArrayObjects = {};
  27153. }
  27154. // applyToMesh
  27155. if (mesh) {
  27156. if (mesh.getClassName() === "LinesMesh") {
  27157. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  27158. this.updateExtend();
  27159. }
  27160. this.applyToMesh(mesh);
  27161. mesh.computeWorldMatrix(true);
  27162. }
  27163. }
  27164. Object.defineProperty(Geometry.prototype, "boundingBias", {
  27165. /**
  27166. * 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
  27167. * @returns The Bias Vector
  27168. */
  27169. get: function () {
  27170. return this._boundingBias;
  27171. },
  27172. set: function (value) {
  27173. if (this._boundingBias && this._boundingBias.equals(value)) {
  27174. return;
  27175. }
  27176. this._boundingBias = value.clone();
  27177. this.updateBoundingInfo(true, null);
  27178. },
  27179. enumerable: true,
  27180. configurable: true
  27181. });
  27182. Object.defineProperty(Geometry.prototype, "extend", {
  27183. get: function () {
  27184. return this._extend;
  27185. },
  27186. enumerable: true,
  27187. configurable: true
  27188. });
  27189. Geometry.prototype.getScene = function () {
  27190. return this._scene;
  27191. };
  27192. Geometry.prototype.getEngine = function () {
  27193. return this._engine;
  27194. };
  27195. Geometry.prototype.isReady = function () {
  27196. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27197. };
  27198. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  27199. get: function () {
  27200. for (var index = 0; index < this._meshes.length; index++) {
  27201. if (!this._meshes[index].doNotSerialize) {
  27202. return false;
  27203. }
  27204. }
  27205. return true;
  27206. },
  27207. enumerable: true,
  27208. configurable: true
  27209. });
  27210. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27211. vertexData.applyToGeometry(this, updatable);
  27212. this.notifyUpdate();
  27213. };
  27214. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27215. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27216. this.setVerticesBuffer(buffer);
  27217. };
  27218. Geometry.prototype.removeVerticesData = function (kind) {
  27219. if (this._vertexBuffers[kind]) {
  27220. this._vertexBuffers[kind].dispose();
  27221. delete this._vertexBuffers[kind];
  27222. }
  27223. };
  27224. Geometry.prototype.setVerticesBuffer = function (buffer) {
  27225. var kind = buffer.getKind();
  27226. if (this._vertexBuffers[kind]) {
  27227. this._vertexBuffers[kind].dispose();
  27228. }
  27229. this._vertexBuffers[kind] = buffer;
  27230. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27231. var data = buffer.getData();
  27232. var stride = buffer.getStrideSize();
  27233. this._totalVertices = data.length / stride;
  27234. this.updateExtend(data, stride);
  27235. this._resetPointsArrayCache();
  27236. var meshes = this._meshes;
  27237. var numOfMeshes = meshes.length;
  27238. for (var index = 0; index < numOfMeshes; index++) {
  27239. var mesh = meshes[index];
  27240. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27241. mesh._createGlobalSubMesh();
  27242. mesh.computeWorldMatrix(true);
  27243. }
  27244. }
  27245. this.notifyUpdate(kind);
  27246. if (this._vertexArrayObjects) {
  27247. this._disposeVertexArrayObjects();
  27248. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  27249. }
  27250. };
  27251. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27252. var vertexBuffer = this.getVertexBuffer(kind);
  27253. if (!vertexBuffer) {
  27254. return;
  27255. }
  27256. vertexBuffer.updateDirectly(data, offset);
  27257. this.notifyUpdate(kind);
  27258. };
  27259. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27260. var vertexBuffer = this.getVertexBuffer(kind);
  27261. if (!vertexBuffer) {
  27262. return;
  27263. }
  27264. vertexBuffer.update(data);
  27265. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27266. var stride = vertexBuffer.getStrideSize();
  27267. this._totalVertices = data.length / stride;
  27268. this.updateBoundingInfo(updateExtends, data);
  27269. }
  27270. this.notifyUpdate(kind);
  27271. };
  27272. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27273. if (updateExtends) {
  27274. this.updateExtend(data);
  27275. }
  27276. var meshes = this._meshes;
  27277. var numOfMeshes = meshes.length;
  27278. this._resetPointsArrayCache();
  27279. for (var index = 0; index < numOfMeshes; index++) {
  27280. var mesh = meshes[index];
  27281. if (updateExtends) {
  27282. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27283. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27284. var subMesh = mesh.subMeshes[subIndex];
  27285. subMesh.refreshBoundingInfo();
  27286. }
  27287. }
  27288. }
  27289. };
  27290. Geometry.prototype._bind = function (effect, indexToBind) {
  27291. if (indexToBind === void 0) { indexToBind = undefined; }
  27292. if (indexToBind === undefined) {
  27293. indexToBind = this._indexBuffer;
  27294. }
  27295. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27296. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27297. return;
  27298. }
  27299. // Using VAO
  27300. if (!this._vertexArrayObjects[effect.key]) {
  27301. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27302. }
  27303. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27304. };
  27305. Geometry.prototype.getTotalVertices = function () {
  27306. if (!this.isReady()) {
  27307. return 0;
  27308. }
  27309. return this._totalVertices;
  27310. };
  27311. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27312. var vertexBuffer = this.getVertexBuffer(kind);
  27313. if (!vertexBuffer) {
  27314. return null;
  27315. }
  27316. var orig = vertexBuffer.getData();
  27317. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27318. return orig;
  27319. }
  27320. else {
  27321. var len = orig.length;
  27322. var copy = [];
  27323. for (var i = 0; i < len; i++) {
  27324. copy.push(orig[i]);
  27325. }
  27326. return copy;
  27327. }
  27328. };
  27329. Geometry.prototype.getVertexBuffer = function (kind) {
  27330. if (!this.isReady()) {
  27331. return null;
  27332. }
  27333. return this._vertexBuffers[kind];
  27334. };
  27335. Geometry.prototype.getVertexBuffers = function () {
  27336. if (!this.isReady()) {
  27337. return null;
  27338. }
  27339. return this._vertexBuffers;
  27340. };
  27341. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27342. if (!this._vertexBuffers) {
  27343. if (this._delayInfo) {
  27344. return this._delayInfo.indexOf(kind) !== -1;
  27345. }
  27346. return false;
  27347. }
  27348. return this._vertexBuffers[kind] !== undefined;
  27349. };
  27350. Geometry.prototype.getVerticesDataKinds = function () {
  27351. var result = [];
  27352. var kind;
  27353. if (!this._vertexBuffers && this._delayInfo) {
  27354. for (kind in this._delayInfo) {
  27355. result.push(kind);
  27356. }
  27357. }
  27358. else {
  27359. for (kind in this._vertexBuffers) {
  27360. result.push(kind);
  27361. }
  27362. }
  27363. return result;
  27364. };
  27365. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27366. if (this._indexBuffer) {
  27367. this._engine._releaseBuffer(this._indexBuffer);
  27368. }
  27369. this._disposeVertexArrayObjects();
  27370. this._indices = indices;
  27371. if (this._meshes.length !== 0 && this._indices) {
  27372. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27373. }
  27374. if (totalVertices !== undefined) {
  27375. this._totalVertices = totalVertices;
  27376. }
  27377. var meshes = this._meshes;
  27378. var numOfMeshes = meshes.length;
  27379. for (var index = 0; index < numOfMeshes; index++) {
  27380. meshes[index]._createGlobalSubMesh();
  27381. }
  27382. this.notifyUpdate();
  27383. };
  27384. Geometry.prototype.getTotalIndices = function () {
  27385. if (!this.isReady()) {
  27386. return 0;
  27387. }
  27388. return this._indices.length;
  27389. };
  27390. Geometry.prototype.getIndices = function (copyWhenShared) {
  27391. if (!this.isReady()) {
  27392. return null;
  27393. }
  27394. var orig = this._indices;
  27395. if (!copyWhenShared || this._meshes.length === 1) {
  27396. return orig;
  27397. }
  27398. else {
  27399. var len = orig.length;
  27400. var copy = [];
  27401. for (var i = 0; i < len; i++) {
  27402. copy.push(orig[i]);
  27403. }
  27404. return copy;
  27405. }
  27406. };
  27407. Geometry.prototype.getIndexBuffer = function () {
  27408. if (!this.isReady()) {
  27409. return null;
  27410. }
  27411. return this._indexBuffer;
  27412. };
  27413. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27414. if (!effect || !this._vertexArrayObjects) {
  27415. return;
  27416. }
  27417. if (this._vertexArrayObjects[effect.key]) {
  27418. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27419. delete this._vertexArrayObjects[effect.key];
  27420. }
  27421. };
  27422. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27423. var meshes = this._meshes;
  27424. var index = meshes.indexOf(mesh);
  27425. if (index === -1) {
  27426. return;
  27427. }
  27428. meshes.splice(index, 1);
  27429. mesh._geometry = null;
  27430. if (meshes.length === 0 && shouldDispose) {
  27431. this.dispose();
  27432. }
  27433. };
  27434. Geometry.prototype.applyToMesh = function (mesh) {
  27435. if (mesh._geometry === this) {
  27436. return;
  27437. }
  27438. var previousGeometry = mesh._geometry;
  27439. if (previousGeometry) {
  27440. previousGeometry.releaseForMesh(mesh);
  27441. }
  27442. var meshes = this._meshes;
  27443. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27444. mesh._geometry = this;
  27445. this._scene.pushGeometry(this);
  27446. meshes.push(mesh);
  27447. if (this.isReady()) {
  27448. this._applyToMesh(mesh);
  27449. }
  27450. else {
  27451. mesh._boundingInfo = this._boundingInfo;
  27452. }
  27453. };
  27454. Geometry.prototype.updateExtend = function (data, stride) {
  27455. if (data === void 0) { data = null; }
  27456. if (!data) {
  27457. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27458. }
  27459. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27460. };
  27461. Geometry.prototype._applyToMesh = function (mesh) {
  27462. var numOfMeshes = this._meshes.length;
  27463. // vertexBuffers
  27464. for (var kind in this._vertexBuffers) {
  27465. if (numOfMeshes === 1) {
  27466. this._vertexBuffers[kind].create();
  27467. }
  27468. var buffer = this._vertexBuffers[kind].getBuffer();
  27469. if (buffer)
  27470. buffer.references = numOfMeshes;
  27471. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27472. if (!this._extend) {
  27473. this.updateExtend(this._vertexBuffers[kind].getData());
  27474. }
  27475. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27476. mesh._createGlobalSubMesh();
  27477. //bounding info was just created again, world matrix should be applied again.
  27478. mesh._updateBoundingInfo();
  27479. }
  27480. }
  27481. // indexBuffer
  27482. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27483. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27484. }
  27485. if (this._indexBuffer) {
  27486. this._indexBuffer.references = numOfMeshes;
  27487. }
  27488. };
  27489. Geometry.prototype.notifyUpdate = function (kind) {
  27490. if (this.onGeometryUpdated) {
  27491. this.onGeometryUpdated(this, kind);
  27492. }
  27493. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27494. var mesh = _a[_i];
  27495. mesh._markSubMeshesAsAttributesDirty();
  27496. }
  27497. };
  27498. Geometry.prototype.load = function (scene, onLoaded) {
  27499. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27500. return;
  27501. }
  27502. if (this.isReady()) {
  27503. if (onLoaded) {
  27504. onLoaded();
  27505. }
  27506. return;
  27507. }
  27508. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27509. this._queueLoad(scene, onLoaded);
  27510. };
  27511. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27512. var _this = this;
  27513. scene._addPendingData(this);
  27514. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27515. _this._delayLoadingFunction(JSON.parse(data), _this);
  27516. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27517. _this._delayInfo = [];
  27518. scene._removePendingData(_this);
  27519. var meshes = _this._meshes;
  27520. var numOfMeshes = meshes.length;
  27521. for (var index = 0; index < numOfMeshes; index++) {
  27522. _this._applyToMesh(meshes[index]);
  27523. }
  27524. if (onLoaded) {
  27525. onLoaded();
  27526. }
  27527. }, function () { }, scene.database);
  27528. };
  27529. /**
  27530. * Invert the geometry to move from a right handed system to a left handed one.
  27531. */
  27532. Geometry.prototype.toLeftHanded = function () {
  27533. // Flip faces
  27534. var tIndices = this.getIndices(false);
  27535. if (tIndices != null && tIndices.length > 0) {
  27536. for (var i = 0; i < tIndices.length; i += 3) {
  27537. var tTemp = tIndices[i + 0];
  27538. tIndices[i + 0] = tIndices[i + 2];
  27539. tIndices[i + 2] = tTemp;
  27540. }
  27541. this.setIndices(tIndices);
  27542. }
  27543. // Negate position.z
  27544. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27545. if (tPositions != null && tPositions.length > 0) {
  27546. for (var i = 0; i < tPositions.length; i += 3) {
  27547. tPositions[i + 2] = -tPositions[i + 2];
  27548. }
  27549. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27550. }
  27551. // Negate normal.z
  27552. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27553. if (tNormals != null && tNormals.length > 0) {
  27554. for (var i = 0; i < tNormals.length; i += 3) {
  27555. tNormals[i + 2] = -tNormals[i + 2];
  27556. }
  27557. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27558. }
  27559. };
  27560. // Cache
  27561. Geometry.prototype._resetPointsArrayCache = function () {
  27562. this._positions = null;
  27563. };
  27564. Geometry.prototype._generatePointsArray = function () {
  27565. if (this._positions)
  27566. return true;
  27567. this._positions = [];
  27568. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27569. if (!data) {
  27570. return false;
  27571. }
  27572. for (var index = 0; index < data.length; index += 3) {
  27573. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27574. }
  27575. return true;
  27576. };
  27577. Geometry.prototype.isDisposed = function () {
  27578. return this._isDisposed;
  27579. };
  27580. Geometry.prototype._disposeVertexArrayObjects = function () {
  27581. if (this._vertexArrayObjects) {
  27582. for (var kind in this._vertexArrayObjects) {
  27583. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27584. }
  27585. this._vertexArrayObjects = {};
  27586. }
  27587. };
  27588. Geometry.prototype.dispose = function () {
  27589. var meshes = this._meshes;
  27590. var numOfMeshes = meshes.length;
  27591. var index;
  27592. for (index = 0; index < numOfMeshes; index++) {
  27593. this.releaseForMesh(meshes[index]);
  27594. }
  27595. this._meshes = [];
  27596. this._disposeVertexArrayObjects();
  27597. for (var kind in this._vertexBuffers) {
  27598. this._vertexBuffers[kind].dispose();
  27599. }
  27600. this._vertexBuffers = {};
  27601. this._totalVertices = 0;
  27602. if (this._indexBuffer) {
  27603. this._engine._releaseBuffer(this._indexBuffer);
  27604. }
  27605. this._indexBuffer = null;
  27606. this._indices = [];
  27607. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27608. this.delayLoadingFile = null;
  27609. this._delayLoadingFunction = null;
  27610. this._delayInfo = [];
  27611. this._boundingInfo = null;
  27612. this._scene.removeGeometry(this);
  27613. this._isDisposed = true;
  27614. };
  27615. Geometry.prototype.copy = function (id) {
  27616. var vertexData = new BABYLON.VertexData();
  27617. vertexData.indices = [];
  27618. var indices = this.getIndices();
  27619. for (var index = 0; index < indices.length; index++) {
  27620. vertexData.indices.push(indices[index]);
  27621. }
  27622. var updatable = false;
  27623. var stopChecking = false;
  27624. var kind;
  27625. for (kind in this._vertexBuffers) {
  27626. // using slice() to make a copy of the array and not just reference it
  27627. var data = this.getVerticesData(kind);
  27628. if (data instanceof Float32Array) {
  27629. vertexData.set(new Float32Array(data), kind);
  27630. }
  27631. else {
  27632. vertexData.set(data.slice(0), kind);
  27633. }
  27634. if (!stopChecking) {
  27635. updatable = this.getVertexBuffer(kind).isUpdatable();
  27636. stopChecking = !updatable;
  27637. }
  27638. }
  27639. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27640. geometry.delayLoadState = this.delayLoadState;
  27641. geometry.delayLoadingFile = this.delayLoadingFile;
  27642. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27643. for (kind in this._delayInfo) {
  27644. geometry._delayInfo = geometry._delayInfo || [];
  27645. geometry._delayInfo.push(kind);
  27646. }
  27647. // Bounding info
  27648. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27649. return geometry;
  27650. };
  27651. Geometry.prototype.serialize = function () {
  27652. var serializationObject = {};
  27653. serializationObject.id = this.id;
  27654. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27655. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27656. }
  27657. return serializationObject;
  27658. };
  27659. Geometry.prototype.toNumberArray = function (origin) {
  27660. if (Array.isArray(origin)) {
  27661. return origin;
  27662. }
  27663. else {
  27664. return Array.prototype.slice.call(origin);
  27665. }
  27666. };
  27667. Geometry.prototype.serializeVerticeData = function () {
  27668. var serializationObject = this.serialize();
  27669. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27670. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27671. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27672. serializationObject.positions._updatable = true;
  27673. }
  27674. }
  27675. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27676. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27677. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27678. serializationObject.normals._updatable = true;
  27679. }
  27680. }
  27681. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27682. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27683. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27684. serializationObject.uvs._updatable = true;
  27685. }
  27686. }
  27687. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27688. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27689. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27690. serializationObject.uv2s._updatable = true;
  27691. }
  27692. }
  27693. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27694. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27695. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27696. serializationObject.uv3s._updatable = true;
  27697. }
  27698. }
  27699. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27700. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27701. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27702. serializationObject.uv4s._updatable = true;
  27703. }
  27704. }
  27705. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27706. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27707. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27708. serializationObject.uv5s._updatable = true;
  27709. }
  27710. }
  27711. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27712. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27713. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27714. serializationObject.uv6s._updatable = true;
  27715. }
  27716. }
  27717. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27718. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27719. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27720. serializationObject.colors._updatable = true;
  27721. }
  27722. }
  27723. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27724. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27725. serializationObject.matricesIndices._isExpanded = true;
  27726. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27727. serializationObject.matricesIndices._updatable = true;
  27728. }
  27729. }
  27730. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27731. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27732. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27733. serializationObject.matricesWeights._updatable = true;
  27734. }
  27735. }
  27736. serializationObject.indices = this.toNumberArray(this.getIndices());
  27737. return serializationObject;
  27738. };
  27739. // Statics
  27740. Geometry.ExtractFromMesh = function (mesh, id) {
  27741. var geometry = mesh._geometry;
  27742. if (!geometry) {
  27743. return null;
  27744. }
  27745. return geometry.copy(id);
  27746. };
  27747. /**
  27748. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27749. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27750. * Be aware Math.random() could cause collisions, but:
  27751. * "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"
  27752. */
  27753. Geometry.RandomId = function () {
  27754. return BABYLON.Tools.RandomId();
  27755. };
  27756. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27757. var scene = mesh.getScene();
  27758. // Geometry
  27759. var geometryId = parsedGeometry.geometryId;
  27760. if (geometryId) {
  27761. var geometry = scene.getGeometryByID(geometryId);
  27762. if (geometry) {
  27763. geometry.applyToMesh(mesh);
  27764. }
  27765. }
  27766. else if (parsedGeometry instanceof ArrayBuffer) {
  27767. var binaryInfo = mesh._binaryInfo;
  27768. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27769. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27770. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27771. }
  27772. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27773. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27774. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27775. }
  27776. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27777. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27778. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27779. }
  27780. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27781. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27782. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27783. }
  27784. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27785. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27786. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27787. }
  27788. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27789. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27790. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27791. }
  27792. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27793. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27794. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27795. }
  27796. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27797. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27798. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27799. }
  27800. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27801. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27802. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27803. }
  27804. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27805. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27806. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27807. }
  27808. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27809. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27810. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27811. }
  27812. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27813. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27814. mesh.setIndices(indicesData);
  27815. }
  27816. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27817. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27818. mesh.subMeshes = [];
  27819. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27820. var materialIndex = subMeshesData[(i * 5) + 0];
  27821. var verticesStart = subMeshesData[(i * 5) + 1];
  27822. var verticesCount = subMeshesData[(i * 5) + 2];
  27823. var indexStart = subMeshesData[(i * 5) + 3];
  27824. var indexCount = subMeshesData[(i * 5) + 4];
  27825. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27826. }
  27827. }
  27828. }
  27829. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27830. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27831. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27832. if (parsedGeometry.uvs) {
  27833. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27834. }
  27835. if (parsedGeometry.uvs2) {
  27836. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27837. }
  27838. if (parsedGeometry.uvs3) {
  27839. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27840. }
  27841. if (parsedGeometry.uvs4) {
  27842. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27843. }
  27844. if (parsedGeometry.uvs5) {
  27845. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27846. }
  27847. if (parsedGeometry.uvs6) {
  27848. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27849. }
  27850. if (parsedGeometry.colors) {
  27851. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27852. }
  27853. if (parsedGeometry.matricesIndices) {
  27854. if (!parsedGeometry.matricesIndices._isExpanded) {
  27855. var floatIndices = [];
  27856. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27857. var matricesIndex = parsedGeometry.matricesIndices[i];
  27858. floatIndices.push(matricesIndex & 0x000000FF);
  27859. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27860. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27861. floatIndices.push(matricesIndex >> 24);
  27862. }
  27863. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27864. }
  27865. else {
  27866. delete parsedGeometry.matricesIndices._isExpanded;
  27867. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27868. }
  27869. }
  27870. if (parsedGeometry.matricesIndicesExtra) {
  27871. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27872. var floatIndices = [];
  27873. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27874. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27875. floatIndices.push(matricesIndex & 0x000000FF);
  27876. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27877. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27878. floatIndices.push(matricesIndex >> 24);
  27879. }
  27880. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27881. }
  27882. else {
  27883. delete parsedGeometry.matricesIndices._isExpanded;
  27884. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27885. }
  27886. }
  27887. if (parsedGeometry.matricesWeights) {
  27888. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27889. }
  27890. if (parsedGeometry.matricesWeightsExtra) {
  27891. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27892. }
  27893. mesh.setIndices(parsedGeometry.indices);
  27894. }
  27895. // SubMeshes
  27896. if (parsedGeometry.subMeshes) {
  27897. mesh.subMeshes = [];
  27898. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27899. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27900. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27901. }
  27902. }
  27903. // Flat shading
  27904. if (mesh._shouldGenerateFlatShading) {
  27905. mesh.convertToFlatShadedMesh();
  27906. delete mesh._shouldGenerateFlatShading;
  27907. }
  27908. // Update
  27909. mesh.computeWorldMatrix(true);
  27910. // Octree
  27911. if (scene['_selectionOctree']) {
  27912. scene['_selectionOctree'].addMesh(mesh);
  27913. }
  27914. };
  27915. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27916. if (scene.getGeometryByID(parsedVertexData.id)) {
  27917. return null; // null since geometry could be something else than a box...
  27918. }
  27919. var geometry = new Geometry(parsedVertexData.id, scene);
  27920. if (BABYLON.Tags) {
  27921. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27922. }
  27923. if (parsedVertexData.delayLoadingFile) {
  27924. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27925. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27926. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27927. geometry._delayInfo = [];
  27928. if (parsedVertexData.hasUVs) {
  27929. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27930. }
  27931. if (parsedVertexData.hasUVs2) {
  27932. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27933. }
  27934. if (parsedVertexData.hasUVs3) {
  27935. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27936. }
  27937. if (parsedVertexData.hasUVs4) {
  27938. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27939. }
  27940. if (parsedVertexData.hasUVs5) {
  27941. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27942. }
  27943. if (parsedVertexData.hasUVs6) {
  27944. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27945. }
  27946. if (parsedVertexData.hasColors) {
  27947. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27948. }
  27949. if (parsedVertexData.hasMatricesIndices) {
  27950. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27951. }
  27952. if (parsedVertexData.hasMatricesWeights) {
  27953. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27954. }
  27955. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27956. }
  27957. else {
  27958. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27959. }
  27960. scene.pushGeometry(geometry, true);
  27961. return geometry;
  27962. };
  27963. return Geometry;
  27964. }());
  27965. BABYLON.Geometry = Geometry;
  27966. /////// Primitives //////////////////////////////////////////////
  27967. (function (Geometry) {
  27968. var Primitives;
  27969. (function (Primitives) {
  27970. /// Abstract class
  27971. var _Primitive = (function (_super) {
  27972. __extends(_Primitive, _super);
  27973. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27974. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27975. _this._canBeRegenerated = _canBeRegenerated;
  27976. _this._beingRegenerated = true;
  27977. _this.regenerate();
  27978. _this._beingRegenerated = false;
  27979. return _this;
  27980. }
  27981. _Primitive.prototype.canBeRegenerated = function () {
  27982. return this._canBeRegenerated;
  27983. };
  27984. _Primitive.prototype.regenerate = function () {
  27985. if (!this._canBeRegenerated) {
  27986. return;
  27987. }
  27988. this._beingRegenerated = true;
  27989. this.setAllVerticesData(this._regenerateVertexData(), false);
  27990. this._beingRegenerated = false;
  27991. };
  27992. _Primitive.prototype.asNewGeometry = function (id) {
  27993. return _super.prototype.copy.call(this, id);
  27994. };
  27995. // overrides
  27996. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27997. if (!this._beingRegenerated) {
  27998. return;
  27999. }
  28000. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28001. };
  28002. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28003. if (!this._beingRegenerated) {
  28004. return;
  28005. }
  28006. _super.prototype.setVerticesData.call(this, kind, data, false);
  28007. };
  28008. // to override
  28009. // protected
  28010. _Primitive.prototype._regenerateVertexData = function () {
  28011. throw new Error("Abstract method");
  28012. };
  28013. _Primitive.prototype.copy = function (id) {
  28014. throw new Error("Must be overriden in sub-classes.");
  28015. };
  28016. _Primitive.prototype.serialize = function () {
  28017. var serializationObject = _super.prototype.serialize.call(this);
  28018. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28019. return serializationObject;
  28020. };
  28021. return _Primitive;
  28022. }(Geometry));
  28023. Primitives._Primitive = _Primitive;
  28024. var Ribbon = (function (_super) {
  28025. __extends(Ribbon, _super);
  28026. // Members
  28027. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28028. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28029. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28030. _this.pathArray = pathArray;
  28031. _this.closeArray = closeArray;
  28032. _this.closePath = closePath;
  28033. _this.offset = offset;
  28034. _this.side = side;
  28035. return _this;
  28036. }
  28037. Ribbon.prototype._regenerateVertexData = function () {
  28038. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28039. };
  28040. Ribbon.prototype.copy = function (id) {
  28041. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28042. };
  28043. return Ribbon;
  28044. }(_Primitive));
  28045. Primitives.Ribbon = Ribbon;
  28046. var Box = (function (_super) {
  28047. __extends(Box, _super);
  28048. // Members
  28049. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28050. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28051. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28052. _this.size = size;
  28053. _this.side = side;
  28054. return _this;
  28055. }
  28056. Box.prototype._regenerateVertexData = function () {
  28057. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28058. };
  28059. Box.prototype.copy = function (id) {
  28060. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28061. };
  28062. Box.prototype.serialize = function () {
  28063. var serializationObject = _super.prototype.serialize.call(this);
  28064. serializationObject.size = this.size;
  28065. return serializationObject;
  28066. };
  28067. Box.Parse = function (parsedBox, scene) {
  28068. if (scene.getGeometryByID(parsedBox.id)) {
  28069. return null; // null since geometry could be something else than a box...
  28070. }
  28071. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28072. if (BABYLON.Tags) {
  28073. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28074. }
  28075. scene.pushGeometry(box, true);
  28076. return box;
  28077. };
  28078. return Box;
  28079. }(_Primitive));
  28080. Primitives.Box = Box;
  28081. var Sphere = (function (_super) {
  28082. __extends(Sphere, _super);
  28083. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28084. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28085. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28086. _this.segments = segments;
  28087. _this.diameter = diameter;
  28088. _this.side = side;
  28089. return _this;
  28090. }
  28091. Sphere.prototype._regenerateVertexData = function () {
  28092. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28093. };
  28094. Sphere.prototype.copy = function (id) {
  28095. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28096. };
  28097. Sphere.prototype.serialize = function () {
  28098. var serializationObject = _super.prototype.serialize.call(this);
  28099. serializationObject.segments = this.segments;
  28100. serializationObject.diameter = this.diameter;
  28101. return serializationObject;
  28102. };
  28103. Sphere.Parse = function (parsedSphere, scene) {
  28104. if (scene.getGeometryByID(parsedSphere.id)) {
  28105. return null; // null since geometry could be something else than a sphere...
  28106. }
  28107. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28108. if (BABYLON.Tags) {
  28109. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28110. }
  28111. scene.pushGeometry(sphere, true);
  28112. return sphere;
  28113. };
  28114. return Sphere;
  28115. }(_Primitive));
  28116. Primitives.Sphere = Sphere;
  28117. var Disc = (function (_super) {
  28118. __extends(Disc, _super);
  28119. // Members
  28120. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28121. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28122. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28123. _this.radius = radius;
  28124. _this.tessellation = tessellation;
  28125. _this.side = side;
  28126. return _this;
  28127. }
  28128. Disc.prototype._regenerateVertexData = function () {
  28129. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28130. };
  28131. Disc.prototype.copy = function (id) {
  28132. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28133. };
  28134. return Disc;
  28135. }(_Primitive));
  28136. Primitives.Disc = Disc;
  28137. var Cylinder = (function (_super) {
  28138. __extends(Cylinder, _super);
  28139. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28140. if (subdivisions === void 0) { subdivisions = 1; }
  28141. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28142. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28143. _this.height = height;
  28144. _this.diameterTop = diameterTop;
  28145. _this.diameterBottom = diameterBottom;
  28146. _this.tessellation = tessellation;
  28147. _this.subdivisions = subdivisions;
  28148. _this.side = side;
  28149. return _this;
  28150. }
  28151. Cylinder.prototype._regenerateVertexData = function () {
  28152. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28153. };
  28154. Cylinder.prototype.copy = function (id) {
  28155. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28156. };
  28157. Cylinder.prototype.serialize = function () {
  28158. var serializationObject = _super.prototype.serialize.call(this);
  28159. serializationObject.height = this.height;
  28160. serializationObject.diameterTop = this.diameterTop;
  28161. serializationObject.diameterBottom = this.diameterBottom;
  28162. serializationObject.tessellation = this.tessellation;
  28163. return serializationObject;
  28164. };
  28165. Cylinder.Parse = function (parsedCylinder, scene) {
  28166. if (scene.getGeometryByID(parsedCylinder.id)) {
  28167. return null; // null since geometry could be something else than a cylinder...
  28168. }
  28169. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28170. if (BABYLON.Tags) {
  28171. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28172. }
  28173. scene.pushGeometry(cylinder, true);
  28174. return cylinder;
  28175. };
  28176. return Cylinder;
  28177. }(_Primitive));
  28178. Primitives.Cylinder = Cylinder;
  28179. var Torus = (function (_super) {
  28180. __extends(Torus, _super);
  28181. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28182. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28183. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28184. _this.diameter = diameter;
  28185. _this.thickness = thickness;
  28186. _this.tessellation = tessellation;
  28187. _this.side = side;
  28188. return _this;
  28189. }
  28190. Torus.prototype._regenerateVertexData = function () {
  28191. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28192. };
  28193. Torus.prototype.copy = function (id) {
  28194. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28195. };
  28196. Torus.prototype.serialize = function () {
  28197. var serializationObject = _super.prototype.serialize.call(this);
  28198. serializationObject.diameter = this.diameter;
  28199. serializationObject.thickness = this.thickness;
  28200. serializationObject.tessellation = this.tessellation;
  28201. return serializationObject;
  28202. };
  28203. Torus.Parse = function (parsedTorus, scene) {
  28204. if (scene.getGeometryByID(parsedTorus.id)) {
  28205. return null; // null since geometry could be something else than a torus...
  28206. }
  28207. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28208. if (BABYLON.Tags) {
  28209. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28210. }
  28211. scene.pushGeometry(torus, true);
  28212. return torus;
  28213. };
  28214. return Torus;
  28215. }(_Primitive));
  28216. Primitives.Torus = Torus;
  28217. var Ground = (function (_super) {
  28218. __extends(Ground, _super);
  28219. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28220. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28221. _this.width = width;
  28222. _this.height = height;
  28223. _this.subdivisions = subdivisions;
  28224. return _this;
  28225. }
  28226. Ground.prototype._regenerateVertexData = function () {
  28227. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28228. };
  28229. Ground.prototype.copy = function (id) {
  28230. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28231. };
  28232. Ground.prototype.serialize = function () {
  28233. var serializationObject = _super.prototype.serialize.call(this);
  28234. serializationObject.width = this.width;
  28235. serializationObject.height = this.height;
  28236. serializationObject.subdivisions = this.subdivisions;
  28237. return serializationObject;
  28238. };
  28239. Ground.Parse = function (parsedGround, scene) {
  28240. if (scene.getGeometryByID(parsedGround.id)) {
  28241. return null; // null since geometry could be something else than a ground...
  28242. }
  28243. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28244. if (BABYLON.Tags) {
  28245. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28246. }
  28247. scene.pushGeometry(ground, true);
  28248. return ground;
  28249. };
  28250. return Ground;
  28251. }(_Primitive));
  28252. Primitives.Ground = Ground;
  28253. var TiledGround = (function (_super) {
  28254. __extends(TiledGround, _super);
  28255. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28256. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28257. _this.xmin = xmin;
  28258. _this.zmin = zmin;
  28259. _this.xmax = xmax;
  28260. _this.zmax = zmax;
  28261. _this.subdivisions = subdivisions;
  28262. _this.precision = precision;
  28263. return _this;
  28264. }
  28265. TiledGround.prototype._regenerateVertexData = function () {
  28266. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28267. };
  28268. TiledGround.prototype.copy = function (id) {
  28269. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28270. };
  28271. return TiledGround;
  28272. }(_Primitive));
  28273. Primitives.TiledGround = TiledGround;
  28274. var Plane = (function (_super) {
  28275. __extends(Plane, _super);
  28276. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28277. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28278. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28279. _this.size = size;
  28280. _this.side = side;
  28281. return _this;
  28282. }
  28283. Plane.prototype._regenerateVertexData = function () {
  28284. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28285. };
  28286. Plane.prototype.copy = function (id) {
  28287. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28288. };
  28289. Plane.prototype.serialize = function () {
  28290. var serializationObject = _super.prototype.serialize.call(this);
  28291. serializationObject.size = this.size;
  28292. return serializationObject;
  28293. };
  28294. Plane.Parse = function (parsedPlane, scene) {
  28295. if (scene.getGeometryByID(parsedPlane.id)) {
  28296. return null; // null since geometry could be something else than a ground...
  28297. }
  28298. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28299. if (BABYLON.Tags) {
  28300. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28301. }
  28302. scene.pushGeometry(plane, true);
  28303. return plane;
  28304. };
  28305. return Plane;
  28306. }(_Primitive));
  28307. Primitives.Plane = Plane;
  28308. var TorusKnot = (function (_super) {
  28309. __extends(TorusKnot, _super);
  28310. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28311. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28312. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28313. _this.radius = radius;
  28314. _this.tube = tube;
  28315. _this.radialSegments = radialSegments;
  28316. _this.tubularSegments = tubularSegments;
  28317. _this.p = p;
  28318. _this.q = q;
  28319. _this.side = side;
  28320. return _this;
  28321. }
  28322. TorusKnot.prototype._regenerateVertexData = function () {
  28323. 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 });
  28324. };
  28325. TorusKnot.prototype.copy = function (id) {
  28326. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28327. };
  28328. TorusKnot.prototype.serialize = function () {
  28329. var serializationObject = _super.prototype.serialize.call(this);
  28330. serializationObject.radius = this.radius;
  28331. serializationObject.tube = this.tube;
  28332. serializationObject.radialSegments = this.radialSegments;
  28333. serializationObject.tubularSegments = this.tubularSegments;
  28334. serializationObject.p = this.p;
  28335. serializationObject.q = this.q;
  28336. return serializationObject;
  28337. };
  28338. ;
  28339. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28340. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28341. return null; // null since geometry could be something else than a ground...
  28342. }
  28343. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28344. if (BABYLON.Tags) {
  28345. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28346. }
  28347. scene.pushGeometry(torusKnot, true);
  28348. return torusKnot;
  28349. };
  28350. return TorusKnot;
  28351. }(_Primitive));
  28352. Primitives.TorusKnot = TorusKnot;
  28353. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28354. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28355. })(BABYLON || (BABYLON = {}));
  28356. //# sourceMappingURL=babylon.geometry.js.map
  28357. var BABYLON;
  28358. (function (BABYLON) {
  28359. var PostProcessManager = (function () {
  28360. function PostProcessManager(scene) {
  28361. this._vertexBuffers = {};
  28362. this._scene = scene;
  28363. }
  28364. PostProcessManager.prototype._prepareBuffers = function () {
  28365. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28366. return;
  28367. }
  28368. // VBO
  28369. var vertices = [];
  28370. vertices.push(1, 1);
  28371. vertices.push(-1, 1);
  28372. vertices.push(-1, -1);
  28373. vertices.push(1, -1);
  28374. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28375. // Indices
  28376. var indices = [];
  28377. indices.push(0);
  28378. indices.push(1);
  28379. indices.push(2);
  28380. indices.push(0);
  28381. indices.push(2);
  28382. indices.push(3);
  28383. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28384. };
  28385. // Methods
  28386. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28387. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28388. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28389. return false;
  28390. }
  28391. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28392. return true;
  28393. };
  28394. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28395. var engine = this._scene.getEngine();
  28396. for (var index = 0; index < postProcesses.length; index++) {
  28397. if (index < postProcesses.length - 1) {
  28398. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28399. }
  28400. else {
  28401. if (targetTexture) {
  28402. engine.bindFramebuffer(targetTexture);
  28403. }
  28404. else {
  28405. engine.restoreDefaultFramebuffer();
  28406. }
  28407. }
  28408. var pp = postProcesses[index];
  28409. var effect = pp.apply();
  28410. if (effect) {
  28411. pp.onBeforeRenderObservable.notifyObservers(effect);
  28412. // VBOs
  28413. this._prepareBuffers();
  28414. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28415. // Draw order
  28416. engine.draw(true, 0, 6);
  28417. pp.onAfterRenderObservable.notifyObservers(effect);
  28418. }
  28419. }
  28420. // Restore depth buffer
  28421. engine.setDepthBuffer(true);
  28422. engine.setDepthWrite(true);
  28423. };
  28424. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28425. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28426. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28427. return;
  28428. }
  28429. var engine = this._scene.getEngine();
  28430. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28431. if (index < len - 1) {
  28432. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28433. }
  28434. else {
  28435. if (targetTexture) {
  28436. engine.bindFramebuffer(targetTexture, faceIndex);
  28437. }
  28438. else {
  28439. engine.restoreDefaultFramebuffer();
  28440. }
  28441. }
  28442. if (doNotPresent) {
  28443. break;
  28444. }
  28445. var pp = postProcesses[index];
  28446. var effect = pp.apply();
  28447. if (effect) {
  28448. pp.onBeforeRenderObservable.notifyObservers(effect);
  28449. // VBOs
  28450. this._prepareBuffers();
  28451. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28452. // Draw order
  28453. engine.draw(true, 0, 6);
  28454. pp.onAfterRenderObservable.notifyObservers(effect);
  28455. }
  28456. }
  28457. // Restore states
  28458. engine.setDepthBuffer(true);
  28459. engine.setDepthWrite(true);
  28460. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28461. };
  28462. PostProcessManager.prototype.dispose = function () {
  28463. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28464. if (buffer) {
  28465. buffer.dispose();
  28466. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28467. }
  28468. if (this._indexBuffer) {
  28469. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28470. this._indexBuffer = null;
  28471. }
  28472. };
  28473. return PostProcessManager;
  28474. }());
  28475. BABYLON.PostProcessManager = PostProcessManager;
  28476. })(BABYLON || (BABYLON = {}));
  28477. //# sourceMappingURL=babylon.postProcessManager.js.map
  28478. var BABYLON;
  28479. (function (BABYLON) {
  28480. var StandardMaterialDefines = (function (_super) {
  28481. __extends(StandardMaterialDefines, _super);
  28482. function StandardMaterialDefines() {
  28483. var _this = _super.call(this) || this;
  28484. _this.DIFFUSE = false;
  28485. _this.AMBIENT = false;
  28486. _this.OPACITY = false;
  28487. _this.OPACITYRGB = false;
  28488. _this.REFLECTION = false;
  28489. _this.EMISSIVE = false;
  28490. _this.SPECULAR = false;
  28491. _this.BUMP = false;
  28492. _this.PARALLAX = false;
  28493. _this.PARALLAXOCCLUSION = false;
  28494. _this.SPECULAROVERALPHA = false;
  28495. _this.CLIPPLANE = false;
  28496. _this.ALPHATEST = false;
  28497. _this.ALPHAFROMDIFFUSE = false;
  28498. _this.POINTSIZE = false;
  28499. _this.FOG = false;
  28500. _this.SPECULARTERM = false;
  28501. _this.DIFFUSEFRESNEL = false;
  28502. _this.OPACITYFRESNEL = false;
  28503. _this.REFLECTIONFRESNEL = false;
  28504. _this.REFRACTIONFRESNEL = false;
  28505. _this.EMISSIVEFRESNEL = false;
  28506. _this.FRESNEL = false;
  28507. _this.NORMAL = false;
  28508. _this.UV1 = false;
  28509. _this.UV2 = false;
  28510. _this.VERTEXCOLOR = false;
  28511. _this.VERTEXALPHA = false;
  28512. _this.NUM_BONE_INFLUENCERS = 0;
  28513. _this.BonesPerMesh = 0;
  28514. _this.INSTANCES = false;
  28515. _this.GLOSSINESS = false;
  28516. _this.ROUGHNESS = false;
  28517. _this.EMISSIVEASILLUMINATION = false;
  28518. _this.LINKEMISSIVEWITHDIFFUSE = false;
  28519. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  28520. _this.LIGHTMAP = false;
  28521. _this.USELIGHTMAPASSHADOWMAP = false;
  28522. _this.REFLECTIONMAP_3D = false;
  28523. _this.REFLECTIONMAP_SPHERICAL = false;
  28524. _this.REFLECTIONMAP_PLANAR = false;
  28525. _this.REFLECTIONMAP_CUBIC = false;
  28526. _this.REFLECTIONMAP_PROJECTION = false;
  28527. _this.REFLECTIONMAP_SKYBOX = false;
  28528. _this.REFLECTIONMAP_EXPLICIT = false;
  28529. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28530. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28531. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28532. _this.INVERTCUBICMAP = false;
  28533. _this.LOGARITHMICDEPTH = false;
  28534. _this.REFRACTION = false;
  28535. _this.REFRACTIONMAP_3D = false;
  28536. _this.REFLECTIONOVERALPHA = false;
  28537. _this.INVERTNORMALMAPX = false;
  28538. _this.INVERTNORMALMAPY = false;
  28539. _this.TWOSIDEDLIGHTING = false;
  28540. _this.SHADOWFLOAT = false;
  28541. _this.MORPHTARGETS = false;
  28542. _this.MORPHTARGETS_NORMAL = false;
  28543. _this.MORPHTARGETS_TANGENT = false;
  28544. _this.NUM_MORPH_INFLUENCERS = 0;
  28545. _this.USERIGHTHANDEDSYSTEM = false;
  28546. _this.IMAGEPROCESSING = false;
  28547. _this.VIGNETTE = false;
  28548. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  28549. _this.VIGNETTEBLENDMODEOPAQUE = false;
  28550. _this.TONEMAPPING = false;
  28551. _this.CONTRAST = false;
  28552. _this.COLORCURVES = false;
  28553. _this.COLORGRADING = false;
  28554. _this.SAMPLER3DGREENDEPTH = false;
  28555. _this.SAMPLER3DBGRMAP = false;
  28556. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  28557. _this.EXPOSURE = false;
  28558. _this.rebuild();
  28559. return _this;
  28560. }
  28561. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  28562. var modes = [
  28563. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  28564. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  28565. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  28566. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  28567. ];
  28568. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  28569. var mode = modes_1[_i];
  28570. this[mode] = (mode === modeToEnable);
  28571. }
  28572. };
  28573. return StandardMaterialDefines;
  28574. }(BABYLON.MaterialDefines));
  28575. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  28576. var StandardMaterial = (function (_super) {
  28577. __extends(StandardMaterial, _super);
  28578. function StandardMaterial(name, scene) {
  28579. var _this = _super.call(this, name, scene) || this;
  28580. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28581. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  28582. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  28583. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28584. _this.specularPower = 64;
  28585. _this._useAlphaFromDiffuseTexture = false;
  28586. _this._useEmissiveAsIllumination = false;
  28587. _this._linkEmissiveWithDiffuse = false;
  28588. _this._useSpecularOverAlpha = false;
  28589. _this._useReflectionOverAlpha = false;
  28590. _this._disableLighting = false;
  28591. _this._useParallax = false;
  28592. _this._useParallaxOcclusion = false;
  28593. _this.parallaxScaleBias = 0.05;
  28594. _this._roughness = 0;
  28595. _this.indexOfRefraction = 0.98;
  28596. _this.invertRefractionY = true;
  28597. _this._useLightmapAsShadowmap = false;
  28598. _this._useReflectionFresnelFromSpecular = false;
  28599. _this._useGlossinessFromSpecularMapAlpha = false;
  28600. _this._maxSimultaneousLights = 4;
  28601. /**
  28602. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28603. */
  28604. _this._invertNormalMapX = false;
  28605. /**
  28606. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28607. */
  28608. _this._invertNormalMapY = false;
  28609. /**
  28610. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28611. */
  28612. _this._twoSidedLighting = false;
  28613. _this._renderTargets = new BABYLON.SmartArray(16);
  28614. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28615. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28616. // Setup the default processing configuration to the scene.
  28617. _this._attachImageProcessingConfiguration(null);
  28618. _this.getRenderTargetTextures = function () {
  28619. _this._renderTargets.reset();
  28620. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  28621. _this._renderTargets.push(_this._reflectionTexture);
  28622. }
  28623. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  28624. _this._renderTargets.push(_this._refractionTexture);
  28625. }
  28626. return _this._renderTargets;
  28627. };
  28628. return _this;
  28629. }
  28630. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  28631. /**
  28632. * Gets the image processing configuration used either in this material.
  28633. */
  28634. get: function () {
  28635. return this._imageProcessingConfiguration;
  28636. },
  28637. /**
  28638. * Sets the Default image processing configuration used either in the this material.
  28639. *
  28640. * If sets to null, the scene one is in use.
  28641. */
  28642. set: function (value) {
  28643. this._attachImageProcessingConfiguration(value);
  28644. // Ensure the effect will be rebuilt.
  28645. this._markAllSubMeshesAsTexturesDirty();
  28646. },
  28647. enumerable: true,
  28648. configurable: true
  28649. });
  28650. /**
  28651. * Attaches a new image processing configuration to the Standard Material.
  28652. * @param configuration
  28653. */
  28654. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  28655. var _this = this;
  28656. if (configuration === this._imageProcessingConfiguration) {
  28657. return;
  28658. }
  28659. // Detaches observer.
  28660. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  28661. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  28662. }
  28663. // Pick the scene configuration if needed.
  28664. if (!configuration) {
  28665. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  28666. }
  28667. else {
  28668. this._imageProcessingConfiguration = configuration;
  28669. }
  28670. // Attaches observer.
  28671. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  28672. _this._markAllSubMeshesAsImageProcessingDirty();
  28673. });
  28674. };
  28675. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  28676. /**
  28677. * Gets wether the color curves effect is enabled.
  28678. */
  28679. get: function () {
  28680. return this.imageProcessingConfiguration.colorCurvesEnabled;
  28681. },
  28682. /**
  28683. * Sets wether the color curves effect is enabled.
  28684. */
  28685. set: function (value) {
  28686. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  28687. },
  28688. enumerable: true,
  28689. configurable: true
  28690. });
  28691. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  28692. /**
  28693. * Gets wether the color grading effect is enabled.
  28694. */
  28695. get: function () {
  28696. return this.imageProcessingConfiguration.colorGradingEnabled;
  28697. },
  28698. /**
  28699. * Gets wether the color grading effect is enabled.
  28700. */
  28701. set: function (value) {
  28702. this.imageProcessingConfiguration.colorGradingEnabled = value;
  28703. },
  28704. enumerable: true,
  28705. configurable: true
  28706. });
  28707. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  28708. /**
  28709. * Gets wether tonemapping is enabled or not.
  28710. */
  28711. get: function () {
  28712. return this._imageProcessingConfiguration.toneMappingEnabled;
  28713. },
  28714. /**
  28715. * Sets wether tonemapping is enabled or not
  28716. */
  28717. set: function (value) {
  28718. this._imageProcessingConfiguration.toneMappingEnabled = value;
  28719. },
  28720. enumerable: true,
  28721. configurable: true
  28722. });
  28723. ;
  28724. ;
  28725. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  28726. /**
  28727. * The camera exposure used on this material.
  28728. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28729. * This corresponds to a photographic exposure.
  28730. */
  28731. get: function () {
  28732. return this._imageProcessingConfiguration.exposure;
  28733. },
  28734. /**
  28735. * The camera exposure used on this material.
  28736. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28737. * This corresponds to a photographic exposure.
  28738. */
  28739. set: function (value) {
  28740. this._imageProcessingConfiguration.exposure = value;
  28741. },
  28742. enumerable: true,
  28743. configurable: true
  28744. });
  28745. ;
  28746. ;
  28747. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  28748. /**
  28749. * Gets The camera contrast used on this material.
  28750. */
  28751. get: function () {
  28752. return this._imageProcessingConfiguration.contrast;
  28753. },
  28754. /**
  28755. * Sets The camera contrast used on this material.
  28756. */
  28757. set: function (value) {
  28758. this._imageProcessingConfiguration.contrast = value;
  28759. },
  28760. enumerable: true,
  28761. configurable: true
  28762. });
  28763. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  28764. /**
  28765. * Gets the Color Grading 2D Lookup Texture.
  28766. */
  28767. get: function () {
  28768. return this._imageProcessingConfiguration.colorGradingTexture;
  28769. },
  28770. /**
  28771. * Sets the Color Grading 2D Lookup Texture.
  28772. */
  28773. set: function (value) {
  28774. this._imageProcessingConfiguration.colorGradingTexture = value;
  28775. },
  28776. enumerable: true,
  28777. configurable: true
  28778. });
  28779. StandardMaterial.prototype.getClassName = function () {
  28780. return "StandardMaterial";
  28781. };
  28782. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  28783. get: function () {
  28784. return this._useLogarithmicDepth;
  28785. },
  28786. set: function (value) {
  28787. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28788. this._markAllSubMeshesAsMiscDirty();
  28789. },
  28790. enumerable: true,
  28791. configurable: true
  28792. });
  28793. StandardMaterial.prototype.needAlphaBlending = function () {
  28794. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  28795. };
  28796. StandardMaterial.prototype.needAlphaTesting = function () {
  28797. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  28798. };
  28799. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  28800. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  28801. };
  28802. StandardMaterial.prototype.getAlphaTestTexture = function () {
  28803. return this._diffuseTexture;
  28804. };
  28805. /**
  28806. * Child classes can use it to update shaders
  28807. */
  28808. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28809. if (this.isFrozen) {
  28810. if (this._wasPreviouslyReady && subMesh.effect) {
  28811. return true;
  28812. }
  28813. }
  28814. if (!subMesh._materialDefines) {
  28815. subMesh._materialDefines = new StandardMaterialDefines();
  28816. }
  28817. var scene = this.getScene();
  28818. var defines = subMesh._materialDefines;
  28819. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  28820. if (defines._renderId === scene.getRenderId()) {
  28821. return true;
  28822. }
  28823. }
  28824. var engine = scene.getEngine();
  28825. // Lights
  28826. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  28827. // Textures
  28828. if (defines._areTexturesDirty) {
  28829. defines._needUVs = false;
  28830. if (scene.texturesEnabled) {
  28831. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28832. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  28833. return false;
  28834. }
  28835. else {
  28836. defines._needUVs = true;
  28837. defines.DIFFUSE = true;
  28838. }
  28839. }
  28840. else {
  28841. defines.DIFFUSE = false;
  28842. }
  28843. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28844. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  28845. return false;
  28846. }
  28847. else {
  28848. defines._needUVs = true;
  28849. defines.AMBIENT = true;
  28850. }
  28851. }
  28852. else {
  28853. defines.AMBIENT = false;
  28854. }
  28855. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28856. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  28857. return false;
  28858. }
  28859. else {
  28860. defines._needUVs = true;
  28861. defines.OPACITY = true;
  28862. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  28863. }
  28864. }
  28865. else {
  28866. defines.OPACITY = false;
  28867. }
  28868. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28869. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  28870. return false;
  28871. }
  28872. else {
  28873. defines._needNormals = true;
  28874. defines.REFLECTION = true;
  28875. defines.ROUGHNESS = (this._roughness > 0);
  28876. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  28877. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  28878. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  28879. switch (this._reflectionTexture.coordinatesMode) {
  28880. case BABYLON.Texture.CUBIC_MODE:
  28881. case BABYLON.Texture.INVCUBIC_MODE:
  28882. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  28883. break;
  28884. case BABYLON.Texture.EXPLICIT_MODE:
  28885. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  28886. break;
  28887. case BABYLON.Texture.PLANAR_MODE:
  28888. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  28889. break;
  28890. case BABYLON.Texture.PROJECTION_MODE:
  28891. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  28892. break;
  28893. case BABYLON.Texture.SKYBOX_MODE:
  28894. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  28895. break;
  28896. case BABYLON.Texture.SPHERICAL_MODE:
  28897. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  28898. break;
  28899. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28900. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  28901. break;
  28902. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28903. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  28904. break;
  28905. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28906. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  28907. break;
  28908. }
  28909. }
  28910. }
  28911. else {
  28912. defines.REFLECTION = false;
  28913. }
  28914. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28915. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  28916. return false;
  28917. }
  28918. else {
  28919. defines._needUVs = true;
  28920. defines.EMISSIVE = true;
  28921. }
  28922. }
  28923. else {
  28924. defines.EMISSIVE = false;
  28925. }
  28926. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28927. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  28928. return false;
  28929. }
  28930. else {
  28931. defines._needUVs = true;
  28932. defines.LIGHTMAP = true;
  28933. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  28934. }
  28935. }
  28936. else {
  28937. defines.LIGHTMAP = false;
  28938. }
  28939. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28940. if (!this._specularTexture.isReadyOrNotBlocking()) {
  28941. return false;
  28942. }
  28943. else {
  28944. defines._needUVs = true;
  28945. defines.SPECULAR = true;
  28946. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  28947. }
  28948. }
  28949. else {
  28950. defines.SPECULAR = false;
  28951. }
  28952. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  28953. // Bump texure can not be not blocking.
  28954. if (!this._bumpTexture.isReady()) {
  28955. return false;
  28956. }
  28957. else {
  28958. defines._needUVs = true;
  28959. defines.BUMP = true;
  28960. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  28961. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  28962. defines.PARALLAX = this._useParallax;
  28963. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  28964. }
  28965. }
  28966. else {
  28967. defines.BUMP = false;
  28968. }
  28969. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28970. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  28971. return false;
  28972. }
  28973. else {
  28974. defines._needUVs = true;
  28975. defines.REFRACTION = true;
  28976. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  28977. }
  28978. }
  28979. else {
  28980. defines.REFRACTION = false;
  28981. }
  28982. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  28983. }
  28984. else {
  28985. defines.DIFFUSE = false;
  28986. defines.AMBIENT = false;
  28987. defines.OPACITY = false;
  28988. defines.REFLECTION = false;
  28989. defines.EMISSIVE = false;
  28990. defines.LIGHTMAP = false;
  28991. defines.BUMP = false;
  28992. defines.REFRACTION = false;
  28993. }
  28994. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  28995. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  28996. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  28997. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  28998. }
  28999. if (defines._areImageProcessingDirty) {
  29000. if (!this._imageProcessingConfiguration.isReady()) {
  29001. return false;
  29002. }
  29003. this._imageProcessingConfiguration.prepareDefines(defines);
  29004. }
  29005. if (defines._areFresnelDirty) {
  29006. if (StandardMaterial.FresnelEnabled) {
  29007. // Fresnel
  29008. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  29009. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  29010. this._reflectionFresnelParameters) {
  29011. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  29012. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  29013. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  29014. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  29015. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  29016. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  29017. defines._needNormals = true;
  29018. defines.FRESNEL = true;
  29019. }
  29020. }
  29021. else {
  29022. defines.FRESNEL = false;
  29023. }
  29024. }
  29025. // Misc.
  29026. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  29027. // Attribs
  29028. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  29029. // Values that need to be evaluated on every frame
  29030. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  29031. if (scene._mirroredCameraPosition && defines.BUMP) {
  29032. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  29033. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  29034. defines.markAsUnprocessed();
  29035. }
  29036. // Get correct effect
  29037. if (defines.isDirty) {
  29038. defines.markAsProcessed();
  29039. scene.resetCachedMaterial();
  29040. // Fallbacks
  29041. var fallbacks = new BABYLON.EffectFallbacks();
  29042. if (defines.REFLECTION) {
  29043. fallbacks.addFallback(0, "REFLECTION");
  29044. }
  29045. if (defines.SPECULAR) {
  29046. fallbacks.addFallback(0, "SPECULAR");
  29047. }
  29048. if (defines.BUMP) {
  29049. fallbacks.addFallback(0, "BUMP");
  29050. }
  29051. if (defines.PARALLAX) {
  29052. fallbacks.addFallback(1, "PARALLAX");
  29053. }
  29054. if (defines.PARALLAXOCCLUSION) {
  29055. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29056. }
  29057. if (defines.SPECULAROVERALPHA) {
  29058. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29059. }
  29060. if (defines.FOG) {
  29061. fallbacks.addFallback(1, "FOG");
  29062. }
  29063. if (defines.POINTSIZE) {
  29064. fallbacks.addFallback(0, "POINTSIZE");
  29065. }
  29066. if (defines.LOGARITHMICDEPTH) {
  29067. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29068. }
  29069. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  29070. if (defines.SPECULARTERM) {
  29071. fallbacks.addFallback(0, "SPECULARTERM");
  29072. }
  29073. if (defines.DIFFUSEFRESNEL) {
  29074. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  29075. }
  29076. if (defines.OPACITYFRESNEL) {
  29077. fallbacks.addFallback(2, "OPACITYFRESNEL");
  29078. }
  29079. if (defines.REFLECTIONFRESNEL) {
  29080. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  29081. }
  29082. if (defines.EMISSIVEFRESNEL) {
  29083. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  29084. }
  29085. if (defines.FRESNEL) {
  29086. fallbacks.addFallback(4, "FRESNEL");
  29087. }
  29088. //Attributes
  29089. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29090. if (defines.NORMAL) {
  29091. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29092. }
  29093. if (defines.UV1) {
  29094. attribs.push(BABYLON.VertexBuffer.UVKind);
  29095. }
  29096. if (defines.UV2) {
  29097. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29098. }
  29099. if (defines.VERTEXCOLOR) {
  29100. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29101. }
  29102. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  29103. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  29104. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  29105. var shaderName = "default";
  29106. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  29107. "vFogInfos", "vFogColor", "pointSize",
  29108. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29109. "mBones",
  29110. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29111. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  29112. "logarithmicDepthConstant"
  29113. ];
  29114. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29115. var uniformBuffers = ["Material", "Scene"];
  29116. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  29117. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  29118. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  29119. uniformsNames: uniforms,
  29120. uniformBuffersNames: uniformBuffers,
  29121. samplers: samplers,
  29122. defines: defines,
  29123. maxSimultaneousLights: this._maxSimultaneousLights
  29124. });
  29125. if (this.customShaderNameResolve) {
  29126. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  29127. }
  29128. var join = defines.toString();
  29129. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  29130. attributes: attribs,
  29131. uniformsNames: uniforms,
  29132. uniformBuffersNames: uniformBuffers,
  29133. samplers: samplers,
  29134. defines: join,
  29135. fallbacks: fallbacks,
  29136. onCompiled: this.onCompiled,
  29137. onError: this.onError,
  29138. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  29139. }, engine), defines);
  29140. this.buildUniformLayout();
  29141. }
  29142. if (!subMesh.effect.isReady()) {
  29143. return false;
  29144. }
  29145. defines._renderId = scene.getRenderId();
  29146. this._wasPreviouslyReady = true;
  29147. return true;
  29148. };
  29149. StandardMaterial.prototype.buildUniformLayout = function () {
  29150. // Order is important !
  29151. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  29152. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  29153. this._uniformBuffer.addUniform("opacityParts", 4);
  29154. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  29155. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  29156. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  29157. this._uniformBuffer.addUniform("refractionRightColor", 4);
  29158. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  29159. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  29160. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  29161. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  29162. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  29163. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  29164. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  29165. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  29166. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  29167. this._uniformBuffer.addUniform("vBumpInfos", 3);
  29168. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  29169. this._uniformBuffer.addUniform("ambientMatrix", 16);
  29170. this._uniformBuffer.addUniform("opacityMatrix", 16);
  29171. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  29172. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  29173. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  29174. this._uniformBuffer.addUniform("specularMatrix", 16);
  29175. this._uniformBuffer.addUniform("bumpMatrix", 16);
  29176. this._uniformBuffer.addUniform("refractionMatrix", 16);
  29177. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  29178. this._uniformBuffer.addUniform("vSpecularColor", 4);
  29179. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  29180. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  29181. this._uniformBuffer.addUniform("pointSize", 1);
  29182. this._uniformBuffer.create();
  29183. };
  29184. StandardMaterial.prototype.unbind = function () {
  29185. if (this._activeEffect) {
  29186. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  29187. this._activeEffect.setTexture("reflection2DSampler", null);
  29188. }
  29189. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  29190. this._activeEffect.setTexture("refraction2DSampler", null);
  29191. }
  29192. }
  29193. _super.prototype.unbind.call(this);
  29194. };
  29195. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29196. var scene = this.getScene();
  29197. var defines = subMesh._materialDefines;
  29198. if (!defines) {
  29199. return;
  29200. }
  29201. var effect = subMesh.effect;
  29202. this._activeEffect = effect;
  29203. // Matrices
  29204. this.bindOnlyWorldMatrix(world);
  29205. // Bones
  29206. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  29207. if (this._mustRebind(scene, effect, mesh.visibility)) {
  29208. this._uniformBuffer.bindToEffect(effect, "Material");
  29209. this.bindViewProjection(effect);
  29210. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  29211. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  29212. // Fresnel
  29213. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29214. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  29215. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  29216. }
  29217. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29218. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29219. }
  29220. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29221. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  29222. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  29223. }
  29224. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29225. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  29226. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  29227. }
  29228. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29229. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29230. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29231. }
  29232. }
  29233. // Textures
  29234. if (scene.texturesEnabled) {
  29235. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29236. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  29237. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  29238. }
  29239. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29240. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  29241. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  29242. }
  29243. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29244. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  29245. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  29246. }
  29247. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29248. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  29249. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  29250. }
  29251. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29252. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  29253. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  29254. }
  29255. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29256. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  29257. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  29258. }
  29259. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29260. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  29261. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  29262. }
  29263. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29264. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  29265. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  29266. }
  29267. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29268. var depth = 1.0;
  29269. if (!this._refractionTexture.isCube) {
  29270. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  29271. if (this._refractionTexture.depth) {
  29272. depth = this._refractionTexture.depth;
  29273. }
  29274. }
  29275. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29276. }
  29277. }
  29278. // Point size
  29279. if (this.pointsCloud) {
  29280. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  29281. }
  29282. if (defines.SPECULARTERM) {
  29283. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  29284. }
  29285. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  29286. // Diffuse
  29287. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  29288. }
  29289. // Textures
  29290. if (scene.texturesEnabled) {
  29291. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29292. effect.setTexture("diffuseSampler", this._diffuseTexture);
  29293. }
  29294. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29295. effect.setTexture("ambientSampler", this._ambientTexture);
  29296. }
  29297. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29298. effect.setTexture("opacitySampler", this._opacityTexture);
  29299. }
  29300. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29301. if (this._reflectionTexture.isCube) {
  29302. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  29303. }
  29304. else {
  29305. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  29306. }
  29307. }
  29308. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29309. effect.setTexture("emissiveSampler", this._emissiveTexture);
  29310. }
  29311. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29312. effect.setTexture("lightmapSampler", this._lightmapTexture);
  29313. }
  29314. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29315. effect.setTexture("specularSampler", this._specularTexture);
  29316. }
  29317. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29318. effect.setTexture("bumpSampler", this._bumpTexture);
  29319. }
  29320. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29321. var depth = 1.0;
  29322. if (this._refractionTexture.isCube) {
  29323. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  29324. }
  29325. else {
  29326. effect.setTexture("refraction2DSampler", this._refractionTexture);
  29327. }
  29328. }
  29329. }
  29330. // Clip plane
  29331. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  29332. // Colors
  29333. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29334. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  29335. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29336. }
  29337. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  29338. // Lights
  29339. if (scene.lightsEnabled && !this._disableLighting) {
  29340. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  29341. }
  29342. // View
  29343. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  29344. this.bindView(effect);
  29345. }
  29346. // Fog
  29347. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  29348. // Morph targets
  29349. if (defines.NUM_MORPH_INFLUENCERS) {
  29350. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  29351. }
  29352. // Log. depth
  29353. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  29354. // image processing
  29355. this._imageProcessingConfiguration.bind(this._activeEffect);
  29356. }
  29357. this._uniformBuffer.update();
  29358. this._afterBind(mesh, this._activeEffect);
  29359. };
  29360. StandardMaterial.prototype.getAnimatables = function () {
  29361. var results = [];
  29362. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  29363. results.push(this._diffuseTexture);
  29364. }
  29365. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  29366. results.push(this._ambientTexture);
  29367. }
  29368. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  29369. results.push(this._opacityTexture);
  29370. }
  29371. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  29372. results.push(this._reflectionTexture);
  29373. }
  29374. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  29375. results.push(this._emissiveTexture);
  29376. }
  29377. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  29378. results.push(this._specularTexture);
  29379. }
  29380. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  29381. results.push(this._bumpTexture);
  29382. }
  29383. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  29384. results.push(this._lightmapTexture);
  29385. }
  29386. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  29387. results.push(this._refractionTexture);
  29388. }
  29389. return results;
  29390. };
  29391. StandardMaterial.prototype.getActiveTextures = function () {
  29392. var activeTextures = _super.prototype.getActiveTextures.call(this);
  29393. if (this._diffuseTexture) {
  29394. activeTextures.push(this._diffuseTexture);
  29395. }
  29396. if (this._ambientTexture) {
  29397. activeTextures.push(this._ambientTexture);
  29398. }
  29399. if (this._opacityTexture) {
  29400. activeTextures.push(this._opacityTexture);
  29401. }
  29402. if (this._reflectionTexture) {
  29403. activeTextures.push(this._reflectionTexture);
  29404. }
  29405. if (this._emissiveTexture) {
  29406. activeTextures.push(this._emissiveTexture);
  29407. }
  29408. if (this._specularTexture) {
  29409. activeTextures.push(this._specularTexture);
  29410. }
  29411. if (this._bumpTexture) {
  29412. activeTextures.push(this._bumpTexture);
  29413. }
  29414. if (this._lightmapTexture) {
  29415. activeTextures.push(this._lightmapTexture);
  29416. }
  29417. if (this._refractionTexture) {
  29418. activeTextures.push(this._refractionTexture);
  29419. }
  29420. return activeTextures;
  29421. };
  29422. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29423. if (forceDisposeTextures) {
  29424. if (this._diffuseTexture) {
  29425. this._diffuseTexture.dispose();
  29426. }
  29427. if (this._ambientTexture) {
  29428. this._ambientTexture.dispose();
  29429. }
  29430. if (this._opacityTexture) {
  29431. this._opacityTexture.dispose();
  29432. }
  29433. if (this._reflectionTexture) {
  29434. this._reflectionTexture.dispose();
  29435. }
  29436. if (this._emissiveTexture) {
  29437. this._emissiveTexture.dispose();
  29438. }
  29439. if (this._specularTexture) {
  29440. this._specularTexture.dispose();
  29441. }
  29442. if (this._bumpTexture) {
  29443. this._bumpTexture.dispose();
  29444. }
  29445. if (this._lightmapTexture) {
  29446. this._lightmapTexture.dispose();
  29447. }
  29448. if (this._refractionTexture) {
  29449. this._refractionTexture.dispose();
  29450. }
  29451. }
  29452. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  29453. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  29454. }
  29455. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29456. };
  29457. StandardMaterial.prototype.clone = function (name) {
  29458. var _this = this;
  29459. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  29460. result.name = name;
  29461. result.id = name;
  29462. return result;
  29463. };
  29464. StandardMaterial.prototype.serialize = function () {
  29465. return BABYLON.SerializationHelper.Serialize(this);
  29466. };
  29467. // Statics
  29468. StandardMaterial.Parse = function (source, scene, rootUrl) {
  29469. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  29470. };
  29471. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  29472. get: function () {
  29473. return StandardMaterial._DiffuseTextureEnabled;
  29474. },
  29475. set: function (value) {
  29476. if (StandardMaterial._DiffuseTextureEnabled === value) {
  29477. return;
  29478. }
  29479. StandardMaterial._DiffuseTextureEnabled = value;
  29480. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29481. },
  29482. enumerable: true,
  29483. configurable: true
  29484. });
  29485. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  29486. get: function () {
  29487. return StandardMaterial._AmbientTextureEnabled;
  29488. },
  29489. set: function (value) {
  29490. if (StandardMaterial._AmbientTextureEnabled === value) {
  29491. return;
  29492. }
  29493. StandardMaterial._AmbientTextureEnabled = value;
  29494. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29495. },
  29496. enumerable: true,
  29497. configurable: true
  29498. });
  29499. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  29500. get: function () {
  29501. return StandardMaterial._OpacityTextureEnabled;
  29502. },
  29503. set: function (value) {
  29504. if (StandardMaterial._OpacityTextureEnabled === value) {
  29505. return;
  29506. }
  29507. StandardMaterial._OpacityTextureEnabled = value;
  29508. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29509. },
  29510. enumerable: true,
  29511. configurable: true
  29512. });
  29513. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  29514. get: function () {
  29515. return StandardMaterial._ReflectionTextureEnabled;
  29516. },
  29517. set: function (value) {
  29518. if (StandardMaterial._ReflectionTextureEnabled === value) {
  29519. return;
  29520. }
  29521. StandardMaterial._ReflectionTextureEnabled = value;
  29522. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29523. },
  29524. enumerable: true,
  29525. configurable: true
  29526. });
  29527. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  29528. get: function () {
  29529. return StandardMaterial._EmissiveTextureEnabled;
  29530. },
  29531. set: function (value) {
  29532. if (StandardMaterial._EmissiveTextureEnabled === value) {
  29533. return;
  29534. }
  29535. StandardMaterial._EmissiveTextureEnabled = value;
  29536. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29537. },
  29538. enumerable: true,
  29539. configurable: true
  29540. });
  29541. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  29542. get: function () {
  29543. return StandardMaterial._SpecularTextureEnabled;
  29544. },
  29545. set: function (value) {
  29546. if (StandardMaterial._SpecularTextureEnabled === value) {
  29547. return;
  29548. }
  29549. StandardMaterial._SpecularTextureEnabled = value;
  29550. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29551. },
  29552. enumerable: true,
  29553. configurable: true
  29554. });
  29555. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  29556. get: function () {
  29557. return StandardMaterial._BumpTextureEnabled;
  29558. },
  29559. set: function (value) {
  29560. if (StandardMaterial._BumpTextureEnabled === value) {
  29561. return;
  29562. }
  29563. StandardMaterial._BumpTextureEnabled = value;
  29564. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29565. },
  29566. enumerable: true,
  29567. configurable: true
  29568. });
  29569. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  29570. get: function () {
  29571. return StandardMaterial._LightmapTextureEnabled;
  29572. },
  29573. set: function (value) {
  29574. if (StandardMaterial._LightmapTextureEnabled === value) {
  29575. return;
  29576. }
  29577. StandardMaterial._LightmapTextureEnabled = value;
  29578. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29579. },
  29580. enumerable: true,
  29581. configurable: true
  29582. });
  29583. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  29584. get: function () {
  29585. return StandardMaterial._RefractionTextureEnabled;
  29586. },
  29587. set: function (value) {
  29588. if (StandardMaterial._RefractionTextureEnabled === value) {
  29589. return;
  29590. }
  29591. StandardMaterial._RefractionTextureEnabled = value;
  29592. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29593. },
  29594. enumerable: true,
  29595. configurable: true
  29596. });
  29597. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  29598. get: function () {
  29599. return StandardMaterial._ColorGradingTextureEnabled;
  29600. },
  29601. set: function (value) {
  29602. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  29603. return;
  29604. }
  29605. StandardMaterial._ColorGradingTextureEnabled = value;
  29606. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29607. },
  29608. enumerable: true,
  29609. configurable: true
  29610. });
  29611. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  29612. get: function () {
  29613. return StandardMaterial._FresnelEnabled;
  29614. },
  29615. set: function (value) {
  29616. if (StandardMaterial._FresnelEnabled === value) {
  29617. return;
  29618. }
  29619. StandardMaterial._FresnelEnabled = value;
  29620. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  29621. },
  29622. enumerable: true,
  29623. configurable: true
  29624. });
  29625. return StandardMaterial;
  29626. }(BABYLON.PushMaterial));
  29627. // Flags used to enable or disable a type of texture for all Standard Materials
  29628. StandardMaterial._DiffuseTextureEnabled = true;
  29629. StandardMaterial._AmbientTextureEnabled = true;
  29630. StandardMaterial._OpacityTextureEnabled = true;
  29631. StandardMaterial._ReflectionTextureEnabled = true;
  29632. StandardMaterial._EmissiveTextureEnabled = true;
  29633. StandardMaterial._SpecularTextureEnabled = true;
  29634. StandardMaterial._BumpTextureEnabled = true;
  29635. StandardMaterial._LightmapTextureEnabled = true;
  29636. StandardMaterial._RefractionTextureEnabled = true;
  29637. StandardMaterial._ColorGradingTextureEnabled = true;
  29638. StandardMaterial._FresnelEnabled = true;
  29639. __decorate([
  29640. BABYLON.serializeAsTexture("diffuseTexture")
  29641. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  29642. __decorate([
  29643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29644. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  29645. __decorate([
  29646. BABYLON.serializeAsTexture("ambientTexture")
  29647. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  29648. __decorate([
  29649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29650. ], StandardMaterial.prototype, "ambientTexture", void 0);
  29651. __decorate([
  29652. BABYLON.serializeAsTexture("opacityTexture")
  29653. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  29654. __decorate([
  29655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29656. ], StandardMaterial.prototype, "opacityTexture", void 0);
  29657. __decorate([
  29658. BABYLON.serializeAsTexture("reflectionTexture")
  29659. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  29660. __decorate([
  29661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29662. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  29663. __decorate([
  29664. BABYLON.serializeAsTexture("emissiveTexture")
  29665. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  29666. __decorate([
  29667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29668. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  29669. __decorate([
  29670. BABYLON.serializeAsTexture("specularTexture")
  29671. ], StandardMaterial.prototype, "_specularTexture", void 0);
  29672. __decorate([
  29673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29674. ], StandardMaterial.prototype, "specularTexture", void 0);
  29675. __decorate([
  29676. BABYLON.serializeAsTexture("bumpTexture")
  29677. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  29678. __decorate([
  29679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29680. ], StandardMaterial.prototype, "bumpTexture", void 0);
  29681. __decorate([
  29682. BABYLON.serializeAsTexture("lightmapTexture")
  29683. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  29684. __decorate([
  29685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29686. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  29687. __decorate([
  29688. BABYLON.serializeAsTexture("refractionTexture")
  29689. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  29690. __decorate([
  29691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29692. ], StandardMaterial.prototype, "refractionTexture", void 0);
  29693. __decorate([
  29694. BABYLON.serializeAsColor3("ambient")
  29695. ], StandardMaterial.prototype, "ambientColor", void 0);
  29696. __decorate([
  29697. BABYLON.serializeAsColor3("diffuse")
  29698. ], StandardMaterial.prototype, "diffuseColor", void 0);
  29699. __decorate([
  29700. BABYLON.serializeAsColor3("specular")
  29701. ], StandardMaterial.prototype, "specularColor", void 0);
  29702. __decorate([
  29703. BABYLON.serializeAsColor3("emissive")
  29704. ], StandardMaterial.prototype, "emissiveColor", void 0);
  29705. __decorate([
  29706. BABYLON.serialize()
  29707. ], StandardMaterial.prototype, "specularPower", void 0);
  29708. __decorate([
  29709. BABYLON.serialize("useAlphaFromDiffuseTexture")
  29710. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  29711. __decorate([
  29712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29713. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  29714. __decorate([
  29715. BABYLON.serialize("useEmissiveAsIllumination")
  29716. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  29717. __decorate([
  29718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29719. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29720. __decorate([
  29721. BABYLON.serialize("linkEmissiveWithDiffuse")
  29722. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  29723. __decorate([
  29724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29725. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  29726. __decorate([
  29727. BABYLON.serialize("useSpecularOverAlpha")
  29728. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  29729. __decorate([
  29730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29731. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  29732. __decorate([
  29733. BABYLON.serialize("useReflectionOverAlpha")
  29734. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  29735. __decorate([
  29736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29737. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  29738. __decorate([
  29739. BABYLON.serialize("disableLighting")
  29740. ], StandardMaterial.prototype, "_disableLighting", void 0);
  29741. __decorate([
  29742. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29743. ], StandardMaterial.prototype, "disableLighting", void 0);
  29744. __decorate([
  29745. BABYLON.serialize("useParallax")
  29746. ], StandardMaterial.prototype, "_useParallax", void 0);
  29747. __decorate([
  29748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29749. ], StandardMaterial.prototype, "useParallax", void 0);
  29750. __decorate([
  29751. BABYLON.serialize("useParallaxOcclusion")
  29752. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  29753. __decorate([
  29754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29755. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  29756. __decorate([
  29757. BABYLON.serialize()
  29758. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  29759. __decorate([
  29760. BABYLON.serialize("roughness")
  29761. ], StandardMaterial.prototype, "_roughness", void 0);
  29762. __decorate([
  29763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29764. ], StandardMaterial.prototype, "roughness", void 0);
  29765. __decorate([
  29766. BABYLON.serialize()
  29767. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  29768. __decorate([
  29769. BABYLON.serialize()
  29770. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  29771. __decorate([
  29772. BABYLON.serialize("useLightmapAsShadowmap")
  29773. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  29774. __decorate([
  29775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29776. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29777. __decorate([
  29778. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  29779. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  29780. __decorate([
  29781. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29782. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  29783. __decorate([
  29784. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  29785. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  29786. __decorate([
  29787. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29788. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  29789. __decorate([
  29790. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  29791. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  29792. __decorate([
  29793. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29794. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  29795. __decorate([
  29796. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  29797. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  29798. __decorate([
  29799. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29800. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  29801. __decorate([
  29802. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  29803. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  29804. __decorate([
  29805. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29806. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  29807. __decorate([
  29808. BABYLON.serialize("useReflectionFresnelFromSpecular")
  29809. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  29810. __decorate([
  29811. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29812. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  29813. __decorate([
  29814. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  29815. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  29816. __decorate([
  29817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29818. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  29819. __decorate([
  29820. BABYLON.serialize("maxSimultaneousLights")
  29821. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  29822. __decorate([
  29823. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29824. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  29825. __decorate([
  29826. BABYLON.serialize("invertNormalMapX")
  29827. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  29828. __decorate([
  29829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29830. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  29831. __decorate([
  29832. BABYLON.serialize("invertNormalMapY")
  29833. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  29834. __decorate([
  29835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29836. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  29837. __decorate([
  29838. BABYLON.serialize("twoSidedLighting")
  29839. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  29840. __decorate([
  29841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29842. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  29843. __decorate([
  29844. BABYLON.serialize()
  29845. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  29846. BABYLON.StandardMaterial = StandardMaterial;
  29847. })(BABYLON || (BABYLON = {}));
  29848. //# sourceMappingURL=babylon.standardMaterial.js.map
  29849. var BABYLON;
  29850. (function (BABYLON) {
  29851. var PBRMaterialDefines = (function (_super) {
  29852. __extends(PBRMaterialDefines, _super);
  29853. function PBRMaterialDefines() {
  29854. var _this = _super.call(this) || this;
  29855. _this.PBR = true;
  29856. _this.ALBEDO = false;
  29857. _this.AMBIENT = false;
  29858. _this.AMBIENTINGRAYSCALE = false;
  29859. _this.OPACITY = false;
  29860. _this.OPACITYRGB = false;
  29861. _this.REFLECTION = false;
  29862. _this.EMISSIVE = false;
  29863. _this.REFLECTIVITY = false;
  29864. _this.BUMP = false;
  29865. _this.PARALLAX = false;
  29866. _this.PARALLAXOCCLUSION = false;
  29867. _this.SPECULAROVERALPHA = false;
  29868. _this.CLIPPLANE = false;
  29869. _this.ALPHATEST = false;
  29870. _this.ALPHABLEND = false;
  29871. _this.ALPHAFROMALBEDO = false;
  29872. _this.POINTSIZE = false;
  29873. _this.FOG = false;
  29874. _this.SPECULARTERM = false;
  29875. _this.NORMAL = false;
  29876. _this.TANGENT = false;
  29877. _this.UV1 = false;
  29878. _this.UV2 = false;
  29879. _this.VERTEXCOLOR = false;
  29880. _this.VERTEXALPHA = false;
  29881. _this.NUM_BONE_INFLUENCERS = 0;
  29882. _this.BonesPerMesh = 0;
  29883. _this.INSTANCES = false;
  29884. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  29885. _this.MICROSURFACEAUTOMATIC = false;
  29886. _this.LIGHTMAP = false;
  29887. _this.USELIGHTMAPASSHADOWMAP = false;
  29888. _this.REFLECTIONMAP_3D = false;
  29889. _this.REFLECTIONMAP_SPHERICAL = false;
  29890. _this.REFLECTIONMAP_PLANAR = false;
  29891. _this.REFLECTIONMAP_CUBIC = false;
  29892. _this.REFLECTIONMAP_PROJECTION = false;
  29893. _this.REFLECTIONMAP_SKYBOX = false;
  29894. _this.REFLECTIONMAP_EXPLICIT = false;
  29895. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29896. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29897. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29898. _this.INVERTCUBICMAP = false;
  29899. _this.LOGARITHMICDEPTH = false;
  29900. _this.USESPHERICALFROMREFLECTIONMAP = false;
  29901. _this.REFRACTION = false;
  29902. _this.REFRACTIONMAP_3D = false;
  29903. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  29904. _this.REFRACTIONMAPINLINEARSPACE = false;
  29905. _this.LODBASEDMICROSFURACE = false;
  29906. _this.USEPHYSICALLIGHTFALLOFF = false;
  29907. _this.RADIANCEOVERALPHA = false;
  29908. _this.USEPMREMREFLECTION = false;
  29909. _this.USEPMREMREFRACTION = false;
  29910. _this.INVERTNORMALMAPX = false;
  29911. _this.INVERTNORMALMAPY = false;
  29912. _this.TWOSIDEDLIGHTING = false;
  29913. _this.SHADOWFLOAT = false;
  29914. _this.NORMALXYSCALE = true;
  29915. _this.USERIGHTHANDEDSYSTEM = false;
  29916. _this.METALLICWORKFLOW = false;
  29917. _this.METALLICMAP = false;
  29918. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  29919. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  29920. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  29921. _this.AOSTOREINMETALMAPRED = false;
  29922. _this.MICROSURFACEMAP = false;
  29923. _this.MORPHTARGETS = false;
  29924. _this.MORPHTARGETS_NORMAL = false;
  29925. _this.MORPHTARGETS_TANGENT = false;
  29926. _this.NUM_MORPH_INFLUENCERS = 0;
  29927. _this.ALPHATESTVALUE = 0.5;
  29928. _this.PREMULTIPLYALPHA = false;
  29929. _this.ALPHAFRESNEL = false;
  29930. _this.IMAGEPROCESSING = false;
  29931. _this.VIGNETTE = false;
  29932. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  29933. _this.VIGNETTEBLENDMODEOPAQUE = false;
  29934. _this.TONEMAPPING = false;
  29935. _this.CONTRAST = false;
  29936. _this.COLORCURVES = false;
  29937. _this.COLORGRADING = false;
  29938. _this.SAMPLER3DGREENDEPTH = false;
  29939. _this.SAMPLER3DBGRMAP = false;
  29940. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  29941. _this.EXPOSURE = false;
  29942. _this.rebuild();
  29943. return _this;
  29944. }
  29945. PBRMaterialDefines.prototype.reset = function () {
  29946. _super.prototype.reset.call(this);
  29947. this.ALPHATESTVALUE = 0.5;
  29948. this.PBR = true;
  29949. };
  29950. return PBRMaterialDefines;
  29951. }(BABYLON.MaterialDefines));
  29952. /**
  29953. * The Physically based material base class of BJS.
  29954. *
  29955. * This offers the main features of a standard PBR material.
  29956. * For more information, please refer to the documentation :
  29957. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  29958. */
  29959. var PBRBaseMaterial = (function (_super) {
  29960. __extends(PBRBaseMaterial, _super);
  29961. /**
  29962. * Instantiates a new PBRMaterial instance.
  29963. *
  29964. * @param name The material name
  29965. * @param scene The scene the material will be use in.
  29966. */
  29967. function PBRBaseMaterial(name, scene) {
  29968. var _this = _super.call(this, name, scene) || this;
  29969. /**
  29970. * Intensity of the direct lights e.g. the four lights available in your scene.
  29971. * This impacts both the direct diffuse and specular highlights.
  29972. */
  29973. _this._directIntensity = 1.0;
  29974. /**
  29975. * Intensity of the emissive part of the material.
  29976. * This helps controlling the emissive effect without modifying the emissive color.
  29977. */
  29978. _this._emissiveIntensity = 1.0;
  29979. /**
  29980. * Intensity of the environment e.g. how much the environment will light the object
  29981. * either through harmonics for rough material or through the refelction for shiny ones.
  29982. */
  29983. _this._environmentIntensity = 1.0;
  29984. /**
  29985. * This is a special control allowing the reduction of the specular highlights coming from the
  29986. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  29987. */
  29988. _this._specularIntensity = 1.0;
  29989. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  29990. /**
  29991. * Debug Control allowing disabling the bump map on this material.
  29992. */
  29993. _this._disableBumpMap = false;
  29994. /**
  29995. * AKA Occlusion Texture Intensity in other nomenclature.
  29996. */
  29997. _this._ambientTextureStrength = 1.0;
  29998. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  29999. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  30000. /**
  30001. * AKA Diffuse Color in other nomenclature.
  30002. */
  30003. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  30004. /**
  30005. * AKA Specular Color in other nomenclature.
  30006. */
  30007. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  30008. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  30009. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  30010. /**
  30011. * AKA Glossiness in other nomenclature.
  30012. */
  30013. _this._microSurface = 0.9;
  30014. /**
  30015. * source material index of refraction (IOR)' / 'destination material IOR.
  30016. */
  30017. _this._indexOfRefraction = 0.66;
  30018. /**
  30019. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  30020. */
  30021. _this._invertRefractionY = false;
  30022. /**
  30023. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  30024. * Materials half opaque for instance using refraction could benefit from this control.
  30025. */
  30026. _this._linkRefractionWithTransparency = false;
  30027. _this._useLightmapAsShadowmap = false;
  30028. /**
  30029. * Specifies that the alpha is coming form the albedo channel alpha channel.
  30030. */
  30031. _this._useAlphaFromAlbedoTexture = false;
  30032. /**
  30033. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  30034. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  30035. */
  30036. _this._useSpecularOverAlpha = true;
  30037. /**
  30038. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  30039. */
  30040. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  30041. /**
  30042. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  30043. */
  30044. _this._useRoughnessFromMetallicTextureAlpha = true;
  30045. /**
  30046. * Specifies if the metallic texture contains the roughness information in its green channel.
  30047. */
  30048. _this._useRoughnessFromMetallicTextureGreen = false;
  30049. /**
  30050. * Specifies if the metallic texture contains the metallness information in its blue channel.
  30051. */
  30052. _this._useMetallnessFromMetallicTextureBlue = false;
  30053. /**
  30054. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  30055. */
  30056. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  30057. /**
  30058. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  30059. */
  30060. _this._useAmbientInGrayScale = false;
  30061. /**
  30062. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  30063. * The material will try to infer what glossiness each pixel should be.
  30064. */
  30065. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  30066. /**
  30067. * BJS is using an harcoded light falloff based on a manually sets up range.
  30068. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  30069. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  30070. */
  30071. _this._usePhysicalLightFalloff = true;
  30072. /**
  30073. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  30074. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  30075. */
  30076. _this._useRadianceOverAlpha = true;
  30077. /**
  30078. * Allows using the bump map in parallax mode.
  30079. */
  30080. _this._useParallax = false;
  30081. /**
  30082. * Allows using the bump map in parallax occlusion mode.
  30083. */
  30084. _this._useParallaxOcclusion = false;
  30085. /**
  30086. * Controls the scale bias of the parallax mode.
  30087. */
  30088. _this._parallaxScaleBias = 0.05;
  30089. /**
  30090. * If sets to true, disables all the lights affecting the material.
  30091. */
  30092. _this._disableLighting = false;
  30093. /**
  30094. * Number of Simultaneous lights allowed on the material.
  30095. */
  30096. _this._maxSimultaneousLights = 4;
  30097. /**
  30098. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30099. */
  30100. _this._invertNormalMapX = false;
  30101. /**
  30102. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30103. */
  30104. _this._invertNormalMapY = false;
  30105. /**
  30106. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30107. */
  30108. _this._twoSidedLighting = false;
  30109. /**
  30110. * Defines the alpha limits in alpha test mode.
  30111. */
  30112. _this._alphaCutOff = 0.4;
  30113. /**
  30114. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  30115. */
  30116. _this._forceAlphaTest = false;
  30117. /**
  30118. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  30119. * in your scene composition.
  30120. */
  30121. _this._premultiplyAlpha = false;
  30122. /**
  30123. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  30124. * And/Or occlude the blended part.
  30125. */
  30126. _this._useAlphaFresnel = false;
  30127. _this._renderTargets = new BABYLON.SmartArray(16);
  30128. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30129. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30130. _this._tempColor = new BABYLON.Color3();
  30131. // Setup the default processing configuration to the scene.
  30132. _this._attachImageProcessingConfiguration(null);
  30133. _this.getRenderTargetTextures = function () {
  30134. _this._renderTargets.reset();
  30135. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30136. _this._renderTargets.push(_this._reflectionTexture);
  30137. }
  30138. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30139. _this._renderTargets.push(_this._refractionTexture);
  30140. }
  30141. return _this._renderTargets;
  30142. };
  30143. return _this;
  30144. }
  30145. /**
  30146. * Attaches a new image processing configuration to the PBR Material.
  30147. * @param configuration
  30148. */
  30149. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30150. var _this = this;
  30151. if (configuration === this._imageProcessingConfiguration) {
  30152. return;
  30153. }
  30154. // Detaches observer.
  30155. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30156. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30157. }
  30158. // Pick the scene configuration if needed.
  30159. if (!configuration) {
  30160. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30161. }
  30162. else {
  30163. this._imageProcessingConfiguration = configuration;
  30164. }
  30165. // Attaches observer.
  30166. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30167. _this._markAllSubMeshesAsImageProcessingDirty();
  30168. });
  30169. };
  30170. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  30171. get: function () {
  30172. return this._useLogarithmicDepth;
  30173. },
  30174. set: function (value) {
  30175. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30176. },
  30177. enumerable: true,
  30178. configurable: true
  30179. });
  30180. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  30181. if (this._linkRefractionWithTransparency) {
  30182. return false;
  30183. }
  30184. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  30185. };
  30186. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  30187. if (this._forceAlphaTest) {
  30188. return true;
  30189. }
  30190. if (this._linkRefractionWithTransparency) {
  30191. return false;
  30192. }
  30193. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  30194. };
  30195. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30196. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  30197. };
  30198. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  30199. return this._albedoTexture;
  30200. };
  30201. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30202. if (this.isFrozen) {
  30203. if (this._wasPreviouslyReady) {
  30204. return true;
  30205. }
  30206. }
  30207. if (!subMesh._materialDefines) {
  30208. subMesh._materialDefines = new PBRMaterialDefines();
  30209. }
  30210. var scene = this.getScene();
  30211. var defines = subMesh._materialDefines;
  30212. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30213. if (defines._renderId === scene.getRenderId()) {
  30214. return true;
  30215. }
  30216. }
  30217. var engine = scene.getEngine();
  30218. // Lights
  30219. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30220. defines._needNormals = true;
  30221. // Textures
  30222. if (defines._areTexturesDirty) {
  30223. defines._needUVs = false;
  30224. if (scene.texturesEnabled) {
  30225. if (scene.getEngine().getCaps().textureLOD) {
  30226. defines.LODBASEDMICROSFURACE = true;
  30227. }
  30228. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30229. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  30230. return false;
  30231. }
  30232. defines._needUVs = true;
  30233. defines.ALBEDO = true;
  30234. }
  30235. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30236. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30237. return false;
  30238. }
  30239. defines._needUVs = true;
  30240. defines.AMBIENT = true;
  30241. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  30242. }
  30243. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30244. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30245. return false;
  30246. }
  30247. defines._needUVs = true;
  30248. defines.OPACITY = true;
  30249. if (this._opacityTexture.getAlphaFromRGB) {
  30250. defines.OPACITYRGB = true;
  30251. }
  30252. }
  30253. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  30254. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30255. if (!reflectionTexture.isReadyOrNotBlocking()) {
  30256. return false;
  30257. }
  30258. defines.REFLECTION = true;
  30259. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  30260. defines.INVERTCUBICMAP = true;
  30261. }
  30262. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  30263. switch (reflectionTexture.coordinatesMode) {
  30264. case BABYLON.Texture.CUBIC_MODE:
  30265. case BABYLON.Texture.INVCUBIC_MODE:
  30266. defines.REFLECTIONMAP_CUBIC = true;
  30267. break;
  30268. case BABYLON.Texture.EXPLICIT_MODE:
  30269. defines.REFLECTIONMAP_EXPLICIT = true;
  30270. break;
  30271. case BABYLON.Texture.PLANAR_MODE:
  30272. defines.REFLECTIONMAP_PLANAR = true;
  30273. break;
  30274. case BABYLON.Texture.PROJECTION_MODE:
  30275. defines.REFLECTIONMAP_PROJECTION = true;
  30276. break;
  30277. case BABYLON.Texture.SKYBOX_MODE:
  30278. defines.REFLECTIONMAP_SKYBOX = true;
  30279. break;
  30280. case BABYLON.Texture.SPHERICAL_MODE:
  30281. defines.REFLECTIONMAP_SPHERICAL = true;
  30282. break;
  30283. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30284. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  30285. break;
  30286. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30287. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  30288. break;
  30289. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30290. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  30291. break;
  30292. }
  30293. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  30294. defines.USESPHERICALFROMREFLECTIONMAP = true;
  30295. if (reflectionTexture.isPMREM) {
  30296. defines.USEPMREMREFLECTION = true;
  30297. }
  30298. }
  30299. }
  30300. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30301. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30302. return false;
  30303. }
  30304. defines._needUVs = true;
  30305. defines.LIGHTMAP = true;
  30306. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30307. }
  30308. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30309. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30310. return false;
  30311. }
  30312. defines._needUVs = true;
  30313. defines.EMISSIVE = true;
  30314. }
  30315. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30316. if (this._metallicTexture) {
  30317. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  30318. return false;
  30319. }
  30320. defines._needUVs = true;
  30321. defines.METALLICWORKFLOW = true;
  30322. defines.METALLICMAP = true;
  30323. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  30324. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  30325. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  30326. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  30327. }
  30328. else if (this._reflectivityTexture) {
  30329. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  30330. return false;
  30331. }
  30332. defines._needUVs = true;
  30333. defines.REFLECTIVITY = true;
  30334. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  30335. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  30336. }
  30337. if (this._microSurfaceTexture) {
  30338. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  30339. return false;
  30340. }
  30341. defines._needUVs = true;
  30342. defines.MICROSURFACEMAP = true;
  30343. }
  30344. }
  30345. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30346. // Bump texure can not be none blocking.
  30347. if (!this._bumpTexture.isReady()) {
  30348. return false;
  30349. }
  30350. defines._needUVs = true;
  30351. defines.BUMP = true;
  30352. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30353. defines.PARALLAX = true;
  30354. if (this._useParallaxOcclusion) {
  30355. defines.PARALLAXOCCLUSION = true;
  30356. }
  30357. }
  30358. if (this._invertNormalMapX) {
  30359. defines.INVERTNORMALMAPX = true;
  30360. }
  30361. if (this._invertNormalMapY) {
  30362. defines.INVERTNORMALMAPY = true;
  30363. }
  30364. if (scene._mirroredCameraPosition) {
  30365. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  30366. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  30367. }
  30368. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  30369. }
  30370. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30371. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30372. return false;
  30373. }
  30374. defines._needUVs = true;
  30375. defines.REFRACTION = true;
  30376. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30377. if (this._linkRefractionWithTransparency) {
  30378. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  30379. }
  30380. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  30381. defines.REFRACTIONMAPINLINEARSPACE = true;
  30382. if (this._refractionTexture.isPMREM) {
  30383. defines.USEPMREMREFRACTION = true;
  30384. }
  30385. }
  30386. }
  30387. if (this._shouldUseAlphaFromAlbedoTexture()) {
  30388. defines.ALPHAFROMALBEDO = true;
  30389. }
  30390. }
  30391. if (this._useSpecularOverAlpha) {
  30392. defines.SPECULAROVERALPHA = true;
  30393. }
  30394. if (this._usePhysicalLightFalloff) {
  30395. defines.USEPHYSICALLIGHTFALLOFF = true;
  30396. }
  30397. if (this._useRadianceOverAlpha) {
  30398. defines.RADIANCEOVERALPHA = true;
  30399. }
  30400. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  30401. defines.METALLICWORKFLOW = true;
  30402. }
  30403. if (!this.backFaceCulling && this._twoSidedLighting) {
  30404. defines.TWOSIDEDLIGHTING = true;
  30405. }
  30406. defines.ALPHATESTVALUE = this._alphaCutOff;
  30407. defines.PREMULTIPLYALPHA = this._premultiplyAlpha;
  30408. defines.ALPHABLEND = this.needAlphaBlending();
  30409. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  30410. }
  30411. if (defines._areImageProcessingDirty) {
  30412. if (!this._imageProcessingConfiguration.isReady()) {
  30413. return false;
  30414. }
  30415. this._imageProcessingConfiguration.prepareDefines(defines);
  30416. }
  30417. // Misc.
  30418. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  30419. // Values that need to be evaluated on every frame
  30420. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  30421. // Attribs
  30422. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  30423. if (mesh) {
  30424. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30425. mesh.createNormals(true);
  30426. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  30427. }
  30428. }
  30429. }
  30430. // Get correct effect
  30431. if (defines.isDirty) {
  30432. defines.markAsProcessed();
  30433. scene.resetCachedMaterial();
  30434. // Fallbacks
  30435. var fallbacks = new BABYLON.EffectFallbacks();
  30436. if (defines.REFLECTION) {
  30437. fallbacks.addFallback(0, "REFLECTION");
  30438. }
  30439. if (defines.REFRACTION) {
  30440. fallbacks.addFallback(0, "REFRACTION");
  30441. }
  30442. if (defines.REFLECTIVITY) {
  30443. fallbacks.addFallback(0, "REFLECTIVITY");
  30444. }
  30445. if (defines.BUMP) {
  30446. fallbacks.addFallback(0, "BUMP");
  30447. }
  30448. if (defines.PARALLAX) {
  30449. fallbacks.addFallback(1, "PARALLAX");
  30450. }
  30451. if (defines.PARALLAXOCCLUSION) {
  30452. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30453. }
  30454. if (defines.SPECULAROVERALPHA) {
  30455. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30456. }
  30457. if (defines.FOG) {
  30458. fallbacks.addFallback(1, "FOG");
  30459. }
  30460. if (defines.POINTSIZE) {
  30461. fallbacks.addFallback(0, "POINTSIZE");
  30462. }
  30463. if (defines.LOGARITHMICDEPTH) {
  30464. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30465. }
  30466. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  30467. if (defines.SPECULARTERM) {
  30468. fallbacks.addFallback(0, "SPECULARTERM");
  30469. }
  30470. if (defines.NUM_BONE_INFLUENCERS > 0) {
  30471. fallbacks.addCPUSkinningFallback(0, mesh);
  30472. }
  30473. //Attributes
  30474. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30475. if (defines.NORMAL) {
  30476. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30477. }
  30478. if (defines.TANGENT) {
  30479. attribs.push(BABYLON.VertexBuffer.TangentKind);
  30480. }
  30481. if (defines.UV1) {
  30482. attribs.push(BABYLON.VertexBuffer.UVKind);
  30483. }
  30484. if (defines.UV2) {
  30485. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30486. }
  30487. if (defines.VERTEXCOLOR) {
  30488. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30489. }
  30490. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  30491. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  30492. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  30493. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  30494. "vFogInfos", "vFogColor", "pointSize",
  30495. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30496. "mBones",
  30497. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30498. "vLightingIntensity",
  30499. "logarithmicDepthConstant",
  30500. "vSphericalX", "vSphericalY", "vSphericalZ",
  30501. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  30502. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  30503. "vMicrosurfaceTextureLods"
  30504. ];
  30505. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30506. var uniformBuffers = ["Material", "Scene"];
  30507. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  30508. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  30509. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30510. uniformsNames: uniforms,
  30511. uniformBuffersNames: uniformBuffers,
  30512. samplers: samplers,
  30513. defines: defines,
  30514. maxSimultaneousLights: this._maxSimultaneousLights
  30515. });
  30516. var onCompiled = function (effect) {
  30517. if (this.onCompiled) {
  30518. this.onCompiled(effect);
  30519. }
  30520. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  30521. }.bind(this);
  30522. var join = defines.toString();
  30523. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  30524. attributes: attribs,
  30525. uniformsNames: uniforms,
  30526. uniformBuffersNames: uniformBuffers,
  30527. samplers: samplers,
  30528. defines: join,
  30529. fallbacks: fallbacks,
  30530. onCompiled: onCompiled,
  30531. onError: this.onError,
  30532. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  30533. }, engine), defines);
  30534. this.buildUniformLayout();
  30535. }
  30536. if (!subMesh.effect.isReady()) {
  30537. return false;
  30538. }
  30539. defines._renderId = scene.getRenderId();
  30540. this._wasPreviouslyReady = true;
  30541. return true;
  30542. };
  30543. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  30544. // Order is important !
  30545. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  30546. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  30547. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30548. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30549. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30550. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  30551. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  30552. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30553. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30554. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30555. this._uniformBuffer.addUniform("albedoMatrix", 16);
  30556. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30557. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30558. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30559. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30560. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  30561. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  30562. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30563. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30564. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30565. this._uniformBuffer.addUniform("vReflectionColor", 3);
  30566. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  30567. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  30568. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  30569. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  30570. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30571. this._uniformBuffer.addUniform("pointSize", 1);
  30572. this._uniformBuffer.create();
  30573. };
  30574. PBRBaseMaterial.prototype.unbind = function () {
  30575. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30576. this._uniformBuffer.setTexture("reflection2DSampler", null);
  30577. }
  30578. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30579. this._uniformBuffer.setTexture("refraction2DSampler", null);
  30580. }
  30581. _super.prototype.unbind.call(this);
  30582. };
  30583. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30584. this._activeEffect.setMatrix("world", world);
  30585. };
  30586. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30587. var scene = this.getScene();
  30588. var defines = subMesh._materialDefines;
  30589. if (!defines) {
  30590. return;
  30591. }
  30592. var effect = subMesh.effect;
  30593. this._activeEffect = effect;
  30594. // Matrices
  30595. this.bindOnlyWorldMatrix(world);
  30596. // Bones
  30597. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  30598. if (this._mustRebind(scene, effect, mesh.visibility)) {
  30599. this._uniformBuffer.bindToEffect(effect, "Material");
  30600. this.bindViewProjection(effect);
  30601. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30602. // Texture uniforms
  30603. if (scene.texturesEnabled) {
  30604. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30605. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  30606. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  30607. }
  30608. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30609. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  30610. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  30611. }
  30612. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30613. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30614. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  30615. }
  30616. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  30617. ;
  30618. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30619. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  30620. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  30621. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  30622. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  30623. this._activeEffect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  30624. this._activeEffect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  30625. this._activeEffect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  30626. this._activeEffect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  30627. this._activeEffect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  30628. this._activeEffect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  30629. this._activeEffect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  30630. this._activeEffect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  30631. this._activeEffect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  30632. }
  30633. }
  30634. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30635. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30636. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  30637. }
  30638. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30639. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30640. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  30641. }
  30642. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30643. if (this._metallicTexture) {
  30644. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  30645. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  30646. }
  30647. else if (this._reflectivityTexture) {
  30648. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  30649. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  30650. }
  30651. if (this._microSurfaceTexture) {
  30652. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  30653. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  30654. }
  30655. }
  30656. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30657. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  30658. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  30659. }
  30660. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30661. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  30662. var depth = 1.0;
  30663. if (!this._refractionTexture.isCube) {
  30664. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30665. if (this._refractionTexture.depth) {
  30666. depth = this._refractionTexture.depth;
  30667. }
  30668. }
  30669. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  30670. }
  30671. if ((reflectionTexture || this._refractionTexture)) {
  30672. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  30673. }
  30674. }
  30675. // Point size
  30676. if (this.pointsCloud) {
  30677. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30678. }
  30679. // Colors
  30680. if (defines.METALLICWORKFLOW) {
  30681. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  30682. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  30683. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  30684. }
  30685. else {
  30686. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  30687. }
  30688. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  30689. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  30690. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  30691. // Misc
  30692. this._lightingInfos.x = this._directIntensity;
  30693. this._lightingInfos.y = this._emissiveIntensity;
  30694. this._lightingInfos.z = this._environmentIntensity;
  30695. this._lightingInfos.w = this._specularIntensity;
  30696. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  30697. }
  30698. // Textures
  30699. if (scene.texturesEnabled) {
  30700. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30701. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  30702. }
  30703. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30704. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  30705. }
  30706. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30707. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  30708. }
  30709. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30710. if (reflectionTexture.isCube) {
  30711. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  30712. }
  30713. else {
  30714. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  30715. }
  30716. }
  30717. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30718. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  30719. }
  30720. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30721. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  30722. }
  30723. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30724. if (this._metallicTexture) {
  30725. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  30726. }
  30727. else if (this._reflectivityTexture) {
  30728. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  30729. }
  30730. if (this._microSurfaceTexture) {
  30731. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  30732. }
  30733. }
  30734. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30735. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  30736. }
  30737. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30738. if (this._refractionTexture.isCube) {
  30739. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  30740. }
  30741. else {
  30742. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  30743. }
  30744. }
  30745. }
  30746. // Clip plane
  30747. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  30748. // Colors
  30749. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  30750. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  30751. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30752. }
  30753. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  30754. // Lights
  30755. if (scene.lightsEnabled && !this._disableLighting) {
  30756. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  30757. }
  30758. // View
  30759. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  30760. this.bindView(effect);
  30761. }
  30762. // Fog
  30763. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  30764. // Morph targets
  30765. if (defines.NUM_MORPH_INFLUENCERS) {
  30766. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  30767. }
  30768. // image processing
  30769. this._imageProcessingConfiguration.bind(this._activeEffect);
  30770. // Log. depth
  30771. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  30772. }
  30773. this._uniformBuffer.update();
  30774. this._afterBind(mesh);
  30775. scene = null;
  30776. };
  30777. PBRBaseMaterial.prototype.getAnimatables = function () {
  30778. var results = [];
  30779. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  30780. results.push(this._albedoTexture);
  30781. }
  30782. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30783. results.push(this._ambientTexture);
  30784. }
  30785. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30786. results.push(this._opacityTexture);
  30787. }
  30788. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30789. results.push(this._reflectionTexture);
  30790. }
  30791. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30792. results.push(this._emissiveTexture);
  30793. }
  30794. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  30795. results.push(this._metallicTexture);
  30796. }
  30797. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  30798. results.push(this._reflectivityTexture);
  30799. }
  30800. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30801. results.push(this._bumpTexture);
  30802. }
  30803. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30804. results.push(this._lightmapTexture);
  30805. }
  30806. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30807. results.push(this._refractionTexture);
  30808. }
  30809. return results;
  30810. };
  30811. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30812. if (forceDisposeTextures) {
  30813. if (this._albedoTexture) {
  30814. this._albedoTexture.dispose();
  30815. }
  30816. if (this._ambientTexture) {
  30817. this._ambientTexture.dispose();
  30818. }
  30819. if (this._opacityTexture) {
  30820. this._opacityTexture.dispose();
  30821. }
  30822. if (this._reflectionTexture) {
  30823. this._reflectionTexture.dispose();
  30824. }
  30825. if (this._emissiveTexture) {
  30826. this._emissiveTexture.dispose();
  30827. }
  30828. if (this._metallicTexture) {
  30829. this._metallicTexture.dispose();
  30830. }
  30831. if (this._reflectivityTexture) {
  30832. this._reflectivityTexture.dispose();
  30833. }
  30834. if (this._bumpTexture) {
  30835. this._bumpTexture.dispose();
  30836. }
  30837. if (this._lightmapTexture) {
  30838. this._lightmapTexture.dispose();
  30839. }
  30840. if (this._refractionTexture) {
  30841. this._refractionTexture.dispose();
  30842. }
  30843. }
  30844. this._renderTargets.dispose();
  30845. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30846. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30847. }
  30848. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30849. };
  30850. return PBRBaseMaterial;
  30851. }(BABYLON.PushMaterial));
  30852. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  30853. __decorate([
  30854. BABYLON.serializeAsImageProcessingConfiguration()
  30855. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  30856. __decorate([
  30857. BABYLON.serialize()
  30858. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  30859. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  30860. })(BABYLON || (BABYLON = {}));
  30861. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  30862. var BABYLON;
  30863. (function (BABYLON) {
  30864. var Internals;
  30865. (function (Internals) {
  30866. /**
  30867. * The Physically based simple base material of BJS.
  30868. *
  30869. * This enables better naming and convention enforcements on top of the pbrMaterial.
  30870. * It is used as the base class for both the specGloss and metalRough conventions.
  30871. */
  30872. var PBRBaseSimpleMaterial = (function (_super) {
  30873. __extends(PBRBaseSimpleMaterial, _super);
  30874. /**
  30875. * Instantiates a new PBRMaterial instance.
  30876. *
  30877. * @param name The material name
  30878. * @param scene The scene the material will be use in.
  30879. */
  30880. function PBRBaseSimpleMaterial(name, scene) {
  30881. var _this = _super.call(this, name, scene) || this;
  30882. /**
  30883. * Number of Simultaneous lights allowed on the material.
  30884. */
  30885. _this.maxSimultaneousLights = 4;
  30886. /**
  30887. * If sets to true, disables all the lights affecting the material.
  30888. */
  30889. _this.disableLighting = false;
  30890. /**
  30891. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30892. */
  30893. _this.invertNormalMapX = false;
  30894. /**
  30895. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30896. */
  30897. _this.invertNormalMapY = false;
  30898. /**
  30899. * Emissivie color used to self-illuminate the model.
  30900. */
  30901. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30902. /**
  30903. * Occlusion Channel Strenght.
  30904. */
  30905. _this.occlusionStrength = 1.0;
  30906. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30907. _this._useAmbientInGrayScale = true;
  30908. return _this;
  30909. }
  30910. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  30911. /**
  30912. * Gets the current transparency mode.
  30913. */
  30914. get: function () {
  30915. return this._transparencyMode;
  30916. },
  30917. /**
  30918. * Sets the transparency mode of the material.
  30919. */
  30920. set: function (value) {
  30921. if (this._transparencyMode === value) {
  30922. return;
  30923. }
  30924. this._transparencyMode = value;
  30925. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  30926. this._forceAlphaTest = true;
  30927. }
  30928. else {
  30929. this._forceAlphaTest = false;
  30930. }
  30931. this._markAllSubMeshesAsTexturesDirty();
  30932. },
  30933. enumerable: true,
  30934. configurable: true
  30935. });
  30936. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  30937. /**
  30938. * Gets the current double sided mode.
  30939. */
  30940. get: function () {
  30941. return this._twoSidedLighting;
  30942. },
  30943. /**
  30944. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30945. */
  30946. set: function (value) {
  30947. if (this._twoSidedLighting === value) {
  30948. return;
  30949. }
  30950. this._twoSidedLighting = value;
  30951. this.backFaceCulling = !value;
  30952. this._markAllSubMeshesAsTexturesDirty();
  30953. },
  30954. enumerable: true,
  30955. configurable: true
  30956. });
  30957. /**
  30958. * Specifies wether or not the alpha value of the albedo texture should be used.
  30959. */
  30960. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30961. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30962. };
  30963. /**
  30964. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  30965. */
  30966. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  30967. if (this._linkRefractionWithTransparency) {
  30968. return false;
  30969. }
  30970. return (this.alpha < 1.0) ||
  30971. (this._shouldUseAlphaFromAlbedoTexture() &&
  30972. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  30973. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  30974. };
  30975. /**
  30976. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  30977. */
  30978. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  30979. if (this._linkRefractionWithTransparency) {
  30980. return false;
  30981. }
  30982. return this._shouldUseAlphaFromAlbedoTexture() &&
  30983. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  30984. };
  30985. return PBRBaseSimpleMaterial;
  30986. }(BABYLON.PBRBaseMaterial));
  30987. __decorate([
  30988. BABYLON.serialize(),
  30989. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30990. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  30991. __decorate([
  30992. BABYLON.serialize(),
  30993. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30994. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  30995. __decorate([
  30996. BABYLON.serializeAsTexture(),
  30997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  30998. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  30999. __decorate([
  31000. BABYLON.serialize(),
  31001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31002. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  31003. __decorate([
  31004. BABYLON.serialize(),
  31005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31006. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  31007. __decorate([
  31008. BABYLON.serializeAsTexture(),
  31009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  31010. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  31011. __decorate([
  31012. BABYLON.serializeAsColor3("emissive"),
  31013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31014. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  31015. __decorate([
  31016. BABYLON.serializeAsTexture(),
  31017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31018. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  31019. __decorate([
  31020. BABYLON.serialize(),
  31021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  31022. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  31023. __decorate([
  31024. BABYLON.serializeAsTexture(),
  31025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  31026. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  31027. __decorate([
  31028. BABYLON.serialize(),
  31029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  31030. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  31031. __decorate([
  31032. BABYLON.serialize()
  31033. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  31034. __decorate([
  31035. BABYLON.serialize()
  31036. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  31037. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  31038. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31039. })(BABYLON || (BABYLON = {}));
  31040. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  31041. var BABYLON;
  31042. (function (BABYLON) {
  31043. /**
  31044. * The Physically based material of BJS.
  31045. *
  31046. * This offers the main features of a standard PBR material.
  31047. * For more information, please refer to the documentation :
  31048. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31049. */
  31050. var PBRMaterial = (function (_super) {
  31051. __extends(PBRMaterial, _super);
  31052. /**
  31053. * Instantiates a new PBRMaterial instance.
  31054. *
  31055. * @param name The material name
  31056. * @param scene The scene the material will be use in.
  31057. */
  31058. function PBRMaterial(name, scene) {
  31059. var _this = _super.call(this, name, scene) || this;
  31060. /**
  31061. * Intensity of the direct lights e.g. the four lights available in your scene.
  31062. * This impacts both the direct diffuse and specular highlights.
  31063. */
  31064. _this.directIntensity = 1.0;
  31065. /**
  31066. * Intensity of the emissive part of the material.
  31067. * This helps controlling the emissive effect without modifying the emissive color.
  31068. */
  31069. _this.emissiveIntensity = 1.0;
  31070. /**
  31071. * Intensity of the environment e.g. how much the environment will light the object
  31072. * either through harmonics for rough material or through the refelction for shiny ones.
  31073. */
  31074. _this.environmentIntensity = 1.0;
  31075. /**
  31076. * This is a special control allowing the reduction of the specular highlights coming from the
  31077. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31078. */
  31079. _this.specularIntensity = 1.0;
  31080. /**
  31081. * Debug Control allowing disabling the bump map on this material.
  31082. */
  31083. _this.disableBumpMap = false;
  31084. /**
  31085. * AKA Occlusion Texture Intensity in other nomenclature.
  31086. */
  31087. _this.ambientTextureStrength = 1.0;
  31088. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  31089. /**
  31090. * AKA Diffuse Color in other nomenclature.
  31091. */
  31092. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  31093. /**
  31094. * AKA Specular Color in other nomenclature.
  31095. */
  31096. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31097. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  31098. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  31099. /**
  31100. * AKA Glossiness in other nomenclature.
  31101. */
  31102. _this.microSurface = 0.9;
  31103. /**
  31104. * source material index of refraction (IOR)' / 'destination material IOR.
  31105. */
  31106. _this.indexOfRefraction = 0.66;
  31107. /**
  31108. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31109. */
  31110. _this.invertRefractionY = false;
  31111. /**
  31112. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31113. * Materials half opaque for instance using refraction could benefit from this control.
  31114. */
  31115. _this.linkRefractionWithTransparency = false;
  31116. _this.useLightmapAsShadowmap = false;
  31117. /**
  31118. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31119. */
  31120. _this.useAlphaFromAlbedoTexture = false;
  31121. /**
  31122. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31123. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31124. */
  31125. _this.useSpecularOverAlpha = true;
  31126. /**
  31127. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31128. */
  31129. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  31130. /**
  31131. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31132. */
  31133. _this.useRoughnessFromMetallicTextureAlpha = true;
  31134. /**
  31135. * Specifies if the metallic texture contains the roughness information in its green channel.
  31136. */
  31137. _this.useRoughnessFromMetallicTextureGreen = false;
  31138. /**
  31139. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31140. */
  31141. _this.useMetallnessFromMetallicTextureBlue = false;
  31142. /**
  31143. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31144. */
  31145. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  31146. /**
  31147. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31148. */
  31149. _this.useAmbientInGrayScale = false;
  31150. /**
  31151. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31152. * The material will try to infer what glossiness each pixel should be.
  31153. */
  31154. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  31155. /**
  31156. * BJS is using an harcoded light falloff based on a manually sets up range.
  31157. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  31158. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  31159. */
  31160. _this.usePhysicalLightFalloff = true;
  31161. /**
  31162. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  31163. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  31164. */
  31165. _this.useRadianceOverAlpha = true;
  31166. /**
  31167. * Allows using the bump map in parallax mode.
  31168. */
  31169. _this.useParallax = false;
  31170. /**
  31171. * Allows using the bump map in parallax occlusion mode.
  31172. */
  31173. _this.useParallaxOcclusion = false;
  31174. /**
  31175. * Controls the scale bias of the parallax mode.
  31176. */
  31177. _this.parallaxScaleBias = 0.05;
  31178. /**
  31179. * If sets to true, disables all the lights affecting the material.
  31180. */
  31181. _this.disableLighting = false;
  31182. /**
  31183. * Number of Simultaneous lights allowed on the material.
  31184. */
  31185. _this.maxSimultaneousLights = 4;
  31186. /**
  31187. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  31188. */
  31189. _this.invertNormalMapX = false;
  31190. /**
  31191. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  31192. */
  31193. _this.invertNormalMapY = false;
  31194. /**
  31195. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31196. */
  31197. _this.twoSidedLighting = false;
  31198. /**
  31199. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  31200. * in your scene composition.
  31201. */
  31202. _this.premultiplyAlpha = false;
  31203. /**
  31204. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31205. * And/Or occlude the blended part.
  31206. */
  31207. _this.useAlphaFresnel = false;
  31208. return _this;
  31209. }
  31210. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  31211. /**
  31212. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  31213. */
  31214. get: function () {
  31215. return this._PBRMATERIAL_OPAQUE;
  31216. },
  31217. enumerable: true,
  31218. configurable: true
  31219. });
  31220. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  31221. /**
  31222. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  31223. */
  31224. get: function () {
  31225. return this._PBRMATERIAL_ALPHATEST;
  31226. },
  31227. enumerable: true,
  31228. configurable: true
  31229. });
  31230. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  31231. /**
  31232. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  31233. */
  31234. get: function () {
  31235. return this._PBRMATERIAL_ALPHABLEND;
  31236. },
  31237. enumerable: true,
  31238. configurable: true
  31239. });
  31240. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  31241. /**
  31242. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  31243. * They are also discarded below the alpha cutoff threshold to improve performances.
  31244. */
  31245. get: function () {
  31246. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  31247. },
  31248. enumerable: true,
  31249. configurable: true
  31250. });
  31251. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  31252. /**
  31253. * Gets the image processing configuration used either in this material.
  31254. */
  31255. get: function () {
  31256. return this._imageProcessingConfiguration;
  31257. },
  31258. /**
  31259. * Sets the Default image processing configuration used either in the this material.
  31260. *
  31261. * If sets to null, the scene one is in use.
  31262. */
  31263. set: function (value) {
  31264. this._attachImageProcessingConfiguration(value);
  31265. // Ensure the effect will be rebuilt.
  31266. this._markAllSubMeshesAsTexturesDirty();
  31267. },
  31268. enumerable: true,
  31269. configurable: true
  31270. });
  31271. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  31272. /**
  31273. * Gets wether the color curves effect is enabled.
  31274. */
  31275. get: function () {
  31276. return this.imageProcessingConfiguration.colorCurvesEnabled;
  31277. },
  31278. /**
  31279. * Sets wether the color curves effect is enabled.
  31280. */
  31281. set: function (value) {
  31282. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  31283. },
  31284. enumerable: true,
  31285. configurable: true
  31286. });
  31287. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  31288. /**
  31289. * Gets wether the color grading effect is enabled.
  31290. */
  31291. get: function () {
  31292. return this.imageProcessingConfiguration.colorGradingEnabled;
  31293. },
  31294. /**
  31295. * Gets wether the color grading effect is enabled.
  31296. */
  31297. set: function (value) {
  31298. this.imageProcessingConfiguration.colorGradingEnabled = value;
  31299. },
  31300. enumerable: true,
  31301. configurable: true
  31302. });
  31303. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  31304. /**
  31305. * Gets wether tonemapping is enabled or not.
  31306. */
  31307. get: function () {
  31308. return this._imageProcessingConfiguration.toneMappingEnabled;
  31309. },
  31310. /**
  31311. * Sets wether tonemapping is enabled or not
  31312. */
  31313. set: function (value) {
  31314. this._imageProcessingConfiguration.toneMappingEnabled = value;
  31315. },
  31316. enumerable: true,
  31317. configurable: true
  31318. });
  31319. ;
  31320. ;
  31321. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  31322. /**
  31323. * The camera exposure used on this material.
  31324. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  31325. * This corresponds to a photographic exposure.
  31326. */
  31327. get: function () {
  31328. return this._imageProcessingConfiguration.exposure;
  31329. },
  31330. /**
  31331. * The camera exposure used on this material.
  31332. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  31333. * This corresponds to a photographic exposure.
  31334. */
  31335. set: function (value) {
  31336. this._imageProcessingConfiguration.exposure = value;
  31337. },
  31338. enumerable: true,
  31339. configurable: true
  31340. });
  31341. ;
  31342. ;
  31343. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  31344. /**
  31345. * Gets The camera contrast used on this material.
  31346. */
  31347. get: function () {
  31348. return this._imageProcessingConfiguration.contrast;
  31349. },
  31350. /**
  31351. * Sets The camera contrast used on this material.
  31352. */
  31353. set: function (value) {
  31354. this._imageProcessingConfiguration.contrast = value;
  31355. },
  31356. enumerable: true,
  31357. configurable: true
  31358. });
  31359. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  31360. /**
  31361. * Gets the Color Grading 2D Lookup Texture.
  31362. */
  31363. get: function () {
  31364. return this._imageProcessingConfiguration.colorGradingTexture;
  31365. },
  31366. /**
  31367. * Sets the Color Grading 2D Lookup Texture.
  31368. */
  31369. set: function (value) {
  31370. this._imageProcessingConfiguration.colorGradingTexture = value;
  31371. },
  31372. enumerable: true,
  31373. configurable: true
  31374. });
  31375. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  31376. /**
  31377. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  31378. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  31379. * 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;
  31380. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  31381. */
  31382. get: function () {
  31383. return this._imageProcessingConfiguration.colorCurves;
  31384. },
  31385. /**
  31386. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  31387. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  31388. * 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;
  31389. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  31390. */
  31391. set: function (value) {
  31392. this._imageProcessingConfiguration.colorCurves = value;
  31393. },
  31394. enumerable: true,
  31395. configurable: true
  31396. });
  31397. PBRMaterial.prototype.getClassName = function () {
  31398. return "PBRMaterial";
  31399. };
  31400. PBRMaterial.prototype.getActiveTextures = function () {
  31401. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31402. if (this._albedoTexture) {
  31403. activeTextures.push(this._albedoTexture);
  31404. }
  31405. if (this._ambientTexture) {
  31406. activeTextures.push(this._ambientTexture);
  31407. }
  31408. if (this._opacityTexture) {
  31409. activeTextures.push(this._opacityTexture);
  31410. }
  31411. if (this._reflectionTexture) {
  31412. activeTextures.push(this._reflectionTexture);
  31413. }
  31414. if (this._emissiveTexture) {
  31415. activeTextures.push(this._emissiveTexture);
  31416. }
  31417. if (this._reflectionTexture) {
  31418. activeTextures.push(this._reflectionTexture);
  31419. }
  31420. if (this._metallicTexture) {
  31421. activeTextures.push(this._metallicTexture);
  31422. }
  31423. if (this._microSurfaceTexture) {
  31424. activeTextures.push(this._microSurfaceTexture);
  31425. }
  31426. if (this._bumpTexture) {
  31427. activeTextures.push(this._bumpTexture);
  31428. }
  31429. if (this._lightmapTexture) {
  31430. activeTextures.push(this._lightmapTexture);
  31431. }
  31432. if (this._refractionTexture) {
  31433. activeTextures.push(this._refractionTexture);
  31434. }
  31435. return activeTextures;
  31436. };
  31437. PBRMaterial.prototype.clone = function (name) {
  31438. var _this = this;
  31439. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  31440. };
  31441. PBRMaterial.prototype.serialize = function () {
  31442. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31443. serializationObject.customType = "BABYLON.PBRMaterial";
  31444. return serializationObject;
  31445. };
  31446. // Statics
  31447. PBRMaterial.Parse = function (source, scene, rootUrl) {
  31448. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  31449. };
  31450. return PBRMaterial;
  31451. }(BABYLON.PBRBaseMaterial));
  31452. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  31453. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  31454. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  31455. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  31456. __decorate([
  31457. BABYLON.serialize(),
  31458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31459. ], PBRMaterial.prototype, "directIntensity", void 0);
  31460. __decorate([
  31461. BABYLON.serialize(),
  31462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31463. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  31464. __decorate([
  31465. BABYLON.serialize(),
  31466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31467. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  31468. __decorate([
  31469. BABYLON.serialize(),
  31470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31471. ], PBRMaterial.prototype, "specularIntensity", void 0);
  31472. __decorate([
  31473. BABYLON.serialize(),
  31474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31475. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  31476. __decorate([
  31477. BABYLON.serializeAsTexture(),
  31478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31479. ], PBRMaterial.prototype, "albedoTexture", void 0);
  31480. __decorate([
  31481. BABYLON.serializeAsTexture(),
  31482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31483. ], PBRMaterial.prototype, "ambientTexture", void 0);
  31484. __decorate([
  31485. BABYLON.serialize(),
  31486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31487. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  31488. __decorate([
  31489. BABYLON.serializeAsTexture(),
  31490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31491. ], PBRMaterial.prototype, "opacityTexture", void 0);
  31492. __decorate([
  31493. BABYLON.serializeAsTexture(),
  31494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31495. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  31496. __decorate([
  31497. BABYLON.serializeAsTexture(),
  31498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31499. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  31500. __decorate([
  31501. BABYLON.serializeAsTexture(),
  31502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31503. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  31504. __decorate([
  31505. BABYLON.serializeAsTexture(),
  31506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31507. ], PBRMaterial.prototype, "metallicTexture", void 0);
  31508. __decorate([
  31509. BABYLON.serialize(),
  31510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31511. ], PBRMaterial.prototype, "metallic", void 0);
  31512. __decorate([
  31513. BABYLON.serialize(),
  31514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31515. ], PBRMaterial.prototype, "roughness", void 0);
  31516. __decorate([
  31517. BABYLON.serializeAsTexture(),
  31518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31519. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  31520. __decorate([
  31521. BABYLON.serializeAsTexture(),
  31522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31523. ], PBRMaterial.prototype, "bumpTexture", void 0);
  31524. __decorate([
  31525. BABYLON.serializeAsTexture(),
  31526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  31527. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  31528. __decorate([
  31529. BABYLON.serializeAsTexture(),
  31530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31531. ], PBRMaterial.prototype, "refractionTexture", void 0);
  31532. __decorate([
  31533. BABYLON.serializeAsColor3("ambient"),
  31534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31535. ], PBRMaterial.prototype, "ambientColor", void 0);
  31536. __decorate([
  31537. BABYLON.serializeAsColor3("albedo"),
  31538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31539. ], PBRMaterial.prototype, "albedoColor", void 0);
  31540. __decorate([
  31541. BABYLON.serializeAsColor3("reflectivity"),
  31542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31543. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  31544. __decorate([
  31545. BABYLON.serializeAsColor3("reflection"),
  31546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31547. ], PBRMaterial.prototype, "reflectionColor", void 0);
  31548. __decorate([
  31549. BABYLON.serializeAsColor3("emissive"),
  31550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31551. ], PBRMaterial.prototype, "emissiveColor", void 0);
  31552. __decorate([
  31553. BABYLON.serialize(),
  31554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31555. ], PBRMaterial.prototype, "microSurface", void 0);
  31556. __decorate([
  31557. BABYLON.serialize(),
  31558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31559. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  31560. __decorate([
  31561. BABYLON.serialize(),
  31562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31563. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  31564. __decorate([
  31565. BABYLON.serialize(),
  31566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31567. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  31568. __decorate([
  31569. BABYLON.serialize(),
  31570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31571. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31572. __decorate([
  31573. BABYLON.serialize(),
  31574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31575. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  31576. __decorate([
  31577. BABYLON.serialize(),
  31578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31579. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  31580. __decorate([
  31581. BABYLON.serialize(),
  31582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31583. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  31584. __decorate([
  31585. BABYLON.serialize(),
  31586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31587. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  31588. __decorate([
  31589. BABYLON.serialize(),
  31590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31591. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  31592. __decorate([
  31593. BABYLON.serialize(),
  31594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31595. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  31596. __decorate([
  31597. BABYLON.serialize(),
  31598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31599. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  31600. __decorate([
  31601. BABYLON.serialize(),
  31602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31603. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  31604. __decorate([
  31605. BABYLON.serialize(),
  31606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31607. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  31608. __decorate([
  31609. BABYLON.serialize(),
  31610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31611. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  31612. __decorate([
  31613. BABYLON.serialize(),
  31614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31615. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  31616. __decorate([
  31617. BABYLON.serialize(),
  31618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31619. ], PBRMaterial.prototype, "useParallax", void 0);
  31620. __decorate([
  31621. BABYLON.serialize(),
  31622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31623. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  31624. __decorate([
  31625. BABYLON.serialize(),
  31626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31627. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  31628. __decorate([
  31629. BABYLON.serialize(),
  31630. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31631. ], PBRMaterial.prototype, "disableLighting", void 0);
  31632. __decorate([
  31633. BABYLON.serialize(),
  31634. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31635. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  31636. __decorate([
  31637. BABYLON.serialize(),
  31638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31639. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  31640. __decorate([
  31641. BABYLON.serialize(),
  31642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31643. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  31644. __decorate([
  31645. BABYLON.serialize(),
  31646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31647. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  31648. __decorate([
  31649. BABYLON.serialize(),
  31650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31651. ], PBRMaterial.prototype, "premultiplyAlpha", void 0);
  31652. __decorate([
  31653. BABYLON.serialize(),
  31654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31655. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  31656. BABYLON.PBRMaterial = PBRMaterial;
  31657. })(BABYLON || (BABYLON = {}));
  31658. //# sourceMappingURL=babylon.pbrMaterial.js.map
  31659. var BABYLON;
  31660. (function (BABYLON) {
  31661. /**
  31662. * The PBR material of BJS following the metal roughness convention.
  31663. *
  31664. * This fits to the define PBR convention in the GLTF definition:
  31665. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  31666. */
  31667. var PBRMetallicRoughnessMaterial = (function (_super) {
  31668. __extends(PBRMetallicRoughnessMaterial, _super);
  31669. /**
  31670. * Instantiates a new PBRMetalRoughnessMaterial instance.
  31671. *
  31672. * @param name The material name
  31673. * @param scene The scene the material will be use in.
  31674. */
  31675. function PBRMetallicRoughnessMaterial(name, scene) {
  31676. var _this = _super.call(this, name, scene) || this;
  31677. _this._useRoughnessFromMetallicTextureGreen = true;
  31678. _this._useMetallnessFromMetallicTextureBlue = true;
  31679. return _this;
  31680. }
  31681. /**
  31682. * Return the currrent class name of the material.
  31683. */
  31684. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  31685. return "PBRMetallicRoughnessMaterial";
  31686. };
  31687. /**
  31688. * Return the active textures of the material.
  31689. */
  31690. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  31691. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31692. if (this.baseTexture) {
  31693. activeTextures.push(this.baseTexture);
  31694. }
  31695. if (this.metallicRoughnessTexture) {
  31696. activeTextures.push(this.metallicRoughnessTexture);
  31697. }
  31698. return activeTextures;
  31699. };
  31700. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  31701. var _this = this;
  31702. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  31703. };
  31704. /**
  31705. * Serialize the material to a parsable JSON object.
  31706. */
  31707. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  31708. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31709. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  31710. return serializationObject;
  31711. };
  31712. /**
  31713. * Parses a JSON object correponding to the serialize function.
  31714. */
  31715. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  31716. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  31717. };
  31718. return PBRMetallicRoughnessMaterial;
  31719. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31720. __decorate([
  31721. BABYLON.serializeAsTexture(),
  31722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  31723. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  31724. __decorate([
  31725. BABYLON.serializeAsTexture(),
  31726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  31727. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  31728. __decorate([
  31729. BABYLON.serialize(),
  31730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31731. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  31732. __decorate([
  31733. BABYLON.serialize(),
  31734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31735. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  31736. __decorate([
  31737. BABYLON.serializeAsTexture(),
  31738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  31739. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  31740. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  31741. })(BABYLON || (BABYLON = {}));
  31742. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  31743. var BABYLON;
  31744. (function (BABYLON) {
  31745. /**
  31746. * The PBR material of BJS following the specular glossiness convention.
  31747. *
  31748. * This fits to the define PBR convention in the GLTF definition:
  31749. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  31750. */
  31751. var PBRSpecularGlossinessMaterial = (function (_super) {
  31752. __extends(PBRSpecularGlossinessMaterial, _super);
  31753. /**
  31754. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  31755. *
  31756. * @param name The material name
  31757. * @param scene The scene the material will be use in.
  31758. */
  31759. function PBRSpecularGlossinessMaterial(name, scene) {
  31760. var _this = _super.call(this, name, scene) || this;
  31761. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  31762. return _this;
  31763. }
  31764. /**
  31765. * Return the currrent class name of the material.
  31766. */
  31767. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  31768. return "PBRSpecularGlossinessMaterial";
  31769. };
  31770. /**
  31771. * Return the active textures of the material.
  31772. */
  31773. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  31774. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31775. if (this.diffuseTexture) {
  31776. activeTextures.push(this.diffuseTexture);
  31777. }
  31778. if (this.specularGlossinessTexture) {
  31779. activeTextures.push(this.specularGlossinessTexture);
  31780. }
  31781. return activeTextures;
  31782. };
  31783. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  31784. var _this = this;
  31785. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  31786. };
  31787. /**
  31788. * Serialize the material to a parsable JSON object.
  31789. */
  31790. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  31791. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31792. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  31793. return serializationObject;
  31794. };
  31795. /**
  31796. * Parses a JSON object correponding to the serialize function.
  31797. */
  31798. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  31799. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  31800. };
  31801. return PBRSpecularGlossinessMaterial;
  31802. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31803. __decorate([
  31804. BABYLON.serializeAsColor3(),
  31805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  31806. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  31807. __decorate([
  31808. BABYLON.serializeAsTexture(),
  31809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  31810. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  31811. __decorate([
  31812. BABYLON.serializeAsColor3(),
  31813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  31814. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  31815. __decorate([
  31816. BABYLON.serialize(),
  31817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  31818. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  31819. __decorate([
  31820. BABYLON.serializeAsTexture(),
  31821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  31822. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  31823. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  31824. })(BABYLON || (BABYLON = {}));
  31825. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  31826. var BABYLON;
  31827. (function (BABYLON) {
  31828. BABYLON.CameraInputTypes = {};
  31829. var CameraInputsManager = (function () {
  31830. function CameraInputsManager(camera) {
  31831. this.attached = {};
  31832. this.camera = camera;
  31833. this.checkInputs = function () { };
  31834. }
  31835. CameraInputsManager.prototype.add = function (input) {
  31836. var type = input.getSimpleName();
  31837. if (this.attached[type]) {
  31838. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31839. return;
  31840. }
  31841. this.attached[type] = input;
  31842. input.camera = this.camera;
  31843. //for checkInputs, we are dynamically creating a function
  31844. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31845. if (input.checkInputs) {
  31846. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31847. }
  31848. if (this.attachedElement) {
  31849. input.attachControl(this.attachedElement);
  31850. }
  31851. };
  31852. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31853. for (var cam in this.attached) {
  31854. var input = this.attached[cam];
  31855. if (input === inputToRemove) {
  31856. input.detachControl(this.attachedElement);
  31857. delete this.attached[cam];
  31858. this.rebuildInputCheck();
  31859. }
  31860. }
  31861. };
  31862. CameraInputsManager.prototype.removeByType = function (inputType) {
  31863. for (var cam in this.attached) {
  31864. var input = this.attached[cam];
  31865. if (input.getTypeName() === inputType) {
  31866. input.detachControl(this.attachedElement);
  31867. delete this.attached[cam];
  31868. this.rebuildInputCheck();
  31869. }
  31870. }
  31871. };
  31872. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31873. var current = this.checkInputs;
  31874. return function () {
  31875. current();
  31876. fn();
  31877. };
  31878. };
  31879. CameraInputsManager.prototype.attachInput = function (input) {
  31880. input.attachControl(this.attachedElement, this.noPreventDefault);
  31881. };
  31882. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31883. if (this.attachedElement) {
  31884. return;
  31885. }
  31886. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31887. this.attachedElement = element;
  31888. this.noPreventDefault = noPreventDefault;
  31889. for (var cam in this.attached) {
  31890. var input = this.attached[cam];
  31891. this.attached[cam].attachControl(element, noPreventDefault);
  31892. }
  31893. };
  31894. CameraInputsManager.prototype.detachElement = function (element) {
  31895. if (this.attachedElement !== element) {
  31896. return;
  31897. }
  31898. for (var cam in this.attached) {
  31899. var input = this.attached[cam];
  31900. this.attached[cam].detachControl(element);
  31901. }
  31902. this.attachedElement = null;
  31903. };
  31904. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31905. this.checkInputs = function () { };
  31906. for (var cam in this.attached) {
  31907. var input = this.attached[cam];
  31908. if (input.checkInputs) {
  31909. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31910. }
  31911. }
  31912. };
  31913. CameraInputsManager.prototype.clear = function () {
  31914. if (this.attachedElement) {
  31915. this.detachElement(this.attachedElement);
  31916. }
  31917. this.attached = {};
  31918. this.attachedElement = null;
  31919. this.checkInputs = function () { };
  31920. };
  31921. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31922. var inputs = {};
  31923. for (var cam in this.attached) {
  31924. var input = this.attached[cam];
  31925. var res = BABYLON.SerializationHelper.Serialize(input);
  31926. inputs[input.getTypeName()] = res;
  31927. }
  31928. serializedCamera.inputsmgr = inputs;
  31929. };
  31930. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31931. var parsedInputs = parsedCamera.inputsmgr;
  31932. if (parsedInputs) {
  31933. this.clear();
  31934. for (var n in parsedInputs) {
  31935. var construct = BABYLON.CameraInputTypes[n];
  31936. if (construct) {
  31937. var parsedinput = parsedInputs[n];
  31938. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31939. this.add(input);
  31940. }
  31941. }
  31942. }
  31943. else {
  31944. //2016-03-08 this part is for managing backward compatibility
  31945. for (var n in this.attached) {
  31946. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31947. if (construct) {
  31948. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31949. this.remove(this.attached[n]);
  31950. this.add(input);
  31951. }
  31952. }
  31953. }
  31954. };
  31955. return CameraInputsManager;
  31956. }());
  31957. BABYLON.CameraInputsManager = CameraInputsManager;
  31958. })(BABYLON || (BABYLON = {}));
  31959. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31960. var BABYLON;
  31961. (function (BABYLON) {
  31962. var FreeCameraMouseInput = (function () {
  31963. function FreeCameraMouseInput(touchEnabled) {
  31964. if (touchEnabled === void 0) { touchEnabled = true; }
  31965. this.touchEnabled = touchEnabled;
  31966. this.buttons = [0, 1, 2];
  31967. this.angularSensibility = 2000.0;
  31968. }
  31969. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  31970. var _this = this;
  31971. var engine = this.camera.getEngine();
  31972. if (!this._pointerInput) {
  31973. this._pointerInput = function (p, s) {
  31974. var evt = p.event;
  31975. if (!_this.touchEnabled && evt.pointerType === "touch") {
  31976. return;
  31977. }
  31978. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31979. return;
  31980. }
  31981. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31982. try {
  31983. evt.srcElement.setPointerCapture(evt.pointerId);
  31984. }
  31985. catch (e) {
  31986. //Nothing to do with the error. Execution will continue.
  31987. }
  31988. _this.previousPosition = {
  31989. x: evt.clientX,
  31990. y: evt.clientY
  31991. };
  31992. if (!noPreventDefault) {
  31993. evt.preventDefault();
  31994. element.focus();
  31995. }
  31996. }
  31997. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31998. try {
  31999. evt.srcElement.releasePointerCapture(evt.pointerId);
  32000. }
  32001. catch (e) {
  32002. //Nothing to do with the error.
  32003. }
  32004. _this.previousPosition = null;
  32005. if (!noPreventDefault) {
  32006. evt.preventDefault();
  32007. }
  32008. }
  32009. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32010. if (!_this.previousPosition || engine.isPointerLock) {
  32011. return;
  32012. }
  32013. var offsetX = evt.clientX - _this.previousPosition.x;
  32014. var offsetY = evt.clientY - _this.previousPosition.y;
  32015. if (_this.camera.getScene().useRightHandedSystem) {
  32016. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  32017. }
  32018. else {
  32019. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  32020. }
  32021. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  32022. _this.previousPosition = {
  32023. x: evt.clientX,
  32024. y: evt.clientY
  32025. };
  32026. if (!noPreventDefault) {
  32027. evt.preventDefault();
  32028. }
  32029. }
  32030. };
  32031. }
  32032. this._onMouseMove = function (evt) {
  32033. if (!engine.isPointerLock) {
  32034. return;
  32035. }
  32036. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32037. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32038. if (_this.camera.getScene().useRightHandedSystem) {
  32039. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  32040. }
  32041. else {
  32042. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  32043. }
  32044. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  32045. _this.previousPosition = null;
  32046. if (!noPreventDefault) {
  32047. evt.preventDefault();
  32048. }
  32049. };
  32050. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  32051. element.addEventListener("mousemove", this._onMouseMove, false);
  32052. };
  32053. FreeCameraMouseInput.prototype.detachControl = function (element) {
  32054. if (this._observer && element) {
  32055. this.camera.getScene().onPointerObservable.remove(this._observer);
  32056. element.removeEventListener("mousemove", this._onMouseMove);
  32057. this._observer = null;
  32058. this._onMouseMove = null;
  32059. this.previousPosition = null;
  32060. }
  32061. };
  32062. FreeCameraMouseInput.prototype.getTypeName = function () {
  32063. return "FreeCameraMouseInput";
  32064. };
  32065. FreeCameraMouseInput.prototype.getSimpleName = function () {
  32066. return "mouse";
  32067. };
  32068. return FreeCameraMouseInput;
  32069. }());
  32070. __decorate([
  32071. BABYLON.serialize()
  32072. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  32073. __decorate([
  32074. BABYLON.serialize()
  32075. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  32076. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  32077. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  32078. })(BABYLON || (BABYLON = {}));
  32079. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  32080. var BABYLON;
  32081. (function (BABYLON) {
  32082. var FreeCameraKeyboardMoveInput = (function () {
  32083. function FreeCameraKeyboardMoveInput() {
  32084. this._keys = [];
  32085. this.keysUp = [38];
  32086. this.keysDown = [40];
  32087. this.keysLeft = [37];
  32088. this.keysRight = [39];
  32089. }
  32090. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32091. var _this = this;
  32092. if (!this._onKeyDown) {
  32093. element.tabIndex = 1;
  32094. this._onKeyDown = function (evt) {
  32095. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32096. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32097. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32098. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32099. var index = _this._keys.indexOf(evt.keyCode);
  32100. if (index === -1) {
  32101. _this._keys.push(evt.keyCode);
  32102. }
  32103. if (!noPreventDefault) {
  32104. evt.preventDefault();
  32105. }
  32106. }
  32107. };
  32108. this._onKeyUp = function (evt) {
  32109. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32110. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32111. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32112. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32113. var index = _this._keys.indexOf(evt.keyCode);
  32114. if (index >= 0) {
  32115. _this._keys.splice(index, 1);
  32116. }
  32117. if (!noPreventDefault) {
  32118. evt.preventDefault();
  32119. }
  32120. }
  32121. };
  32122. element.addEventListener("keydown", this._onKeyDown, false);
  32123. element.addEventListener("keyup", this._onKeyUp, false);
  32124. BABYLON.Tools.RegisterTopRootEvents([
  32125. { name: "blur", handler: this._onLostFocus }
  32126. ]);
  32127. }
  32128. };
  32129. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32130. if (this._onKeyDown) {
  32131. element.removeEventListener("keydown", this._onKeyDown);
  32132. element.removeEventListener("keyup", this._onKeyUp);
  32133. BABYLON.Tools.UnregisterTopRootEvents([
  32134. { name: "blur", handler: this._onLostFocus }
  32135. ]);
  32136. this._keys = [];
  32137. this._onKeyDown = null;
  32138. this._onKeyUp = null;
  32139. }
  32140. };
  32141. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32142. if (this._onKeyDown) {
  32143. var camera = this.camera;
  32144. // Keyboard
  32145. for (var index = 0; index < this._keys.length; index++) {
  32146. var keyCode = this._keys[index];
  32147. var speed = camera._computeLocalCameraSpeed();
  32148. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32149. camera._localDirection.copyFromFloats(-speed, 0, 0);
  32150. }
  32151. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32152. camera._localDirection.copyFromFloats(0, 0, speed);
  32153. }
  32154. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32155. camera._localDirection.copyFromFloats(speed, 0, 0);
  32156. }
  32157. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32158. camera._localDirection.copyFromFloats(0, 0, -speed);
  32159. }
  32160. if (camera.getScene().useRightHandedSystem) {
  32161. camera._localDirection.z *= -1;
  32162. }
  32163. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  32164. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  32165. camera.cameraDirection.addInPlace(camera._transformedDirection);
  32166. }
  32167. }
  32168. };
  32169. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32170. return "FreeCameraKeyboardMoveInput";
  32171. };
  32172. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  32173. this._keys = [];
  32174. };
  32175. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32176. return "keyboard";
  32177. };
  32178. return FreeCameraKeyboardMoveInput;
  32179. }());
  32180. __decorate([
  32181. BABYLON.serialize()
  32182. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32183. __decorate([
  32184. BABYLON.serialize()
  32185. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32186. __decorate([
  32187. BABYLON.serialize()
  32188. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32189. __decorate([
  32190. BABYLON.serialize()
  32191. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32192. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  32193. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  32194. })(BABYLON || (BABYLON = {}));
  32195. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  32196. var BABYLON;
  32197. (function (BABYLON) {
  32198. var FreeCameraInputsManager = (function (_super) {
  32199. __extends(FreeCameraInputsManager, _super);
  32200. function FreeCameraInputsManager(camera) {
  32201. return _super.call(this, camera) || this;
  32202. }
  32203. FreeCameraInputsManager.prototype.addKeyboard = function () {
  32204. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  32205. return this;
  32206. };
  32207. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  32208. if (touchEnabled === void 0) { touchEnabled = true; }
  32209. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  32210. return this;
  32211. };
  32212. FreeCameraInputsManager.prototype.addGamepad = function () {
  32213. this.add(new BABYLON.FreeCameraGamepadInput());
  32214. return this;
  32215. };
  32216. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  32217. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  32218. return this;
  32219. };
  32220. FreeCameraInputsManager.prototype.addTouch = function () {
  32221. this.add(new BABYLON.FreeCameraTouchInput());
  32222. return this;
  32223. };
  32224. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  32225. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  32226. return this;
  32227. };
  32228. return FreeCameraInputsManager;
  32229. }(BABYLON.CameraInputsManager));
  32230. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  32231. })(BABYLON || (BABYLON = {}));
  32232. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  32233. /// <reference path="babylon.camera.ts" />
  32234. var BABYLON;
  32235. (function (BABYLON) {
  32236. var TargetCamera = (function (_super) {
  32237. __extends(TargetCamera, _super);
  32238. function TargetCamera(name, position, scene) {
  32239. var _this = _super.call(this, name, position, scene) || this;
  32240. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  32241. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  32242. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  32243. _this.speed = 2.0;
  32244. _this.noRotationConstraint = false;
  32245. _this.lockedTarget = null;
  32246. _this._currentTarget = BABYLON.Vector3.Zero();
  32247. _this._viewMatrix = BABYLON.Matrix.Zero();
  32248. _this._camMatrix = BABYLON.Matrix.Zero();
  32249. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  32250. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  32251. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  32252. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  32253. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  32254. _this._lookAtTemp = BABYLON.Matrix.Zero();
  32255. _this._tempMatrix = BABYLON.Matrix.Zero();
  32256. return _this;
  32257. }
  32258. TargetCamera.prototype.getFrontPosition = function (distance) {
  32259. var direction = this.getTarget().subtract(this.position);
  32260. direction.normalize();
  32261. direction.scaleInPlace(distance);
  32262. return this.globalPosition.add(direction);
  32263. };
  32264. TargetCamera.prototype._getLockedTargetPosition = function () {
  32265. if (!this.lockedTarget) {
  32266. return null;
  32267. }
  32268. if (this.lockedTarget.absolutePosition) {
  32269. this.lockedTarget.computeWorldMatrix();
  32270. }
  32271. return this.lockedTarget.absolutePosition || this.lockedTarget;
  32272. };
  32273. // Cache
  32274. TargetCamera.prototype._initCache = function () {
  32275. _super.prototype._initCache.call(this);
  32276. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32277. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32278. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32279. };
  32280. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  32281. if (!ignoreParentClass) {
  32282. _super.prototype._updateCache.call(this);
  32283. }
  32284. var lockedTargetPosition = this._getLockedTargetPosition();
  32285. if (!lockedTargetPosition) {
  32286. this._cache.lockedTarget = null;
  32287. }
  32288. else {
  32289. if (!this._cache.lockedTarget) {
  32290. this._cache.lockedTarget = lockedTargetPosition.clone();
  32291. }
  32292. else {
  32293. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  32294. }
  32295. }
  32296. this._cache.rotation.copyFrom(this.rotation);
  32297. if (this.rotationQuaternion)
  32298. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32299. };
  32300. // Synchronized
  32301. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  32302. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  32303. return false;
  32304. }
  32305. var lockedTargetPosition = this._getLockedTargetPosition();
  32306. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  32307. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  32308. };
  32309. // Methods
  32310. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  32311. var engine = this.getEngine();
  32312. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  32313. };
  32314. // Target
  32315. TargetCamera.prototype.setTarget = function (target) {
  32316. this.upVector.normalize();
  32317. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  32318. this._camMatrix.invert();
  32319. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  32320. var vDir = target.subtract(this.position);
  32321. if (vDir.x >= 0.0) {
  32322. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  32323. }
  32324. else {
  32325. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  32326. }
  32327. this.rotation.z = 0;
  32328. if (isNaN(this.rotation.x)) {
  32329. this.rotation.x = 0;
  32330. }
  32331. if (isNaN(this.rotation.y)) {
  32332. this.rotation.y = 0;
  32333. }
  32334. if (isNaN(this.rotation.z)) {
  32335. this.rotation.z = 0;
  32336. }
  32337. if (this.rotationQuaternion) {
  32338. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  32339. }
  32340. };
  32341. /**
  32342. * Return the current target position of the camera. This value is expressed in local space.
  32343. */
  32344. TargetCamera.prototype.getTarget = function () {
  32345. return this._currentTarget;
  32346. };
  32347. TargetCamera.prototype._decideIfNeedsToMove = function () {
  32348. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  32349. };
  32350. TargetCamera.prototype._updatePosition = function () {
  32351. if (this.parent) {
  32352. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  32353. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  32354. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  32355. return;
  32356. }
  32357. this.position.addInPlace(this.cameraDirection);
  32358. };
  32359. TargetCamera.prototype._checkInputs = function () {
  32360. var needToMove = this._decideIfNeedsToMove();
  32361. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  32362. // Move
  32363. if (needToMove) {
  32364. this._updatePosition();
  32365. }
  32366. // Rotate
  32367. if (needToRotate) {
  32368. this.rotation.x += this.cameraRotation.x;
  32369. this.rotation.y += this.cameraRotation.y;
  32370. //rotate, if quaternion is set and rotation was used
  32371. if (this.rotationQuaternion) {
  32372. var len = this.rotation.lengthSquared();
  32373. if (len) {
  32374. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  32375. }
  32376. }
  32377. if (!this.noRotationConstraint) {
  32378. var limit = (Math.PI / 2) * 0.95;
  32379. if (this.rotation.x > limit)
  32380. this.rotation.x = limit;
  32381. if (this.rotation.x < -limit)
  32382. this.rotation.x = -limit;
  32383. }
  32384. }
  32385. // Inertia
  32386. if (needToMove) {
  32387. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  32388. this.cameraDirection.x = 0;
  32389. }
  32390. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  32391. this.cameraDirection.y = 0;
  32392. }
  32393. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  32394. this.cameraDirection.z = 0;
  32395. }
  32396. this.cameraDirection.scaleInPlace(this.inertia);
  32397. }
  32398. if (needToRotate) {
  32399. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  32400. this.cameraRotation.x = 0;
  32401. }
  32402. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  32403. this.cameraRotation.y = 0;
  32404. }
  32405. this.cameraRotation.scaleInPlace(this.inertia);
  32406. }
  32407. _super.prototype._checkInputs.call(this);
  32408. };
  32409. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  32410. if (this.rotationQuaternion) {
  32411. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  32412. //update the up vector!
  32413. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  32414. }
  32415. else {
  32416. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  32417. }
  32418. };
  32419. TargetCamera.prototype._getViewMatrix = function () {
  32420. if (!this.lockedTarget) {
  32421. // Compute
  32422. this._updateCameraRotationMatrix();
  32423. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  32424. // Computing target and final matrix
  32425. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  32426. }
  32427. else {
  32428. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  32429. }
  32430. if (this.getScene().useRightHandedSystem) {
  32431. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  32432. }
  32433. else {
  32434. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  32435. }
  32436. return this._viewMatrix;
  32437. };
  32438. /**
  32439. * @override
  32440. * Override Camera.createRigCamera
  32441. */
  32442. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32443. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  32444. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  32445. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  32446. if (!this.rotationQuaternion) {
  32447. this.rotationQuaternion = new BABYLON.Quaternion();
  32448. }
  32449. rigCamera._cameraRigParams = {};
  32450. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  32451. }
  32452. return rigCamera;
  32453. }
  32454. return null;
  32455. };
  32456. /**
  32457. * @override
  32458. * Override Camera._updateRigCameras
  32459. */
  32460. TargetCamera.prototype._updateRigCameras = function () {
  32461. var camLeft = this._rigCameras[0];
  32462. var camRight = this._rigCameras[1];
  32463. switch (this.cameraRigMode) {
  32464. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32465. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32466. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32467. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32468. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  32469. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  32470. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  32471. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  32472. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  32473. camLeft.setTarget(this.getTarget());
  32474. camRight.setTarget(this.getTarget());
  32475. break;
  32476. case BABYLON.Camera.RIG_MODE_VR:
  32477. if (camLeft.rotationQuaternion) {
  32478. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32479. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32480. }
  32481. else {
  32482. camLeft.rotation.copyFrom(this.rotation);
  32483. camRight.rotation.copyFrom(this.rotation);
  32484. }
  32485. camLeft.position.copyFrom(this.position);
  32486. camRight.position.copyFrom(this.position);
  32487. break;
  32488. }
  32489. _super.prototype._updateRigCameras.call(this);
  32490. };
  32491. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  32492. if (!this._rigCamTransformMatrix) {
  32493. this._rigCamTransformMatrix = new BABYLON.Matrix();
  32494. }
  32495. var target = this.getTarget();
  32496. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  32497. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  32498. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  32499. };
  32500. TargetCamera.prototype.getClassName = function () {
  32501. return "TargetCamera";
  32502. };
  32503. return TargetCamera;
  32504. }(BABYLON.Camera));
  32505. __decorate([
  32506. BABYLON.serializeAsVector3()
  32507. ], TargetCamera.prototype, "rotation", void 0);
  32508. __decorate([
  32509. BABYLON.serialize()
  32510. ], TargetCamera.prototype, "speed", void 0);
  32511. __decorate([
  32512. BABYLON.serializeAsMeshReference("lockedTargetId")
  32513. ], TargetCamera.prototype, "lockedTarget", void 0);
  32514. BABYLON.TargetCamera = TargetCamera;
  32515. })(BABYLON || (BABYLON = {}));
  32516. //# sourceMappingURL=babylon.targetCamera.js.map
  32517. var BABYLON;
  32518. (function (BABYLON) {
  32519. var FreeCamera = (function (_super) {
  32520. __extends(FreeCamera, _super);
  32521. function FreeCamera(name, position, scene) {
  32522. var _this = _super.call(this, name, position, scene) || this;
  32523. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  32524. _this.checkCollisions = false;
  32525. _this.applyGravity = false;
  32526. _this._needMoveForGravity = false;
  32527. _this._oldPosition = BABYLON.Vector3.Zero();
  32528. _this._diffPosition = BABYLON.Vector3.Zero();
  32529. _this._newPosition = BABYLON.Vector3.Zero();
  32530. // Collisions
  32531. _this._collisionMask = -1;
  32532. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32533. if (collidedMesh === void 0) { collidedMesh = null; }
  32534. //TODO move this to the collision coordinator!
  32535. if (_this.getScene().workerCollisions)
  32536. newPosition.multiplyInPlace(_this._collider.radius);
  32537. var updatePosition = function (newPos) {
  32538. _this._newPosition.copyFrom(newPos);
  32539. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  32540. var oldPosition = _this.position.clone();
  32541. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  32542. _this.position.addInPlace(_this._diffPosition);
  32543. if (_this.onCollide && collidedMesh) {
  32544. _this.onCollide(collidedMesh);
  32545. }
  32546. }
  32547. };
  32548. updatePosition(newPosition);
  32549. };
  32550. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  32551. _this.inputs.addKeyboard().addMouse();
  32552. return _this;
  32553. }
  32554. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  32555. //-- begin properties for backward compatibility for inputs
  32556. get: function () {
  32557. var mouse = this.inputs.attached["mouse"];
  32558. if (mouse)
  32559. return mouse.angularSensibility;
  32560. },
  32561. set: function (value) {
  32562. var mouse = this.inputs.attached["mouse"];
  32563. if (mouse)
  32564. mouse.angularSensibility = value;
  32565. },
  32566. enumerable: true,
  32567. configurable: true
  32568. });
  32569. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  32570. get: function () {
  32571. var keyboard = this.inputs.attached["keyboard"];
  32572. if (keyboard)
  32573. return keyboard.keysUp;
  32574. },
  32575. set: function (value) {
  32576. var keyboard = this.inputs.attached["keyboard"];
  32577. if (keyboard)
  32578. keyboard.keysUp = value;
  32579. },
  32580. enumerable: true,
  32581. configurable: true
  32582. });
  32583. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  32584. get: function () {
  32585. var keyboard = this.inputs.attached["keyboard"];
  32586. if (keyboard)
  32587. return keyboard.keysDown;
  32588. },
  32589. set: function (value) {
  32590. var keyboard = this.inputs.attached["keyboard"];
  32591. if (keyboard)
  32592. keyboard.keysDown = value;
  32593. },
  32594. enumerable: true,
  32595. configurable: true
  32596. });
  32597. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  32598. get: function () {
  32599. var keyboard = this.inputs.attached["keyboard"];
  32600. if (keyboard)
  32601. return keyboard.keysLeft;
  32602. },
  32603. set: function (value) {
  32604. var keyboard = this.inputs.attached["keyboard"];
  32605. if (keyboard)
  32606. keyboard.keysLeft = value;
  32607. },
  32608. enumerable: true,
  32609. configurable: true
  32610. });
  32611. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  32612. get: function () {
  32613. var keyboard = this.inputs.attached["keyboard"];
  32614. if (keyboard)
  32615. return keyboard.keysRight;
  32616. },
  32617. set: function (value) {
  32618. var keyboard = this.inputs.attached["keyboard"];
  32619. if (keyboard)
  32620. keyboard.keysRight = value;
  32621. },
  32622. enumerable: true,
  32623. configurable: true
  32624. });
  32625. // Controls
  32626. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32627. this.inputs.attachElement(element, noPreventDefault);
  32628. };
  32629. FreeCamera.prototype.detachControl = function (element) {
  32630. this.inputs.detachElement(element);
  32631. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  32632. this.cameraRotation = new BABYLON.Vector2(0, 0);
  32633. };
  32634. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  32635. get: function () {
  32636. return this._collisionMask;
  32637. },
  32638. set: function (mask) {
  32639. this._collisionMask = !isNaN(mask) ? mask : -1;
  32640. },
  32641. enumerable: true,
  32642. configurable: true
  32643. });
  32644. FreeCamera.prototype._collideWithWorld = function (velocity) {
  32645. var globalPosition;
  32646. if (this.parent) {
  32647. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  32648. }
  32649. else {
  32650. globalPosition = this.position;
  32651. }
  32652. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  32653. if (!this._collider) {
  32654. this._collider = new BABYLON.Collider();
  32655. }
  32656. this._collider.radius = this.ellipsoid;
  32657. this._collider.collisionMask = this._collisionMask;
  32658. //no need for clone, as long as gravity is not on.
  32659. var actualVelocity = velocity;
  32660. //add gravity to the velocity to prevent the dual-collision checking
  32661. if (this.applyGravity) {
  32662. //this prevents mending with cameraDirection, a global variable of the free camera class.
  32663. actualVelocity = velocity.add(this.getScene().gravity);
  32664. }
  32665. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32666. };
  32667. FreeCamera.prototype._checkInputs = function () {
  32668. if (!this._localDirection) {
  32669. this._localDirection = BABYLON.Vector3.Zero();
  32670. this._transformedDirection = BABYLON.Vector3.Zero();
  32671. }
  32672. this.inputs.checkInputs();
  32673. _super.prototype._checkInputs.call(this);
  32674. };
  32675. FreeCamera.prototype._decideIfNeedsToMove = function () {
  32676. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  32677. };
  32678. FreeCamera.prototype._updatePosition = function () {
  32679. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  32680. this._collideWithWorld(this.cameraDirection);
  32681. }
  32682. else {
  32683. _super.prototype._updatePosition.call(this);
  32684. }
  32685. };
  32686. FreeCamera.prototype.dispose = function () {
  32687. this.inputs.clear();
  32688. _super.prototype.dispose.call(this);
  32689. };
  32690. FreeCamera.prototype.getClassName = function () {
  32691. return "FreeCamera";
  32692. };
  32693. return FreeCamera;
  32694. }(BABYLON.TargetCamera));
  32695. __decorate([
  32696. BABYLON.serializeAsVector3()
  32697. ], FreeCamera.prototype, "ellipsoid", void 0);
  32698. __decorate([
  32699. BABYLON.serialize()
  32700. ], FreeCamera.prototype, "checkCollisions", void 0);
  32701. __decorate([
  32702. BABYLON.serialize()
  32703. ], FreeCamera.prototype, "applyGravity", void 0);
  32704. BABYLON.FreeCamera = FreeCamera;
  32705. })(BABYLON || (BABYLON = {}));
  32706. //# sourceMappingURL=babylon.freeCamera.js.map
  32707. var BABYLON;
  32708. (function (BABYLON) {
  32709. var ArcRotateCameraKeyboardMoveInput = (function () {
  32710. function ArcRotateCameraKeyboardMoveInput() {
  32711. this._keys = [];
  32712. this.keysUp = [38];
  32713. this.keysDown = [40];
  32714. this.keysLeft = [37];
  32715. this.keysRight = [39];
  32716. }
  32717. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32718. var _this = this;
  32719. element.tabIndex = 1;
  32720. this._onKeyDown = function (evt) {
  32721. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32722. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32723. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32724. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32725. var index = _this._keys.indexOf(evt.keyCode);
  32726. if (index === -1) {
  32727. _this._keys.push(evt.keyCode);
  32728. }
  32729. if (evt.preventDefault) {
  32730. if (!noPreventDefault) {
  32731. evt.preventDefault();
  32732. }
  32733. }
  32734. }
  32735. };
  32736. this._onKeyUp = function (evt) {
  32737. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32738. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32739. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32740. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32741. var index = _this._keys.indexOf(evt.keyCode);
  32742. if (index >= 0) {
  32743. _this._keys.splice(index, 1);
  32744. }
  32745. if (evt.preventDefault) {
  32746. if (!noPreventDefault) {
  32747. evt.preventDefault();
  32748. }
  32749. }
  32750. }
  32751. };
  32752. this._onLostFocus = function () {
  32753. _this._keys = [];
  32754. };
  32755. element.addEventListener("keydown", this._onKeyDown, false);
  32756. element.addEventListener("keyup", this._onKeyUp, false);
  32757. BABYLON.Tools.RegisterTopRootEvents([
  32758. { name: "blur", handler: this._onLostFocus }
  32759. ]);
  32760. };
  32761. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32762. if (element) {
  32763. element.removeEventListener("keydown", this._onKeyDown);
  32764. element.removeEventListener("keyup", this._onKeyUp);
  32765. }
  32766. BABYLON.Tools.UnregisterTopRootEvents([
  32767. { name: "blur", handler: this._onLostFocus }
  32768. ]);
  32769. this._keys = [];
  32770. this._onKeyDown = null;
  32771. this._onKeyUp = null;
  32772. this._onLostFocus = null;
  32773. };
  32774. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32775. if (this._onKeyDown) {
  32776. var camera = this.camera;
  32777. for (var index = 0; index < this._keys.length; index++) {
  32778. var keyCode = this._keys[index];
  32779. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32780. camera.inertialAlphaOffset -= 0.01;
  32781. }
  32782. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32783. camera.inertialBetaOffset -= 0.01;
  32784. }
  32785. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32786. camera.inertialAlphaOffset += 0.01;
  32787. }
  32788. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32789. camera.inertialBetaOffset += 0.01;
  32790. }
  32791. }
  32792. }
  32793. };
  32794. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32795. return "ArcRotateCameraKeyboardMoveInput";
  32796. };
  32797. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32798. return "keyboard";
  32799. };
  32800. return ArcRotateCameraKeyboardMoveInput;
  32801. }());
  32802. __decorate([
  32803. BABYLON.serialize()
  32804. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32805. __decorate([
  32806. BABYLON.serialize()
  32807. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32808. __decorate([
  32809. BABYLON.serialize()
  32810. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32811. __decorate([
  32812. BABYLON.serialize()
  32813. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32814. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  32815. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  32816. })(BABYLON || (BABYLON = {}));
  32817. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  32818. var BABYLON;
  32819. (function (BABYLON) {
  32820. var ArcRotateCameraMouseWheelInput = (function () {
  32821. function ArcRotateCameraMouseWheelInput() {
  32822. this.wheelPrecision = 3.0;
  32823. }
  32824. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  32825. var _this = this;
  32826. this._wheel = function (p, s) {
  32827. //sanity check - this should be a PointerWheel event.
  32828. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  32829. return;
  32830. var event = p.event;
  32831. var delta = 0;
  32832. if (event.wheelDelta) {
  32833. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  32834. }
  32835. else if (event.detail) {
  32836. delta = -event.detail / _this.wheelPrecision;
  32837. }
  32838. if (delta)
  32839. _this.camera.inertialRadiusOffset += delta;
  32840. if (event.preventDefault) {
  32841. if (!noPreventDefault) {
  32842. event.preventDefault();
  32843. }
  32844. }
  32845. };
  32846. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  32847. };
  32848. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  32849. if (this._observer && element) {
  32850. this.camera.getScene().onPointerObservable.remove(this._observer);
  32851. this._observer = null;
  32852. this._wheel = null;
  32853. }
  32854. };
  32855. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  32856. return "ArcRotateCameraMouseWheelInput";
  32857. };
  32858. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  32859. return "mousewheel";
  32860. };
  32861. return ArcRotateCameraMouseWheelInput;
  32862. }());
  32863. __decorate([
  32864. BABYLON.serialize()
  32865. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  32866. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  32867. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  32868. })(BABYLON || (BABYLON = {}));
  32869. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  32870. var BABYLON;
  32871. (function (BABYLON) {
  32872. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  32873. var ArcRotateCameraPointersInput = (function () {
  32874. function ArcRotateCameraPointersInput() {
  32875. this.buttons = [0, 1, 2];
  32876. this.angularSensibilityX = 1000.0;
  32877. this.angularSensibilityY = 1000.0;
  32878. this.pinchPrecision = 6.0;
  32879. this.panningSensibility = 50.0;
  32880. this._isPanClick = false;
  32881. this.pinchInwards = true;
  32882. }
  32883. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  32884. var _this = this;
  32885. var engine = this.camera.getEngine();
  32886. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  32887. var pointA, pointB;
  32888. var previousPinchDistance = 0;
  32889. this._pointerInput = function (p, s) {
  32890. var evt = p.event;
  32891. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32892. return;
  32893. }
  32894. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32895. try {
  32896. evt.srcElement.setPointerCapture(evt.pointerId);
  32897. }
  32898. catch (e) {
  32899. //Nothing to do with the error. Execution will continue.
  32900. }
  32901. // Manage panning with pan button click
  32902. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  32903. // manage pointers
  32904. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  32905. if (pointA === undefined) {
  32906. pointA = cacheSoloPointer;
  32907. }
  32908. else if (pointB === undefined) {
  32909. pointB = cacheSoloPointer;
  32910. }
  32911. if (!noPreventDefault) {
  32912. evt.preventDefault();
  32913. element.focus();
  32914. }
  32915. }
  32916. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32917. try {
  32918. evt.srcElement.releasePointerCapture(evt.pointerId);
  32919. }
  32920. catch (e) {
  32921. //Nothing to do with the error.
  32922. }
  32923. cacheSoloPointer = null;
  32924. previousPinchDistance = 0;
  32925. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32926. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32927. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32928. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32929. pointA = pointB = undefined;
  32930. if (!noPreventDefault) {
  32931. evt.preventDefault();
  32932. }
  32933. }
  32934. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32935. if (!noPreventDefault) {
  32936. evt.preventDefault();
  32937. }
  32938. // One button down
  32939. if (pointA && pointB === undefined) {
  32940. if (_this.panningSensibility !== 0 &&
  32941. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32942. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32943. _this.camera
  32944. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32945. _this.camera
  32946. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32947. }
  32948. else {
  32949. var offsetX = evt.clientX - cacheSoloPointer.x;
  32950. var offsetY = evt.clientY - cacheSoloPointer.y;
  32951. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32952. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32953. }
  32954. cacheSoloPointer.x = evt.clientX;
  32955. cacheSoloPointer.y = evt.clientY;
  32956. }
  32957. else if (pointA && pointB) {
  32958. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32959. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32960. ed.x = evt.clientX;
  32961. ed.y = evt.clientY;
  32962. var direction = _this.pinchInwards ? 1 : -1;
  32963. var distX = pointA.x - pointB.x;
  32964. var distY = pointA.y - pointB.y;
  32965. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32966. if (previousPinchDistance === 0) {
  32967. previousPinchDistance = pinchSquaredDistance;
  32968. return;
  32969. }
  32970. if (pinchSquaredDistance !== previousPinchDistance) {
  32971. _this.camera
  32972. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32973. (_this.pinchPrecision *
  32974. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32975. direction);
  32976. previousPinchDistance = pinchSquaredDistance;
  32977. }
  32978. }
  32979. }
  32980. };
  32981. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  32982. this._onContextMenu = function (evt) {
  32983. evt.preventDefault();
  32984. };
  32985. if (!this.camera._useCtrlForPanning) {
  32986. element.addEventListener("contextmenu", this._onContextMenu, false);
  32987. }
  32988. this._onLostFocus = function () {
  32989. //this._keys = [];
  32990. pointA = pointB = undefined;
  32991. previousPinchDistance = 0;
  32992. cacheSoloPointer = null;
  32993. };
  32994. this._onMouseMove = function (evt) {
  32995. if (!engine.isPointerLock) {
  32996. return;
  32997. }
  32998. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32999. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  33000. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  33001. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  33002. if (!noPreventDefault) {
  33003. evt.preventDefault();
  33004. }
  33005. };
  33006. this._onGestureStart = function (e) {
  33007. if (window.MSGesture === undefined) {
  33008. return;
  33009. }
  33010. if (!_this._MSGestureHandler) {
  33011. _this._MSGestureHandler = new MSGesture();
  33012. _this._MSGestureHandler.target = element;
  33013. }
  33014. _this._MSGestureHandler.addPointer(e.pointerId);
  33015. };
  33016. this._onGesture = function (e) {
  33017. _this.camera.radius *= e.scale;
  33018. if (e.preventDefault) {
  33019. if (!noPreventDefault) {
  33020. e.stopPropagation();
  33021. e.preventDefault();
  33022. }
  33023. }
  33024. };
  33025. element.addEventListener("mousemove", this._onMouseMove, false);
  33026. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  33027. element.addEventListener("MSGestureChange", this._onGesture, false);
  33028. BABYLON.Tools.RegisterTopRootEvents([
  33029. { name: "blur", handler: this._onLostFocus }
  33030. ]);
  33031. };
  33032. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  33033. if (element && this._observer) {
  33034. this.camera.getScene().onPointerObservable.remove(this._observer);
  33035. this._observer = null;
  33036. element.removeEventListener("contextmenu", this._onContextMenu);
  33037. element.removeEventListener("mousemove", this._onMouseMove);
  33038. element.removeEventListener("MSPointerDown", this._onGestureStart);
  33039. element.removeEventListener("MSGestureChange", this._onGesture);
  33040. this._isPanClick = false;
  33041. this.pinchInwards = true;
  33042. this._onMouseMove = null;
  33043. this._onGestureStart = null;
  33044. this._onGesture = null;
  33045. this._MSGestureHandler = null;
  33046. this._onLostFocus = null;
  33047. this._onContextMenu = null;
  33048. }
  33049. BABYLON.Tools.UnregisterTopRootEvents([
  33050. { name: "blur", handler: this._onLostFocus }
  33051. ]);
  33052. };
  33053. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  33054. return "ArcRotateCameraPointersInput";
  33055. };
  33056. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  33057. return "pointers";
  33058. };
  33059. return ArcRotateCameraPointersInput;
  33060. }());
  33061. __decorate([
  33062. BABYLON.serialize()
  33063. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  33064. __decorate([
  33065. BABYLON.serialize()
  33066. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  33067. __decorate([
  33068. BABYLON.serialize()
  33069. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  33070. __decorate([
  33071. BABYLON.serialize()
  33072. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  33073. __decorate([
  33074. BABYLON.serialize()
  33075. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  33076. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  33077. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  33078. })(BABYLON || (BABYLON = {}));
  33079. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  33080. /// <reference path="babylon.targetCamera.ts" />
  33081. /// <reference path="..\Tools\babylon.tools.ts" />
  33082. var BABYLON;
  33083. (function (BABYLON) {
  33084. var ArcRotateCamera = (function (_super) {
  33085. __extends(ArcRotateCamera, _super);
  33086. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  33087. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  33088. _this.inertialAlphaOffset = 0;
  33089. _this.inertialBetaOffset = 0;
  33090. _this.inertialRadiusOffset = 0;
  33091. _this.lowerAlphaLimit = null;
  33092. _this.upperAlphaLimit = null;
  33093. _this.lowerBetaLimit = 0.01;
  33094. _this.upperBetaLimit = Math.PI;
  33095. _this.lowerRadiusLimit = null;
  33096. _this.upperRadiusLimit = null;
  33097. _this.inertialPanningX = 0;
  33098. _this.inertialPanningY = 0;
  33099. _this.panningInertia = 0.9;
  33100. //-- end properties for backward compatibility for inputs
  33101. _this.zoomOnFactor = 1;
  33102. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  33103. _this.allowUpsideDown = true;
  33104. _this._viewMatrix = new BABYLON.Matrix();
  33105. // Panning
  33106. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  33107. _this.checkCollisions = false;
  33108. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  33109. _this._previousPosition = BABYLON.Vector3.Zero();
  33110. _this._collisionVelocity = BABYLON.Vector3.Zero();
  33111. _this._newPosition = BABYLON.Vector3.Zero();
  33112. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  33113. if (collidedMesh === void 0) { collidedMesh = null; }
  33114. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  33115. newPosition.multiplyInPlace(_this._collider.radius);
  33116. }
  33117. if (!collidedMesh) {
  33118. _this._previousPosition.copyFrom(_this.position);
  33119. }
  33120. else {
  33121. _this.setPosition(newPosition);
  33122. if (_this.onCollide) {
  33123. _this.onCollide(collidedMesh);
  33124. }
  33125. }
  33126. // Recompute because of constraints
  33127. var cosa = Math.cos(_this.alpha);
  33128. var sina = Math.sin(_this.alpha);
  33129. var cosb = Math.cos(_this.beta);
  33130. var sinb = Math.sin(_this.beta);
  33131. if (sinb === 0) {
  33132. sinb = 0.0001;
  33133. }
  33134. var target = _this._getTargetPosition();
  33135. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  33136. _this.position.copyFrom(_this._newPosition);
  33137. var up = _this.upVector;
  33138. if (_this.allowUpsideDown && _this.beta < 0) {
  33139. up = up.clone();
  33140. up = up.negate();
  33141. }
  33142. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  33143. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  33144. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  33145. _this._collisionTriggered = false;
  33146. };
  33147. _this._target = BABYLON.Vector3.Zero();
  33148. if (target) {
  33149. _this.setTarget(target);
  33150. }
  33151. _this.alpha = alpha;
  33152. _this.beta = beta;
  33153. _this.radius = radius;
  33154. _this.getViewMatrix();
  33155. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  33156. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  33157. return _this;
  33158. }
  33159. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  33160. get: function () {
  33161. return this._target;
  33162. },
  33163. set: function (value) {
  33164. this.setTarget(value);
  33165. },
  33166. enumerable: true,
  33167. configurable: true
  33168. });
  33169. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  33170. //-- begin properties for backward compatibility for inputs
  33171. get: function () {
  33172. var pointers = this.inputs.attached["pointers"];
  33173. if (pointers)
  33174. return pointers.angularSensibilityX;
  33175. },
  33176. set: function (value) {
  33177. var pointers = this.inputs.attached["pointers"];
  33178. if (pointers) {
  33179. pointers.angularSensibilityX = value;
  33180. }
  33181. },
  33182. enumerable: true,
  33183. configurable: true
  33184. });
  33185. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  33186. get: function () {
  33187. var pointers = this.inputs.attached["pointers"];
  33188. if (pointers)
  33189. return pointers.angularSensibilityY;
  33190. },
  33191. set: function (value) {
  33192. var pointers = this.inputs.attached["pointers"];
  33193. if (pointers) {
  33194. pointers.angularSensibilityY = value;
  33195. }
  33196. },
  33197. enumerable: true,
  33198. configurable: true
  33199. });
  33200. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  33201. get: function () {
  33202. var pointers = this.inputs.attached["pointers"];
  33203. if (pointers)
  33204. return pointers.pinchPrecision;
  33205. },
  33206. set: function (value) {
  33207. var pointers = this.inputs.attached["pointers"];
  33208. if (pointers) {
  33209. pointers.pinchPrecision = value;
  33210. }
  33211. },
  33212. enumerable: true,
  33213. configurable: true
  33214. });
  33215. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  33216. get: function () {
  33217. var pointers = this.inputs.attached["pointers"];
  33218. if (pointers)
  33219. return pointers.panningSensibility;
  33220. },
  33221. set: function (value) {
  33222. var pointers = this.inputs.attached["pointers"];
  33223. if (pointers) {
  33224. pointers.panningSensibility = value;
  33225. }
  33226. },
  33227. enumerable: true,
  33228. configurable: true
  33229. });
  33230. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  33231. get: function () {
  33232. var keyboard = this.inputs.attached["keyboard"];
  33233. if (keyboard)
  33234. return keyboard.keysUp;
  33235. },
  33236. set: function (value) {
  33237. var keyboard = this.inputs.attached["keyboard"];
  33238. if (keyboard)
  33239. keyboard.keysUp = value;
  33240. },
  33241. enumerable: true,
  33242. configurable: true
  33243. });
  33244. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  33245. get: function () {
  33246. var keyboard = this.inputs.attached["keyboard"];
  33247. if (keyboard)
  33248. return keyboard.keysDown;
  33249. },
  33250. set: function (value) {
  33251. var keyboard = this.inputs.attached["keyboard"];
  33252. if (keyboard)
  33253. keyboard.keysDown = value;
  33254. },
  33255. enumerable: true,
  33256. configurable: true
  33257. });
  33258. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  33259. get: function () {
  33260. var keyboard = this.inputs.attached["keyboard"];
  33261. if (keyboard)
  33262. return keyboard.keysLeft;
  33263. },
  33264. set: function (value) {
  33265. var keyboard = this.inputs.attached["keyboard"];
  33266. if (keyboard)
  33267. keyboard.keysLeft = value;
  33268. },
  33269. enumerable: true,
  33270. configurable: true
  33271. });
  33272. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  33273. get: function () {
  33274. var keyboard = this.inputs.attached["keyboard"];
  33275. if (keyboard)
  33276. return keyboard.keysRight;
  33277. },
  33278. set: function (value) {
  33279. var keyboard = this.inputs.attached["keyboard"];
  33280. if (keyboard)
  33281. keyboard.keysRight = value;
  33282. },
  33283. enumerable: true,
  33284. configurable: true
  33285. });
  33286. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  33287. get: function () {
  33288. var mousewheel = this.inputs.attached["mousewheel"];
  33289. if (mousewheel)
  33290. return mousewheel.wheelPrecision;
  33291. },
  33292. set: function (value) {
  33293. var mousewheel = this.inputs.attached["mousewheel"];
  33294. if (mousewheel)
  33295. mousewheel.wheelPrecision = value;
  33296. },
  33297. enumerable: true,
  33298. configurable: true
  33299. });
  33300. // Cache
  33301. ArcRotateCamera.prototype._initCache = function () {
  33302. _super.prototype._initCache.call(this);
  33303. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33304. this._cache.alpha = undefined;
  33305. this._cache.beta = undefined;
  33306. this._cache.radius = undefined;
  33307. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  33308. };
  33309. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  33310. if (!ignoreParentClass) {
  33311. _super.prototype._updateCache.call(this);
  33312. }
  33313. this._cache._target.copyFrom(this._getTargetPosition());
  33314. this._cache.alpha = this.alpha;
  33315. this._cache.beta = this.beta;
  33316. this._cache.radius = this.radius;
  33317. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  33318. };
  33319. ArcRotateCamera.prototype._getTargetPosition = function () {
  33320. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  33321. var pos = this._targetHost.getAbsolutePosition();
  33322. if (this._targetBoundingCenter) {
  33323. pos.addToRef(this._targetBoundingCenter, this._target);
  33324. }
  33325. else {
  33326. this._target.copyFrom(pos);
  33327. }
  33328. }
  33329. var lockedTargetPosition = this._getLockedTargetPosition();
  33330. if (lockedTargetPosition) {
  33331. return lockedTargetPosition;
  33332. }
  33333. return this._target;
  33334. };
  33335. // Synchronized
  33336. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  33337. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  33338. return false;
  33339. return this._cache._target.equals(this._getTargetPosition())
  33340. && this._cache.alpha === this.alpha
  33341. && this._cache.beta === this.beta
  33342. && this._cache.radius === this.radius
  33343. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  33344. };
  33345. // Methods
  33346. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  33347. var _this = this;
  33348. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  33349. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  33350. this._useCtrlForPanning = useCtrlForPanning;
  33351. this._panningMouseButton = panningMouseButton;
  33352. this.inputs.attachElement(element, noPreventDefault);
  33353. this._reset = function () {
  33354. _this.inertialAlphaOffset = 0;
  33355. _this.inertialBetaOffset = 0;
  33356. _this.inertialRadiusOffset = 0;
  33357. };
  33358. };
  33359. ArcRotateCamera.prototype.detachControl = function (element) {
  33360. this.inputs.detachElement(element);
  33361. if (this._reset) {
  33362. this._reset();
  33363. }
  33364. };
  33365. ArcRotateCamera.prototype._checkInputs = function () {
  33366. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  33367. if (this._collisionTriggered) {
  33368. return;
  33369. }
  33370. this.inputs.checkInputs();
  33371. // Inertia
  33372. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  33373. if (this.getScene().useRightHandedSystem) {
  33374. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  33375. }
  33376. else {
  33377. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  33378. }
  33379. this.beta += this.inertialBetaOffset;
  33380. this.radius -= this.inertialRadiusOffset;
  33381. this.inertialAlphaOffset *= this.inertia;
  33382. this.inertialBetaOffset *= this.inertia;
  33383. this.inertialRadiusOffset *= this.inertia;
  33384. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  33385. this.inertialAlphaOffset = 0;
  33386. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  33387. this.inertialBetaOffset = 0;
  33388. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  33389. this.inertialRadiusOffset = 0;
  33390. }
  33391. // Panning inertia
  33392. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  33393. if (!this._localDirection) {
  33394. this._localDirection = BABYLON.Vector3.Zero();
  33395. this._transformedDirection = BABYLON.Vector3.Zero();
  33396. }
  33397. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  33398. this._localDirection.multiplyInPlace(this.panningAxis);
  33399. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  33400. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  33401. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  33402. if (!this.panningAxis.y) {
  33403. this._transformedDirection.y = 0;
  33404. }
  33405. if (!this._targetHost) {
  33406. this._target.addInPlace(this._transformedDirection);
  33407. }
  33408. this.inertialPanningX *= this.panningInertia;
  33409. this.inertialPanningY *= this.panningInertia;
  33410. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  33411. this.inertialPanningX = 0;
  33412. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  33413. this.inertialPanningY = 0;
  33414. }
  33415. // Limits
  33416. this._checkLimits();
  33417. _super.prototype._checkInputs.call(this);
  33418. };
  33419. ArcRotateCamera.prototype._checkLimits = function () {
  33420. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  33421. if (this.allowUpsideDown && this.beta > Math.PI) {
  33422. this.beta = this.beta - (2 * Math.PI);
  33423. }
  33424. }
  33425. else {
  33426. if (this.beta < this.lowerBetaLimit) {
  33427. this.beta = this.lowerBetaLimit;
  33428. }
  33429. }
  33430. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  33431. if (this.allowUpsideDown && this.beta < -Math.PI) {
  33432. this.beta = this.beta + (2 * Math.PI);
  33433. }
  33434. }
  33435. else {
  33436. if (this.beta > this.upperBetaLimit) {
  33437. this.beta = this.upperBetaLimit;
  33438. }
  33439. }
  33440. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  33441. this.alpha = this.lowerAlphaLimit;
  33442. }
  33443. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  33444. this.alpha = this.upperAlphaLimit;
  33445. }
  33446. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  33447. this.radius = this.lowerRadiusLimit;
  33448. }
  33449. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  33450. this.radius = this.upperRadiusLimit;
  33451. }
  33452. };
  33453. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  33454. var radiusv3 = this.position.subtract(this._getTargetPosition());
  33455. this.radius = radiusv3.length();
  33456. // Alpha
  33457. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  33458. if (radiusv3.z < 0) {
  33459. this.alpha = 2 * Math.PI - this.alpha;
  33460. }
  33461. // Beta
  33462. this.beta = Math.acos(radiusv3.y / this.radius);
  33463. this._checkLimits();
  33464. };
  33465. ArcRotateCamera.prototype.setPosition = function (position) {
  33466. if (this.position.equals(position)) {
  33467. return;
  33468. }
  33469. this.position.copyFrom(position);
  33470. this.rebuildAnglesAndRadius();
  33471. };
  33472. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  33473. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  33474. if (allowSamePosition === void 0) { allowSamePosition = false; }
  33475. if (target.getBoundingInfo) {
  33476. if (toBoundingCenter) {
  33477. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  33478. }
  33479. else {
  33480. this._targetBoundingCenter = null;
  33481. }
  33482. this._targetHost = target;
  33483. this._target = this._getTargetPosition();
  33484. }
  33485. else {
  33486. var newTarget = target;
  33487. var currentTarget = this._getTargetPosition();
  33488. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  33489. return;
  33490. }
  33491. this._target = newTarget;
  33492. this._targetBoundingCenter = null;
  33493. }
  33494. this.rebuildAnglesAndRadius();
  33495. };
  33496. ArcRotateCamera.prototype._getViewMatrix = function () {
  33497. // Compute
  33498. var cosa = Math.cos(this.alpha);
  33499. var sina = Math.sin(this.alpha);
  33500. var cosb = Math.cos(this.beta);
  33501. var sinb = Math.sin(this.beta);
  33502. if (sinb === 0) {
  33503. sinb = 0.0001;
  33504. }
  33505. var target = this._getTargetPosition();
  33506. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  33507. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  33508. if (!this._collider) {
  33509. this._collider = new BABYLON.Collider();
  33510. }
  33511. this._collider.radius = this.collisionRadius;
  33512. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  33513. this._collisionTriggered = true;
  33514. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  33515. }
  33516. else {
  33517. this.position.copyFrom(this._newPosition);
  33518. var up = this.upVector;
  33519. if (this.allowUpsideDown && sinb < 0) {
  33520. up = up.clone();
  33521. up = up.negate();
  33522. }
  33523. if (this.getScene().useRightHandedSystem) {
  33524. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  33525. }
  33526. else {
  33527. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  33528. }
  33529. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  33530. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  33531. }
  33532. this._currentTarget = target;
  33533. return this._viewMatrix;
  33534. };
  33535. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  33536. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33537. meshes = meshes || this.getScene().meshes;
  33538. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  33539. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  33540. this.radius = distance * this.zoomOnFactor;
  33541. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  33542. };
  33543. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  33544. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33545. var meshesOrMinMaxVector;
  33546. var distance;
  33547. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  33548. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  33549. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  33550. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  33551. }
  33552. else {
  33553. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  33554. distance = meshesOrMinMaxVectorAndDistance.distance;
  33555. }
  33556. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  33557. if (!doNotUpdateMaxZ) {
  33558. this.maxZ = distance * 2;
  33559. }
  33560. };
  33561. /**
  33562. * @override
  33563. * Override Camera.createRigCamera
  33564. */
  33565. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  33566. var alphaShift;
  33567. switch (this.cameraRigMode) {
  33568. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33569. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33570. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33571. case BABYLON.Camera.RIG_MODE_VR:
  33572. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  33573. break;
  33574. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33575. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  33576. break;
  33577. }
  33578. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  33579. rigCam._cameraRigParams = {};
  33580. return rigCam;
  33581. };
  33582. /**
  33583. * @override
  33584. * Override Camera._updateRigCameras
  33585. */
  33586. ArcRotateCamera.prototype._updateRigCameras = function () {
  33587. var camLeft = this._rigCameras[0];
  33588. var camRight = this._rigCameras[1];
  33589. camLeft.beta = camRight.beta = this.beta;
  33590. camLeft.radius = camRight.radius = this.radius;
  33591. switch (this.cameraRigMode) {
  33592. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33593. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33594. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33595. case BABYLON.Camera.RIG_MODE_VR:
  33596. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33597. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33598. break;
  33599. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33600. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33601. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33602. break;
  33603. }
  33604. _super.prototype._updateRigCameras.call(this);
  33605. };
  33606. ArcRotateCamera.prototype.dispose = function () {
  33607. this.inputs.clear();
  33608. _super.prototype.dispose.call(this);
  33609. };
  33610. ArcRotateCamera.prototype.getClassName = function () {
  33611. return "ArcRotateCamera";
  33612. };
  33613. return ArcRotateCamera;
  33614. }(BABYLON.TargetCamera));
  33615. __decorate([
  33616. BABYLON.serialize()
  33617. ], ArcRotateCamera.prototype, "alpha", void 0);
  33618. __decorate([
  33619. BABYLON.serialize()
  33620. ], ArcRotateCamera.prototype, "beta", void 0);
  33621. __decorate([
  33622. BABYLON.serialize()
  33623. ], ArcRotateCamera.prototype, "radius", void 0);
  33624. __decorate([
  33625. BABYLON.serializeAsVector3("target")
  33626. ], ArcRotateCamera.prototype, "_target", void 0);
  33627. __decorate([
  33628. BABYLON.serialize()
  33629. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  33630. __decorate([
  33631. BABYLON.serialize()
  33632. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  33633. __decorate([
  33634. BABYLON.serialize()
  33635. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  33636. __decorate([
  33637. BABYLON.serialize()
  33638. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  33639. __decorate([
  33640. BABYLON.serialize()
  33641. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  33642. __decorate([
  33643. BABYLON.serialize()
  33644. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  33645. __decorate([
  33646. BABYLON.serialize()
  33647. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  33648. __decorate([
  33649. BABYLON.serialize()
  33650. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  33651. __decorate([
  33652. BABYLON.serialize()
  33653. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  33654. __decorate([
  33655. BABYLON.serialize()
  33656. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  33657. __decorate([
  33658. BABYLON.serialize()
  33659. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  33660. __decorate([
  33661. BABYLON.serialize()
  33662. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  33663. __decorate([
  33664. BABYLON.serialize()
  33665. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  33666. __decorate([
  33667. BABYLON.serialize()
  33668. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  33669. BABYLON.ArcRotateCamera = ArcRotateCamera;
  33670. })(BABYLON || (BABYLON = {}));
  33671. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  33672. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  33673. var BABYLON;
  33674. (function (BABYLON) {
  33675. var ArcRotateCameraInputsManager = (function (_super) {
  33676. __extends(ArcRotateCameraInputsManager, _super);
  33677. function ArcRotateCameraInputsManager(camera) {
  33678. return _super.call(this, camera) || this;
  33679. }
  33680. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  33681. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  33682. return this;
  33683. };
  33684. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  33685. this.add(new BABYLON.ArcRotateCameraPointersInput());
  33686. return this;
  33687. };
  33688. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  33689. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  33690. return this;
  33691. };
  33692. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  33693. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  33694. return this;
  33695. };
  33696. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  33697. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  33698. return this;
  33699. };
  33700. return ArcRotateCameraInputsManager;
  33701. }(BABYLON.CameraInputsManager));
  33702. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  33703. })(BABYLON || (BABYLON = {}));
  33704. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  33705. var BABYLON;
  33706. (function (BABYLON) {
  33707. var HemisphericLight = (function (_super) {
  33708. __extends(HemisphericLight, _super);
  33709. /**
  33710. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  33711. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  33712. * The HemisphericLight can't cast shadows.
  33713. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33714. */
  33715. function HemisphericLight(name, direction, scene) {
  33716. var _this = _super.call(this, name, scene) || this;
  33717. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  33718. _this.direction = direction || BABYLON.Vector3.Up();
  33719. return _this;
  33720. }
  33721. HemisphericLight.prototype._buildUniformLayout = function () {
  33722. this._uniformBuffer.addUniform("vLightData", 4);
  33723. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33724. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33725. this._uniformBuffer.addUniform("vLightGround", 3);
  33726. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33727. this._uniformBuffer.addUniform("depthValues", 2);
  33728. this._uniformBuffer.create();
  33729. };
  33730. /**
  33731. * Returns the string "HemisphericLight".
  33732. */
  33733. HemisphericLight.prototype.getClassName = function () {
  33734. return "HemisphericLight";
  33735. };
  33736. /**
  33737. * Sets the HemisphericLight direction towards the passed target (Vector3).
  33738. * Returns the updated direction.
  33739. */
  33740. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  33741. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  33742. return this.direction;
  33743. };
  33744. HemisphericLight.prototype.getShadowGenerator = function () {
  33745. return null;
  33746. };
  33747. /**
  33748. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  33749. * Returns the HemisphericLight.
  33750. */
  33751. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  33752. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33753. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  33754. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  33755. return this;
  33756. };
  33757. HemisphericLight.prototype._getWorldMatrix = function () {
  33758. if (!this._worldMatrix) {
  33759. this._worldMatrix = BABYLON.Matrix.Identity();
  33760. }
  33761. return this._worldMatrix;
  33762. };
  33763. /**
  33764. * Returns the integer 3.
  33765. */
  33766. HemisphericLight.prototype.getTypeID = function () {
  33767. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  33768. };
  33769. return HemisphericLight;
  33770. }(BABYLON.Light));
  33771. __decorate([
  33772. BABYLON.serializeAsColor3()
  33773. ], HemisphericLight.prototype, "groundColor", void 0);
  33774. __decorate([
  33775. BABYLON.serializeAsVector3()
  33776. ], HemisphericLight.prototype, "direction", void 0);
  33777. BABYLON.HemisphericLight = HemisphericLight;
  33778. })(BABYLON || (BABYLON = {}));
  33779. //# sourceMappingURL=babylon.hemisphericLight.js.map
  33780. var BABYLON;
  33781. (function (BABYLON) {
  33782. var ShadowLight = (function (_super) {
  33783. __extends(ShadowLight, _super);
  33784. function ShadowLight() {
  33785. var _this = _super !== null && _super.apply(this, arguments) || this;
  33786. _this._needProjectionMatrixCompute = true;
  33787. return _this;
  33788. }
  33789. Object.defineProperty(ShadowLight.prototype, "direction", {
  33790. get: function () {
  33791. return this._direction;
  33792. },
  33793. set: function (value) {
  33794. this._direction = value;
  33795. },
  33796. enumerable: true,
  33797. configurable: true
  33798. });
  33799. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33800. get: function () {
  33801. return this._shadowMinZ;
  33802. },
  33803. set: function (value) {
  33804. this._shadowMinZ = value;
  33805. this.forceProjectionMatrixCompute();
  33806. },
  33807. enumerable: true,
  33808. configurable: true
  33809. });
  33810. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33811. get: function () {
  33812. return this._shadowMaxZ;
  33813. },
  33814. set: function (value) {
  33815. this._shadowMaxZ = value;
  33816. this.forceProjectionMatrixCompute();
  33817. },
  33818. enumerable: true,
  33819. configurable: true
  33820. });
  33821. /**
  33822. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33823. */
  33824. ShadowLight.prototype.computeTransformedInformation = function () {
  33825. if (this.parent && this.parent.getWorldMatrix) {
  33826. if (!this.transformedPosition) {
  33827. this.transformedPosition = BABYLON.Vector3.Zero();
  33828. }
  33829. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33830. // In case the direction is present.
  33831. if (this.direction) {
  33832. if (!this.transformedDirection) {
  33833. this.transformedDirection = BABYLON.Vector3.Zero();
  33834. }
  33835. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33836. }
  33837. return true;
  33838. }
  33839. return false;
  33840. };
  33841. /**
  33842. * Return the depth scale used for the shadow map.
  33843. */
  33844. ShadowLight.prototype.getDepthScale = function () {
  33845. return 50.0;
  33846. };
  33847. /**
  33848. * Returns the light direction (Vector3) for any passed face index.
  33849. */
  33850. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33851. return this.transformedDirection ? this.transformedDirection : this.direction;
  33852. };
  33853. /**
  33854. * Returns the DirectionalLight absolute position in the World.
  33855. */
  33856. ShadowLight.prototype.getAbsolutePosition = function () {
  33857. return this.transformedPosition ? this.transformedPosition : this.position;
  33858. };
  33859. /**
  33860. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33861. * Returns the updated DirectionalLight direction (Vector3).
  33862. */
  33863. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33864. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33865. return this.direction;
  33866. };
  33867. /**
  33868. * Returns the light rotation (Vector3).
  33869. */
  33870. ShadowLight.prototype.getRotation = function () {
  33871. this.direction.normalize();
  33872. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33873. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33874. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33875. };
  33876. /**
  33877. * Boolean : false by default.
  33878. */
  33879. ShadowLight.prototype.needCube = function () {
  33880. return false;
  33881. };
  33882. /**
  33883. * Specifies wether or not the projection matrix should be recomputed this frame.
  33884. */
  33885. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33886. return this._needProjectionMatrixCompute;
  33887. };
  33888. /**
  33889. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33890. */
  33891. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33892. this._needProjectionMatrixCompute = true;
  33893. };
  33894. /**
  33895. * Get the world matrix of the sahdow lights.
  33896. */
  33897. ShadowLight.prototype._getWorldMatrix = function () {
  33898. if (!this._worldMatrix) {
  33899. this._worldMatrix = BABYLON.Matrix.Identity();
  33900. }
  33901. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33902. return this._worldMatrix;
  33903. };
  33904. /**
  33905. * Gets the minZ used for shadow according to both the scene and the light.
  33906. * @param activeCamera
  33907. */
  33908. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  33909. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  33910. };
  33911. /**
  33912. * Gets the maxZ used for shadow according to both the scene and the light.
  33913. * @param activeCamera
  33914. */
  33915. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  33916. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  33917. };
  33918. /**
  33919. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  33920. * Returns the light.
  33921. */
  33922. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33923. if (this.customProjectionMatrixBuilder) {
  33924. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  33925. }
  33926. else {
  33927. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33928. }
  33929. return this;
  33930. };
  33931. return ShadowLight;
  33932. }(BABYLON.Light));
  33933. __decorate([
  33934. BABYLON.serializeAsVector3()
  33935. ], ShadowLight.prototype, "position", void 0);
  33936. __decorate([
  33937. BABYLON.serializeAsVector3()
  33938. ], ShadowLight.prototype, "direction", null);
  33939. __decorate([
  33940. BABYLON.serialize()
  33941. ], ShadowLight.prototype, "shadowMinZ", null);
  33942. __decorate([
  33943. BABYLON.serialize()
  33944. ], ShadowLight.prototype, "shadowMaxZ", null);
  33945. BABYLON.ShadowLight = ShadowLight;
  33946. })(BABYLON || (BABYLON = {}));
  33947. //# sourceMappingURL=babylon.shadowLight.js.map
  33948. var BABYLON;
  33949. (function (BABYLON) {
  33950. var PointLight = (function (_super) {
  33951. __extends(PointLight, _super);
  33952. /**
  33953. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  33954. * A PointLight emits the light in every direction.
  33955. * It can cast shadows.
  33956. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  33957. * ```javascript
  33958. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  33959. * ```
  33960. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33961. */
  33962. function PointLight(name, position, scene) {
  33963. var _this = _super.call(this, name, scene) || this;
  33964. _this._shadowAngle = Math.PI / 2;
  33965. _this.position = position;
  33966. return _this;
  33967. }
  33968. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  33969. /**
  33970. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33971. * This specifies what angle the shadow will use to be created.
  33972. *
  33973. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33974. */
  33975. get: function () {
  33976. return this._shadowAngle;
  33977. },
  33978. /**
  33979. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33980. * This specifies what angle the shadow will use to be created.
  33981. *
  33982. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33983. */
  33984. set: function (value) {
  33985. this._shadowAngle = value;
  33986. this.forceProjectionMatrixCompute();
  33987. },
  33988. enumerable: true,
  33989. configurable: true
  33990. });
  33991. Object.defineProperty(PointLight.prototype, "direction", {
  33992. get: function () {
  33993. return this._direction;
  33994. },
  33995. /**
  33996. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33997. */
  33998. set: function (value) {
  33999. var previousNeedCube = this.needCube();
  34000. this._direction = value;
  34001. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  34002. this._shadowGenerator.recreateShadowMap();
  34003. }
  34004. },
  34005. enumerable: true,
  34006. configurable: true
  34007. });
  34008. /**
  34009. * Returns the string "PointLight"
  34010. */
  34011. PointLight.prototype.getClassName = function () {
  34012. return "PointLight";
  34013. };
  34014. /**
  34015. * Returns the integer 0.
  34016. */
  34017. PointLight.prototype.getTypeID = function () {
  34018. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  34019. };
  34020. /**
  34021. * Specifies wether or not the shadowmap should be a cube texture.
  34022. */
  34023. PointLight.prototype.needCube = function () {
  34024. return !this.direction;
  34025. };
  34026. /**
  34027. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  34028. */
  34029. PointLight.prototype.getShadowDirection = function (faceIndex) {
  34030. if (this.direction) {
  34031. return _super.prototype.getShadowDirection.call(this, faceIndex);
  34032. }
  34033. else {
  34034. switch (faceIndex) {
  34035. case 0:
  34036. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  34037. case 1:
  34038. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  34039. case 2:
  34040. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  34041. case 3:
  34042. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  34043. case 4:
  34044. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  34045. case 5:
  34046. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  34047. }
  34048. }
  34049. return BABYLON.Vector3.Zero();
  34050. };
  34051. /**
  34052. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  34053. * - fov = PI / 2
  34054. * - aspect ratio : 1.0
  34055. * - z-near and far equal to the active camera minZ and maxZ.
  34056. * Returns the PointLight.
  34057. */
  34058. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34059. var activeCamera = this.getScene().activeCamera;
  34060. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34061. };
  34062. PointLight.prototype._buildUniformLayout = function () {
  34063. this._uniformBuffer.addUniform("vLightData", 4);
  34064. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34065. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34066. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34067. this._uniformBuffer.addUniform("depthValues", 2);
  34068. this._uniformBuffer.create();
  34069. };
  34070. /**
  34071. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  34072. * Returns the PointLight.
  34073. */
  34074. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  34075. if (this.computeTransformedInformation()) {
  34076. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  34077. return this;
  34078. }
  34079. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  34080. return this;
  34081. };
  34082. return PointLight;
  34083. }(BABYLON.ShadowLight));
  34084. __decorate([
  34085. BABYLON.serialize()
  34086. ], PointLight.prototype, "shadowAngle", null);
  34087. BABYLON.PointLight = PointLight;
  34088. })(BABYLON || (BABYLON = {}));
  34089. //# sourceMappingURL=babylon.pointLight.js.map
  34090. /// <reference path="babylon.light.ts" />
  34091. var BABYLON;
  34092. (function (BABYLON) {
  34093. var DirectionalLight = (function (_super) {
  34094. __extends(DirectionalLight, _super);
  34095. /**
  34096. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  34097. * The directional light is emitted from everywhere in the given direction.
  34098. * It can cast shawdows.
  34099. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34100. */
  34101. function DirectionalLight(name, direction, scene) {
  34102. var _this = _super.call(this, name, scene) || this;
  34103. _this._shadowFrustumSize = 0;
  34104. _this._shadowOrthoScale = 0.5;
  34105. _this.autoUpdateExtends = true;
  34106. // Cache
  34107. _this._orthoLeft = Number.MAX_VALUE;
  34108. _this._orthoRight = Number.MIN_VALUE;
  34109. _this._orthoTop = Number.MIN_VALUE;
  34110. _this._orthoBottom = Number.MAX_VALUE;
  34111. _this.position = direction.scale(-1.0);
  34112. _this.direction = direction;
  34113. return _this;
  34114. }
  34115. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  34116. /**
  34117. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  34118. */
  34119. get: function () {
  34120. return this._shadowFrustumSize;
  34121. },
  34122. /**
  34123. * Specifies a fix frustum size for the shadow generation.
  34124. */
  34125. set: function (value) {
  34126. this._shadowFrustumSize = value;
  34127. this.forceProjectionMatrixCompute();
  34128. },
  34129. enumerable: true,
  34130. configurable: true
  34131. });
  34132. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  34133. get: function () {
  34134. return this._shadowOrthoScale;
  34135. },
  34136. set: function (value) {
  34137. this._shadowOrthoScale = value;
  34138. this.forceProjectionMatrixCompute();
  34139. },
  34140. enumerable: true,
  34141. configurable: true
  34142. });
  34143. /**
  34144. * Returns the string "DirectionalLight".
  34145. */
  34146. DirectionalLight.prototype.getClassName = function () {
  34147. return "DirectionalLight";
  34148. };
  34149. /**
  34150. * Returns the integer 1.
  34151. */
  34152. DirectionalLight.prototype.getTypeID = function () {
  34153. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  34154. };
  34155. /**
  34156. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  34157. * Returns the DirectionalLight Shadow projection matrix.
  34158. */
  34159. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34160. if (this.shadowFrustumSize > 0) {
  34161. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  34162. }
  34163. else {
  34164. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34165. }
  34166. };
  34167. /**
  34168. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  34169. * Returns the DirectionalLight Shadow projection matrix.
  34170. */
  34171. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  34172. var activeCamera = this.getScene().activeCamera;
  34173. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  34174. };
  34175. /**
  34176. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  34177. * Returns the DirectionalLight Shadow projection matrix.
  34178. */
  34179. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34180. var activeCamera = this.getScene().activeCamera;
  34181. // Check extends
  34182. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  34183. var tempVector3 = BABYLON.Vector3.Zero();
  34184. this._orthoLeft = Number.MAX_VALUE;
  34185. this._orthoRight = Number.MIN_VALUE;
  34186. this._orthoTop = Number.MIN_VALUE;
  34187. this._orthoBottom = Number.MAX_VALUE;
  34188. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  34189. var mesh = renderList[meshIndex];
  34190. if (!mesh) {
  34191. continue;
  34192. }
  34193. var boundingInfo = mesh.getBoundingInfo();
  34194. if (!boundingInfo) {
  34195. continue;
  34196. }
  34197. var boundingBox = boundingInfo.boundingBox;
  34198. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  34199. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  34200. if (tempVector3.x < this._orthoLeft)
  34201. this._orthoLeft = tempVector3.x;
  34202. if (tempVector3.y < this._orthoBottom)
  34203. this._orthoBottom = tempVector3.y;
  34204. if (tempVector3.x > this._orthoRight)
  34205. this._orthoRight = tempVector3.x;
  34206. if (tempVector3.y > this._orthoTop)
  34207. this._orthoTop = tempVector3.y;
  34208. }
  34209. }
  34210. }
  34211. var xOffset = this._orthoRight - this._orthoLeft;
  34212. var yOffset = this._orthoTop - this._orthoBottom;
  34213. 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);
  34214. };
  34215. DirectionalLight.prototype._buildUniformLayout = function () {
  34216. this._uniformBuffer.addUniform("vLightData", 4);
  34217. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34218. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34219. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34220. this._uniformBuffer.addUniform("depthValues", 2);
  34221. this._uniformBuffer.create();
  34222. };
  34223. /**
  34224. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  34225. * Returns the DirectionalLight.
  34226. */
  34227. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  34228. if (this.computeTransformedInformation()) {
  34229. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  34230. return this;
  34231. }
  34232. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  34233. return this;
  34234. };
  34235. /**
  34236. * Gets the minZ used for shadow according to both the scene and the light.
  34237. *
  34238. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34239. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34240. * @param activeCamera
  34241. */
  34242. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  34243. return 1;
  34244. };
  34245. /**
  34246. * Gets the maxZ used for shadow according to both the scene and the light.
  34247. *
  34248. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34249. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34250. * @param activeCamera
  34251. */
  34252. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  34253. return 1;
  34254. };
  34255. return DirectionalLight;
  34256. }(BABYLON.ShadowLight));
  34257. __decorate([
  34258. BABYLON.serialize()
  34259. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  34260. __decorate([
  34261. BABYLON.serialize()
  34262. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  34263. __decorate([
  34264. BABYLON.serialize()
  34265. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  34266. BABYLON.DirectionalLight = DirectionalLight;
  34267. })(BABYLON || (BABYLON = {}));
  34268. //# sourceMappingURL=babylon.directionalLight.js.map
  34269. var BABYLON;
  34270. (function (BABYLON) {
  34271. var SpotLight = (function (_super) {
  34272. __extends(SpotLight, _super);
  34273. /**
  34274. * Creates a SpotLight object in the scene with the passed parameters :
  34275. * - `position` (Vector3) is the initial SpotLight position,
  34276. * - `direction` (Vector3) is the initial SpotLight direction,
  34277. * - `angle` (float, in radians) is the spot light cone angle,
  34278. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  34279. * A spot light is a simply light oriented cone.
  34280. * It can cast shadows.
  34281. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34282. */
  34283. function SpotLight(name, position, direction, angle, exponent, scene) {
  34284. var _this = _super.call(this, name, scene) || this;
  34285. _this.position = position;
  34286. _this.direction = direction;
  34287. _this.angle = angle;
  34288. _this.exponent = exponent;
  34289. return _this;
  34290. }
  34291. Object.defineProperty(SpotLight.prototype, "angle", {
  34292. get: function () {
  34293. return this._angle;
  34294. },
  34295. set: function (value) {
  34296. this._angle = value;
  34297. this.forceProjectionMatrixCompute();
  34298. },
  34299. enumerable: true,
  34300. configurable: true
  34301. });
  34302. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  34303. get: function () {
  34304. return this._shadowAngleScale;
  34305. },
  34306. /**
  34307. * Allows scaling the angle of the light for shadow generation only.
  34308. */
  34309. set: function (value) {
  34310. this._shadowAngleScale = value;
  34311. this.forceProjectionMatrixCompute();
  34312. },
  34313. enumerable: true,
  34314. configurable: true
  34315. });
  34316. /**
  34317. * Returns the string "SpotLight".
  34318. */
  34319. SpotLight.prototype.getClassName = function () {
  34320. return "SpotLight";
  34321. };
  34322. /**
  34323. * Returns the integer 2.
  34324. */
  34325. SpotLight.prototype.getTypeID = function () {
  34326. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  34327. };
  34328. /**
  34329. * 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.
  34330. * Returns the SpotLight.
  34331. */
  34332. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34333. var activeCamera = this.getScene().activeCamera;
  34334. this._shadowAngleScale = this._shadowAngleScale || 1;
  34335. var angle = this._shadowAngleScale * this._angle;
  34336. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34337. };
  34338. SpotLight.prototype._buildUniformLayout = function () {
  34339. this._uniformBuffer.addUniform("vLightData", 4);
  34340. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34341. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34342. this._uniformBuffer.addUniform("vLightDirection", 3);
  34343. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34344. this._uniformBuffer.addUniform("depthValues", 2);
  34345. this._uniformBuffer.create();
  34346. };
  34347. /**
  34348. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  34349. * Return the SpotLight.
  34350. */
  34351. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  34352. var normalizeDirection;
  34353. if (this.computeTransformedInformation()) {
  34354. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  34355. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  34356. }
  34357. else {
  34358. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  34359. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34360. }
  34361. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  34362. return this;
  34363. };
  34364. return SpotLight;
  34365. }(BABYLON.ShadowLight));
  34366. __decorate([
  34367. BABYLON.serialize()
  34368. ], SpotLight.prototype, "angle", null);
  34369. __decorate([
  34370. BABYLON.serialize()
  34371. /**
  34372. * Allows scaling the angle of the light for shadow generation only.
  34373. */
  34374. ], SpotLight.prototype, "shadowAngleScale", null);
  34375. __decorate([
  34376. BABYLON.serialize()
  34377. ], SpotLight.prototype, "exponent", void 0);
  34378. BABYLON.SpotLight = SpotLight;
  34379. })(BABYLON || (BABYLON = {}));
  34380. //# sourceMappingURL=babylon.spotLight.js.map
  34381. var BABYLON;
  34382. (function (BABYLON) {
  34383. var AnimationRange = (function () {
  34384. function AnimationRange(name, from, to) {
  34385. this.name = name;
  34386. this.from = from;
  34387. this.to = to;
  34388. }
  34389. AnimationRange.prototype.clone = function () {
  34390. return new AnimationRange(this.name, this.from, this.to);
  34391. };
  34392. return AnimationRange;
  34393. }());
  34394. BABYLON.AnimationRange = AnimationRange;
  34395. /**
  34396. * Composed of a frame, and an action function
  34397. */
  34398. var AnimationEvent = (function () {
  34399. function AnimationEvent(frame, action, onlyOnce) {
  34400. this.frame = frame;
  34401. this.action = action;
  34402. this.onlyOnce = onlyOnce;
  34403. this.isDone = false;
  34404. }
  34405. return AnimationEvent;
  34406. }());
  34407. BABYLON.AnimationEvent = AnimationEvent;
  34408. var PathCursor = (function () {
  34409. function PathCursor(path) {
  34410. this.path = path;
  34411. this._onchange = new Array();
  34412. this.value = 0;
  34413. this.animations = new Array();
  34414. }
  34415. PathCursor.prototype.getPoint = function () {
  34416. var point = this.path.getPointAtLengthPosition(this.value);
  34417. return new BABYLON.Vector3(point.x, 0, point.y);
  34418. };
  34419. PathCursor.prototype.moveAhead = function (step) {
  34420. if (step === void 0) { step = 0.002; }
  34421. this.move(step);
  34422. return this;
  34423. };
  34424. PathCursor.prototype.moveBack = function (step) {
  34425. if (step === void 0) { step = 0.002; }
  34426. this.move(-step);
  34427. return this;
  34428. };
  34429. PathCursor.prototype.move = function (step) {
  34430. if (Math.abs(step) > 1) {
  34431. throw "step size should be less than 1.";
  34432. }
  34433. this.value += step;
  34434. this.ensureLimits();
  34435. this.raiseOnChange();
  34436. return this;
  34437. };
  34438. PathCursor.prototype.ensureLimits = function () {
  34439. while (this.value > 1) {
  34440. this.value -= 1;
  34441. }
  34442. while (this.value < 0) {
  34443. this.value += 1;
  34444. }
  34445. return this;
  34446. };
  34447. // used by animation engine
  34448. PathCursor.prototype.markAsDirty = function (propertyName) {
  34449. this.ensureLimits();
  34450. this.raiseOnChange();
  34451. return this;
  34452. };
  34453. PathCursor.prototype.raiseOnChange = function () {
  34454. var _this = this;
  34455. this._onchange.forEach(function (f) { return f(_this); });
  34456. return this;
  34457. };
  34458. PathCursor.prototype.onchange = function (f) {
  34459. this._onchange.push(f);
  34460. return this;
  34461. };
  34462. return PathCursor;
  34463. }());
  34464. BABYLON.PathCursor = PathCursor;
  34465. var Animation = (function () {
  34466. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  34467. this.name = name;
  34468. this.targetProperty = targetProperty;
  34469. this.framePerSecond = framePerSecond;
  34470. this.dataType = dataType;
  34471. this.loopMode = loopMode;
  34472. this.enableBlending = enableBlending;
  34473. this._offsetsCache = {};
  34474. this._highLimitsCache = {};
  34475. this._stopped = false;
  34476. this._blendingFactor = 0;
  34477. // The set of event that will be linked to this animation
  34478. this._events = new Array();
  34479. this.allowMatricesInterpolation = false;
  34480. this.blendingSpeed = 0.01;
  34481. this._ranges = {};
  34482. this.targetPropertyPath = targetProperty.split(".");
  34483. this.dataType = dataType;
  34484. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  34485. }
  34486. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  34487. var dataType = undefined;
  34488. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  34489. dataType = Animation.ANIMATIONTYPE_FLOAT;
  34490. }
  34491. else if (from instanceof BABYLON.Quaternion) {
  34492. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  34493. }
  34494. else if (from instanceof BABYLON.Vector3) {
  34495. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  34496. }
  34497. else if (from instanceof BABYLON.Vector2) {
  34498. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  34499. }
  34500. else if (from instanceof BABYLON.Color3) {
  34501. dataType = Animation.ANIMATIONTYPE_COLOR3;
  34502. }
  34503. else if (from instanceof BABYLON.Size) {
  34504. dataType = Animation.ANIMATIONTYPE_SIZE;
  34505. }
  34506. if (dataType == undefined) {
  34507. return null;
  34508. }
  34509. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  34510. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  34511. animation.setKeys(keys);
  34512. if (easingFunction !== undefined) {
  34513. animation.setEasingFunction(easingFunction);
  34514. }
  34515. return animation;
  34516. };
  34517. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34518. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34519. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34520. };
  34521. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34522. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34523. node.animations.push(animation);
  34524. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34525. };
  34526. // Methods
  34527. /**
  34528. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34529. */
  34530. Animation.prototype.toString = function (fullDetails) {
  34531. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  34532. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  34533. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  34534. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34535. if (fullDetails) {
  34536. ret += ", Ranges: {";
  34537. var first = true;
  34538. for (var name in this._ranges) {
  34539. if (first) {
  34540. ret += ", ";
  34541. first = false;
  34542. }
  34543. ret += name;
  34544. }
  34545. ret += "}";
  34546. }
  34547. return ret;
  34548. };
  34549. /**
  34550. * Add an event to this animation.
  34551. */
  34552. Animation.prototype.addEvent = function (event) {
  34553. this._events.push(event);
  34554. };
  34555. /**
  34556. * Remove all events found at the given frame
  34557. * @param frame
  34558. */
  34559. Animation.prototype.removeEvents = function (frame) {
  34560. for (var index = 0; index < this._events.length; index++) {
  34561. if (this._events[index].frame === frame) {
  34562. this._events.splice(index, 1);
  34563. index--;
  34564. }
  34565. }
  34566. };
  34567. Animation.prototype.createRange = function (name, from, to) {
  34568. // check name not already in use; could happen for bones after serialized
  34569. if (!this._ranges[name]) {
  34570. this._ranges[name] = new AnimationRange(name, from, to);
  34571. }
  34572. };
  34573. Animation.prototype.deleteRange = function (name, deleteFrames) {
  34574. if (deleteFrames === void 0) { deleteFrames = true; }
  34575. if (this._ranges[name]) {
  34576. if (deleteFrames) {
  34577. var from = this._ranges[name].from;
  34578. var to = this._ranges[name].to;
  34579. // this loop MUST go high to low for multiple splices to work
  34580. for (var key = this._keys.length - 1; key >= 0; key--) {
  34581. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  34582. this._keys.splice(key, 1);
  34583. }
  34584. }
  34585. }
  34586. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34587. }
  34588. };
  34589. Animation.prototype.getRange = function (name) {
  34590. return this._ranges[name];
  34591. };
  34592. Animation.prototype.reset = function () {
  34593. this._offsetsCache = {};
  34594. this._highLimitsCache = {};
  34595. this.currentFrame = 0;
  34596. this._blendingFactor = 0;
  34597. this._originalBlendValue = null;
  34598. };
  34599. Animation.prototype.isStopped = function () {
  34600. return this._stopped;
  34601. };
  34602. Animation.prototype.getKeys = function () {
  34603. return this._keys;
  34604. };
  34605. Animation.prototype.getHighestFrame = function () {
  34606. var ret = 0;
  34607. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  34608. if (ret < this._keys[key].frame) {
  34609. ret = this._keys[key].frame;
  34610. }
  34611. }
  34612. return ret;
  34613. };
  34614. Animation.prototype.getEasingFunction = function () {
  34615. return this._easingFunction;
  34616. };
  34617. Animation.prototype.setEasingFunction = function (easingFunction) {
  34618. this._easingFunction = easingFunction;
  34619. };
  34620. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  34621. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  34622. };
  34623. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34624. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34625. };
  34626. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  34627. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  34628. };
  34629. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34630. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  34631. };
  34632. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  34633. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  34634. };
  34635. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34636. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34637. };
  34638. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  34639. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  34640. };
  34641. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34642. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34643. };
  34644. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  34645. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  34646. };
  34647. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  34648. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  34649. };
  34650. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  34651. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  34652. };
  34653. Animation.prototype.clone = function () {
  34654. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  34655. clone.enableBlending = this.enableBlending;
  34656. clone.blendingSpeed = this.blendingSpeed;
  34657. if (this._keys) {
  34658. clone.setKeys(this._keys);
  34659. }
  34660. if (this._ranges) {
  34661. clone._ranges = {};
  34662. for (var name in this._ranges) {
  34663. clone._ranges[name] = this._ranges[name].clone();
  34664. }
  34665. }
  34666. return clone;
  34667. };
  34668. Animation.prototype.setKeys = function (values) {
  34669. this._keys = values.slice(0);
  34670. this._offsetsCache = {};
  34671. this._highLimitsCache = {};
  34672. };
  34673. Animation.prototype._getKeyValue = function (value) {
  34674. if (typeof value === "function") {
  34675. return value();
  34676. }
  34677. return value;
  34678. };
  34679. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  34680. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  34681. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  34682. }
  34683. this.currentFrame = currentFrame;
  34684. // Try to get a hash to find the right key
  34685. 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));
  34686. if (this._keys[startKeyIndex].frame >= currentFrame) {
  34687. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  34688. startKeyIndex--;
  34689. }
  34690. }
  34691. for (var key = startKeyIndex; key < this._keys.length; key++) {
  34692. var endKey = this._keys[key + 1];
  34693. if (endKey.frame >= currentFrame) {
  34694. var startKey = this._keys[key];
  34695. var startValue = this._getKeyValue(startKey.value);
  34696. var endValue = this._getKeyValue(endKey.value);
  34697. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  34698. var frameDelta = endKey.frame - startKey.frame;
  34699. // gradient : percent of currentFrame between the frame inf and the frame sup
  34700. var gradient = (currentFrame - startKey.frame) / frameDelta;
  34701. // check for easingFunction and correction of gradient
  34702. if (this._easingFunction != null) {
  34703. gradient = this._easingFunction.ease(gradient);
  34704. }
  34705. switch (this.dataType) {
  34706. // Float
  34707. case Animation.ANIMATIONTYPE_FLOAT:
  34708. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  34709. switch (loopMode) {
  34710. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34711. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34712. return floatValue;
  34713. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34714. return offsetValue * repeatCount + floatValue;
  34715. }
  34716. break;
  34717. // Quaternion
  34718. case Animation.ANIMATIONTYPE_QUATERNION:
  34719. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  34720. switch (loopMode) {
  34721. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34722. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34723. return quatValue;
  34724. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34725. return quatValue.add(offsetValue.scale(repeatCount));
  34726. }
  34727. return quatValue;
  34728. // Vector3
  34729. case Animation.ANIMATIONTYPE_VECTOR3:
  34730. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  34731. switch (loopMode) {
  34732. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34733. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34734. return vec3Value;
  34735. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34736. return vec3Value.add(offsetValue.scale(repeatCount));
  34737. }
  34738. // Vector2
  34739. case Animation.ANIMATIONTYPE_VECTOR2:
  34740. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  34741. switch (loopMode) {
  34742. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34743. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34744. return vec2Value;
  34745. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34746. return vec2Value.add(offsetValue.scale(repeatCount));
  34747. }
  34748. // Size
  34749. case Animation.ANIMATIONTYPE_SIZE:
  34750. switch (loopMode) {
  34751. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34752. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34753. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  34754. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34755. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34756. }
  34757. // Color3
  34758. case Animation.ANIMATIONTYPE_COLOR3:
  34759. switch (loopMode) {
  34760. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34761. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34762. return this.color3InterpolateFunction(startValue, endValue, gradient);
  34763. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34764. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34765. }
  34766. // Matrix
  34767. case Animation.ANIMATIONTYPE_MATRIX:
  34768. switch (loopMode) {
  34769. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34770. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34771. if (this.allowMatricesInterpolation) {
  34772. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  34773. }
  34774. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34775. return startValue;
  34776. }
  34777. default:
  34778. break;
  34779. }
  34780. break;
  34781. }
  34782. }
  34783. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  34784. };
  34785. Animation.prototype.setValue = function (currentValue, blend) {
  34786. if (blend === void 0) { blend = false; }
  34787. // Set value
  34788. var path;
  34789. var destination;
  34790. if (this.targetPropertyPath.length > 1) {
  34791. var property = this._target[this.targetPropertyPath[0]];
  34792. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  34793. property = property[this.targetPropertyPath[index]];
  34794. }
  34795. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  34796. destination = property;
  34797. }
  34798. else {
  34799. path = this.targetPropertyPath[0];
  34800. destination = this._target;
  34801. }
  34802. // Blending
  34803. if (this.enableBlending && this._blendingFactor <= 1.0) {
  34804. if (!this._originalBlendValue) {
  34805. if (destination[path].clone) {
  34806. this._originalBlendValue = destination[path].clone();
  34807. }
  34808. else {
  34809. this._originalBlendValue = destination[path];
  34810. }
  34811. }
  34812. if (this._originalBlendValue.prototype) {
  34813. if (this._originalBlendValue.prototype.Lerp) {
  34814. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  34815. }
  34816. else {
  34817. destination[path] = currentValue;
  34818. }
  34819. }
  34820. else if (this._originalBlendValue.m) {
  34821. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  34822. }
  34823. else {
  34824. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  34825. }
  34826. this._blendingFactor += this.blendingSpeed;
  34827. }
  34828. else {
  34829. destination[path] = currentValue;
  34830. }
  34831. if (this._target.markAsDirty) {
  34832. this._target.markAsDirty(this.targetProperty);
  34833. }
  34834. };
  34835. Animation.prototype.goToFrame = function (frame) {
  34836. if (frame < this._keys[0].frame) {
  34837. frame = this._keys[0].frame;
  34838. }
  34839. else if (frame > this._keys[this._keys.length - 1].frame) {
  34840. frame = this._keys[this._keys.length - 1].frame;
  34841. }
  34842. var currentValue = this._interpolate(frame, 0, this.loopMode);
  34843. this.setValue(currentValue);
  34844. };
  34845. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  34846. if (blend === void 0) { blend = false; }
  34847. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  34848. this._stopped = true;
  34849. return false;
  34850. }
  34851. var returnValue = true;
  34852. // Adding a start key at frame 0 if missing
  34853. if (this._keys[0].frame !== 0) {
  34854. var newKey = { frame: 0, value: this._keys[0].value };
  34855. this._keys.splice(0, 0, newKey);
  34856. }
  34857. // Check limits
  34858. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  34859. from = this._keys[0].frame;
  34860. }
  34861. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  34862. to = this._keys[this._keys.length - 1].frame;
  34863. }
  34864. //to and from cannot be the same key
  34865. if (from === to) {
  34866. from++;
  34867. }
  34868. // Compute ratio
  34869. var range = to - from;
  34870. var offsetValue;
  34871. // ratio represents the frame delta between from and to
  34872. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  34873. var highLimitValue = 0;
  34874. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  34875. returnValue = false;
  34876. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  34877. }
  34878. else {
  34879. // Get max value if required
  34880. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  34881. var keyOffset = to.toString() + from.toString();
  34882. if (!this._offsetsCache[keyOffset]) {
  34883. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34884. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34885. switch (this.dataType) {
  34886. // Float
  34887. case Animation.ANIMATIONTYPE_FLOAT:
  34888. this._offsetsCache[keyOffset] = toValue - fromValue;
  34889. break;
  34890. // Quaternion
  34891. case Animation.ANIMATIONTYPE_QUATERNION:
  34892. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34893. break;
  34894. // Vector3
  34895. case Animation.ANIMATIONTYPE_VECTOR3:
  34896. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34897. // Vector2
  34898. case Animation.ANIMATIONTYPE_VECTOR2:
  34899. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34900. // Size
  34901. case Animation.ANIMATIONTYPE_SIZE:
  34902. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34903. // Color3
  34904. case Animation.ANIMATIONTYPE_COLOR3:
  34905. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34906. default:
  34907. break;
  34908. }
  34909. this._highLimitsCache[keyOffset] = toValue;
  34910. }
  34911. highLimitValue = this._highLimitsCache[keyOffset];
  34912. offsetValue = this._offsetsCache[keyOffset];
  34913. }
  34914. }
  34915. if (offsetValue === undefined) {
  34916. switch (this.dataType) {
  34917. // Float
  34918. case Animation.ANIMATIONTYPE_FLOAT:
  34919. offsetValue = 0;
  34920. break;
  34921. // Quaternion
  34922. case Animation.ANIMATIONTYPE_QUATERNION:
  34923. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  34924. break;
  34925. // Vector3
  34926. case Animation.ANIMATIONTYPE_VECTOR3:
  34927. offsetValue = BABYLON.Vector3.Zero();
  34928. break;
  34929. // Vector2
  34930. case Animation.ANIMATIONTYPE_VECTOR2:
  34931. offsetValue = BABYLON.Vector2.Zero();
  34932. break;
  34933. // Size
  34934. case Animation.ANIMATIONTYPE_SIZE:
  34935. offsetValue = BABYLON.Size.Zero();
  34936. break;
  34937. // Color3
  34938. case Animation.ANIMATIONTYPE_COLOR3:
  34939. offsetValue = BABYLON.Color3.Black();
  34940. }
  34941. }
  34942. // Compute value
  34943. var repeatCount = (ratio / range) >> 0;
  34944. var currentFrame = returnValue ? from + ratio % range : to;
  34945. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  34946. // Set value
  34947. this.setValue(currentValue);
  34948. // Check events
  34949. for (var index = 0; index < this._events.length; index++) {
  34950. // Make sure current frame has passed event frame and that event frame is within the current range
  34951. // Also, handle both forward and reverse animations
  34952. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  34953. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  34954. var event = this._events[index];
  34955. if (!event.isDone) {
  34956. // If event should be done only once, remove it.
  34957. if (event.onlyOnce) {
  34958. this._events.splice(index, 1);
  34959. index--;
  34960. }
  34961. event.isDone = true;
  34962. event.action();
  34963. } // Don't do anything if the event has already be done.
  34964. }
  34965. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  34966. // reset event, the animation is looping
  34967. this._events[index].isDone = false;
  34968. }
  34969. }
  34970. if (!returnValue) {
  34971. this._stopped = true;
  34972. }
  34973. return returnValue;
  34974. };
  34975. Animation.prototype.serialize = function () {
  34976. var serializationObject = {};
  34977. serializationObject.name = this.name;
  34978. serializationObject.property = this.targetProperty;
  34979. serializationObject.framePerSecond = this.framePerSecond;
  34980. serializationObject.dataType = this.dataType;
  34981. serializationObject.loopBehavior = this.loopMode;
  34982. serializationObject.enableBlending = this.enableBlending;
  34983. serializationObject.blendingSpeed = this.blendingSpeed;
  34984. var dataType = this.dataType;
  34985. serializationObject.keys = [];
  34986. var keys = this.getKeys();
  34987. for (var index = 0; index < keys.length; index++) {
  34988. var animationKey = keys[index];
  34989. var key = {};
  34990. key.frame = animationKey.frame;
  34991. switch (dataType) {
  34992. case Animation.ANIMATIONTYPE_FLOAT:
  34993. key.values = [animationKey.value];
  34994. break;
  34995. case Animation.ANIMATIONTYPE_QUATERNION:
  34996. case Animation.ANIMATIONTYPE_MATRIX:
  34997. case Animation.ANIMATIONTYPE_VECTOR3:
  34998. case Animation.ANIMATIONTYPE_COLOR3:
  34999. key.values = animationKey.value.asArray();
  35000. break;
  35001. }
  35002. serializationObject.keys.push(key);
  35003. }
  35004. serializationObject.ranges = [];
  35005. for (var name in this._ranges) {
  35006. var range = {};
  35007. range.name = name;
  35008. range.from = this._ranges[name].from;
  35009. range.to = this._ranges[name].to;
  35010. serializationObject.ranges.push(range);
  35011. }
  35012. return serializationObject;
  35013. };
  35014. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  35015. get: function () {
  35016. return Animation._ANIMATIONTYPE_FLOAT;
  35017. },
  35018. enumerable: true,
  35019. configurable: true
  35020. });
  35021. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  35022. get: function () {
  35023. return Animation._ANIMATIONTYPE_VECTOR3;
  35024. },
  35025. enumerable: true,
  35026. configurable: true
  35027. });
  35028. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  35029. get: function () {
  35030. return Animation._ANIMATIONTYPE_VECTOR2;
  35031. },
  35032. enumerable: true,
  35033. configurable: true
  35034. });
  35035. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  35036. get: function () {
  35037. return Animation._ANIMATIONTYPE_SIZE;
  35038. },
  35039. enumerable: true,
  35040. configurable: true
  35041. });
  35042. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  35043. get: function () {
  35044. return Animation._ANIMATIONTYPE_QUATERNION;
  35045. },
  35046. enumerable: true,
  35047. configurable: true
  35048. });
  35049. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  35050. get: function () {
  35051. return Animation._ANIMATIONTYPE_MATRIX;
  35052. },
  35053. enumerable: true,
  35054. configurable: true
  35055. });
  35056. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  35057. get: function () {
  35058. return Animation._ANIMATIONTYPE_COLOR3;
  35059. },
  35060. enumerable: true,
  35061. configurable: true
  35062. });
  35063. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  35064. get: function () {
  35065. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  35066. },
  35067. enumerable: true,
  35068. configurable: true
  35069. });
  35070. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  35071. get: function () {
  35072. return Animation._ANIMATIONLOOPMODE_CYCLE;
  35073. },
  35074. enumerable: true,
  35075. configurable: true
  35076. });
  35077. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  35078. get: function () {
  35079. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  35080. },
  35081. enumerable: true,
  35082. configurable: true
  35083. });
  35084. Animation.Parse = function (parsedAnimation) {
  35085. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  35086. var dataType = parsedAnimation.dataType;
  35087. var keys = [];
  35088. var data;
  35089. var index;
  35090. if (parsedAnimation.enableBlending) {
  35091. animation.enableBlending = parsedAnimation.enableBlending;
  35092. }
  35093. if (parsedAnimation.blendingSpeed) {
  35094. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  35095. }
  35096. for (index = 0; index < parsedAnimation.keys.length; index++) {
  35097. var key = parsedAnimation.keys[index];
  35098. switch (dataType) {
  35099. case Animation.ANIMATIONTYPE_FLOAT:
  35100. data = key.values[0];
  35101. break;
  35102. case Animation.ANIMATIONTYPE_QUATERNION:
  35103. data = BABYLON.Quaternion.FromArray(key.values);
  35104. break;
  35105. case Animation.ANIMATIONTYPE_MATRIX:
  35106. data = BABYLON.Matrix.FromArray(key.values);
  35107. break;
  35108. case Animation.ANIMATIONTYPE_COLOR3:
  35109. data = BABYLON.Color3.FromArray(key.values);
  35110. break;
  35111. case Animation.ANIMATIONTYPE_VECTOR3:
  35112. default:
  35113. data = BABYLON.Vector3.FromArray(key.values);
  35114. break;
  35115. }
  35116. keys.push({
  35117. frame: key.frame,
  35118. value: data
  35119. });
  35120. }
  35121. animation.setKeys(keys);
  35122. if (parsedAnimation.ranges) {
  35123. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  35124. data = parsedAnimation.ranges[index];
  35125. animation.createRange(data.name, data.from, data.to);
  35126. }
  35127. }
  35128. return animation;
  35129. };
  35130. Animation.AppendSerializedAnimations = function (source, destination) {
  35131. if (source.animations) {
  35132. destination.animations = [];
  35133. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  35134. var animation = source.animations[animationIndex];
  35135. destination.animations.push(animation.serialize());
  35136. }
  35137. }
  35138. };
  35139. return Animation;
  35140. }());
  35141. // Statics
  35142. Animation._ANIMATIONTYPE_FLOAT = 0;
  35143. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  35144. Animation._ANIMATIONTYPE_QUATERNION = 2;
  35145. Animation._ANIMATIONTYPE_MATRIX = 3;
  35146. Animation._ANIMATIONTYPE_COLOR3 = 4;
  35147. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  35148. Animation._ANIMATIONTYPE_SIZE = 6;
  35149. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  35150. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  35151. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  35152. BABYLON.Animation = Animation;
  35153. })(BABYLON || (BABYLON = {}));
  35154. //# sourceMappingURL=babylon.animation.js.map
  35155. var BABYLON;
  35156. (function (BABYLON) {
  35157. var Animatable = (function () {
  35158. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  35159. if (fromFrame === void 0) { fromFrame = 0; }
  35160. if (toFrame === void 0) { toFrame = 100; }
  35161. if (loopAnimation === void 0) { loopAnimation = false; }
  35162. if (speedRatio === void 0) { speedRatio = 1.0; }
  35163. this.target = target;
  35164. this.fromFrame = fromFrame;
  35165. this.toFrame = toFrame;
  35166. this.loopAnimation = loopAnimation;
  35167. this.speedRatio = speedRatio;
  35168. this.onAnimationEnd = onAnimationEnd;
  35169. this._localDelayOffset = null;
  35170. this._pausedDelay = null;
  35171. this._animations = new Array();
  35172. this._paused = false;
  35173. this.animationStarted = false;
  35174. if (animations) {
  35175. this.appendAnimations(target, animations);
  35176. }
  35177. this._scene = scene;
  35178. scene._activeAnimatables.push(this);
  35179. }
  35180. // Methods
  35181. Animatable.prototype.getAnimations = function () {
  35182. return this._animations;
  35183. };
  35184. Animatable.prototype.appendAnimations = function (target, animations) {
  35185. for (var index = 0; index < animations.length; index++) {
  35186. var animation = animations[index];
  35187. animation._target = target;
  35188. this._animations.push(animation);
  35189. }
  35190. };
  35191. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  35192. var animations = this._animations;
  35193. for (var index = 0; index < animations.length; index++) {
  35194. if (animations[index].targetProperty === property) {
  35195. return animations[index];
  35196. }
  35197. }
  35198. return null;
  35199. };
  35200. Animatable.prototype.reset = function () {
  35201. var animations = this._animations;
  35202. for (var index = 0; index < animations.length; index++) {
  35203. animations[index].reset();
  35204. }
  35205. this._localDelayOffset = null;
  35206. this._pausedDelay = null;
  35207. };
  35208. Animatable.prototype.enableBlending = function (blendingSpeed) {
  35209. var animations = this._animations;
  35210. for (var index = 0; index < animations.length; index++) {
  35211. animations[index].enableBlending = true;
  35212. animations[index].blendingSpeed = blendingSpeed;
  35213. }
  35214. };
  35215. Animatable.prototype.disableBlending = function () {
  35216. var animations = this._animations;
  35217. for (var index = 0; index < animations.length; index++) {
  35218. animations[index].enableBlending = false;
  35219. }
  35220. };
  35221. Animatable.prototype.goToFrame = function (frame) {
  35222. var animations = this._animations;
  35223. if (animations[0]) {
  35224. var fps = animations[0].framePerSecond;
  35225. var currentFrame = animations[0].currentFrame;
  35226. var adjustTime = frame - currentFrame;
  35227. var delay = adjustTime * 1000 / fps;
  35228. this._localDelayOffset -= delay;
  35229. }
  35230. for (var index = 0; index < animations.length; index++) {
  35231. animations[index].goToFrame(frame);
  35232. }
  35233. };
  35234. Animatable.prototype.pause = function () {
  35235. if (this._paused) {
  35236. return;
  35237. }
  35238. this._paused = true;
  35239. };
  35240. Animatable.prototype.restart = function () {
  35241. this._paused = false;
  35242. };
  35243. Animatable.prototype.stop = function (animationName) {
  35244. if (animationName) {
  35245. var idx = this._scene._activeAnimatables.indexOf(this);
  35246. if (idx > -1) {
  35247. var animations = this._animations;
  35248. for (var index = animations.length - 1; index >= 0; index--) {
  35249. if (typeof animationName === "string" && animations[index].name != animationName) {
  35250. continue;
  35251. }
  35252. animations[index].reset();
  35253. animations.splice(index, 1);
  35254. }
  35255. if (animations.length == 0) {
  35256. this._scene._activeAnimatables.splice(idx, 1);
  35257. if (this.onAnimationEnd) {
  35258. this.onAnimationEnd();
  35259. }
  35260. }
  35261. }
  35262. }
  35263. else {
  35264. var index = this._scene._activeAnimatables.indexOf(this);
  35265. if (index > -1) {
  35266. this._scene._activeAnimatables.splice(index, 1);
  35267. var animations = this._animations;
  35268. for (var index = 0; index < animations.length; index++) {
  35269. animations[index].reset();
  35270. }
  35271. if (this.onAnimationEnd) {
  35272. this.onAnimationEnd();
  35273. }
  35274. }
  35275. }
  35276. };
  35277. Animatable.prototype._animate = function (delay) {
  35278. if (this._paused) {
  35279. this.animationStarted = false;
  35280. if (this._pausedDelay === null) {
  35281. this._pausedDelay = delay;
  35282. }
  35283. return true;
  35284. }
  35285. if (this._localDelayOffset === null) {
  35286. this._localDelayOffset = delay;
  35287. }
  35288. else if (this._pausedDelay !== null) {
  35289. this._localDelayOffset += delay - this._pausedDelay;
  35290. this._pausedDelay = null;
  35291. }
  35292. // Animating
  35293. var running = false;
  35294. var animations = this._animations;
  35295. var index;
  35296. for (index = 0; index < animations.length; index++) {
  35297. var animation = animations[index];
  35298. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  35299. running = running || isRunning;
  35300. }
  35301. this.animationStarted = running;
  35302. if (!running) {
  35303. // Remove from active animatables
  35304. index = this._scene._activeAnimatables.indexOf(this);
  35305. this._scene._activeAnimatables.splice(index, 1);
  35306. }
  35307. if (!running && this.onAnimationEnd) {
  35308. this.onAnimationEnd();
  35309. this.onAnimationEnd = null;
  35310. }
  35311. return running;
  35312. };
  35313. return Animatable;
  35314. }());
  35315. BABYLON.Animatable = Animatable;
  35316. })(BABYLON || (BABYLON = {}));
  35317. //# sourceMappingURL=babylon.animatable.js.map
  35318. var BABYLON;
  35319. (function (BABYLON) {
  35320. var EasingFunction = (function () {
  35321. function EasingFunction() {
  35322. // Properties
  35323. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  35324. }
  35325. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  35326. get: function () {
  35327. return EasingFunction._EASINGMODE_EASEIN;
  35328. },
  35329. enumerable: true,
  35330. configurable: true
  35331. });
  35332. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  35333. get: function () {
  35334. return EasingFunction._EASINGMODE_EASEOUT;
  35335. },
  35336. enumerable: true,
  35337. configurable: true
  35338. });
  35339. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  35340. get: function () {
  35341. return EasingFunction._EASINGMODE_EASEINOUT;
  35342. },
  35343. enumerable: true,
  35344. configurable: true
  35345. });
  35346. EasingFunction.prototype.setEasingMode = function (easingMode) {
  35347. var n = Math.min(Math.max(easingMode, 0), 2);
  35348. this._easingMode = n;
  35349. };
  35350. EasingFunction.prototype.getEasingMode = function () {
  35351. return this._easingMode;
  35352. };
  35353. EasingFunction.prototype.easeInCore = function (gradient) {
  35354. throw new Error('You must implement this method');
  35355. };
  35356. EasingFunction.prototype.ease = function (gradient) {
  35357. switch (this._easingMode) {
  35358. case EasingFunction.EASINGMODE_EASEIN:
  35359. return this.easeInCore(gradient);
  35360. case EasingFunction.EASINGMODE_EASEOUT:
  35361. return (1 - this.easeInCore(1 - gradient));
  35362. }
  35363. if (gradient >= 0.5) {
  35364. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  35365. }
  35366. return (this.easeInCore(gradient * 2) * 0.5);
  35367. };
  35368. return EasingFunction;
  35369. }());
  35370. //Statics
  35371. EasingFunction._EASINGMODE_EASEIN = 0;
  35372. EasingFunction._EASINGMODE_EASEOUT = 1;
  35373. EasingFunction._EASINGMODE_EASEINOUT = 2;
  35374. BABYLON.EasingFunction = EasingFunction;
  35375. var CircleEase = (function (_super) {
  35376. __extends(CircleEase, _super);
  35377. function CircleEase() {
  35378. return _super !== null && _super.apply(this, arguments) || this;
  35379. }
  35380. CircleEase.prototype.easeInCore = function (gradient) {
  35381. gradient = Math.max(0, Math.min(1, gradient));
  35382. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  35383. };
  35384. return CircleEase;
  35385. }(EasingFunction));
  35386. BABYLON.CircleEase = CircleEase;
  35387. var BackEase = (function (_super) {
  35388. __extends(BackEase, _super);
  35389. function BackEase(amplitude) {
  35390. if (amplitude === void 0) { amplitude = 1; }
  35391. var _this = _super.call(this) || this;
  35392. _this.amplitude = amplitude;
  35393. return _this;
  35394. }
  35395. BackEase.prototype.easeInCore = function (gradient) {
  35396. var num = Math.max(0, this.amplitude);
  35397. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  35398. };
  35399. return BackEase;
  35400. }(EasingFunction));
  35401. BABYLON.BackEase = BackEase;
  35402. var BounceEase = (function (_super) {
  35403. __extends(BounceEase, _super);
  35404. function BounceEase(bounces, bounciness) {
  35405. if (bounces === void 0) { bounces = 3; }
  35406. if (bounciness === void 0) { bounciness = 2; }
  35407. var _this = _super.call(this) || this;
  35408. _this.bounces = bounces;
  35409. _this.bounciness = bounciness;
  35410. return _this;
  35411. }
  35412. BounceEase.prototype.easeInCore = function (gradient) {
  35413. var y = Math.max(0.0, this.bounces);
  35414. var bounciness = this.bounciness;
  35415. if (bounciness <= 1.0) {
  35416. bounciness = 1.001;
  35417. }
  35418. var num9 = Math.pow(bounciness, y);
  35419. var num5 = 1.0 - bounciness;
  35420. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  35421. var num15 = gradient * num4;
  35422. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  35423. var num3 = Math.floor(num65);
  35424. var num13 = num3 + 1.0;
  35425. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  35426. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  35427. var num7 = (num8 + num12) * 0.5;
  35428. var num6 = gradient - num7;
  35429. var num2 = num7 - num8;
  35430. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  35431. };
  35432. return BounceEase;
  35433. }(EasingFunction));
  35434. BABYLON.BounceEase = BounceEase;
  35435. var CubicEase = (function (_super) {
  35436. __extends(CubicEase, _super);
  35437. function CubicEase() {
  35438. return _super !== null && _super.apply(this, arguments) || this;
  35439. }
  35440. CubicEase.prototype.easeInCore = function (gradient) {
  35441. return (gradient * gradient * gradient);
  35442. };
  35443. return CubicEase;
  35444. }(EasingFunction));
  35445. BABYLON.CubicEase = CubicEase;
  35446. var ElasticEase = (function (_super) {
  35447. __extends(ElasticEase, _super);
  35448. function ElasticEase(oscillations, springiness) {
  35449. if (oscillations === void 0) { oscillations = 3; }
  35450. if (springiness === void 0) { springiness = 3; }
  35451. var _this = _super.call(this) || this;
  35452. _this.oscillations = oscillations;
  35453. _this.springiness = springiness;
  35454. return _this;
  35455. }
  35456. ElasticEase.prototype.easeInCore = function (gradient) {
  35457. var num2;
  35458. var num3 = Math.max(0.0, this.oscillations);
  35459. var num = Math.max(0.0, this.springiness);
  35460. if (num == 0) {
  35461. num2 = gradient;
  35462. }
  35463. else {
  35464. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  35465. }
  35466. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  35467. };
  35468. return ElasticEase;
  35469. }(EasingFunction));
  35470. BABYLON.ElasticEase = ElasticEase;
  35471. var ExponentialEase = (function (_super) {
  35472. __extends(ExponentialEase, _super);
  35473. function ExponentialEase(exponent) {
  35474. if (exponent === void 0) { exponent = 2; }
  35475. var _this = _super.call(this) || this;
  35476. _this.exponent = exponent;
  35477. return _this;
  35478. }
  35479. ExponentialEase.prototype.easeInCore = function (gradient) {
  35480. if (this.exponent <= 0) {
  35481. return gradient;
  35482. }
  35483. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  35484. };
  35485. return ExponentialEase;
  35486. }(EasingFunction));
  35487. BABYLON.ExponentialEase = ExponentialEase;
  35488. var PowerEase = (function (_super) {
  35489. __extends(PowerEase, _super);
  35490. function PowerEase(power) {
  35491. if (power === void 0) { power = 2; }
  35492. var _this = _super.call(this) || this;
  35493. _this.power = power;
  35494. return _this;
  35495. }
  35496. PowerEase.prototype.easeInCore = function (gradient) {
  35497. var y = Math.max(0.0, this.power);
  35498. return Math.pow(gradient, y);
  35499. };
  35500. return PowerEase;
  35501. }(EasingFunction));
  35502. BABYLON.PowerEase = PowerEase;
  35503. var QuadraticEase = (function (_super) {
  35504. __extends(QuadraticEase, _super);
  35505. function QuadraticEase() {
  35506. return _super !== null && _super.apply(this, arguments) || this;
  35507. }
  35508. QuadraticEase.prototype.easeInCore = function (gradient) {
  35509. return (gradient * gradient);
  35510. };
  35511. return QuadraticEase;
  35512. }(EasingFunction));
  35513. BABYLON.QuadraticEase = QuadraticEase;
  35514. var QuarticEase = (function (_super) {
  35515. __extends(QuarticEase, _super);
  35516. function QuarticEase() {
  35517. return _super !== null && _super.apply(this, arguments) || this;
  35518. }
  35519. QuarticEase.prototype.easeInCore = function (gradient) {
  35520. return (gradient * gradient * gradient * gradient);
  35521. };
  35522. return QuarticEase;
  35523. }(EasingFunction));
  35524. BABYLON.QuarticEase = QuarticEase;
  35525. var QuinticEase = (function (_super) {
  35526. __extends(QuinticEase, _super);
  35527. function QuinticEase() {
  35528. return _super !== null && _super.apply(this, arguments) || this;
  35529. }
  35530. QuinticEase.prototype.easeInCore = function (gradient) {
  35531. return (gradient * gradient * gradient * gradient * gradient);
  35532. };
  35533. return QuinticEase;
  35534. }(EasingFunction));
  35535. BABYLON.QuinticEase = QuinticEase;
  35536. var SineEase = (function (_super) {
  35537. __extends(SineEase, _super);
  35538. function SineEase() {
  35539. return _super !== null && _super.apply(this, arguments) || this;
  35540. }
  35541. SineEase.prototype.easeInCore = function (gradient) {
  35542. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  35543. };
  35544. return SineEase;
  35545. }(EasingFunction));
  35546. BABYLON.SineEase = SineEase;
  35547. var BezierCurveEase = (function (_super) {
  35548. __extends(BezierCurveEase, _super);
  35549. function BezierCurveEase(x1, y1, x2, y2) {
  35550. if (x1 === void 0) { x1 = 0; }
  35551. if (y1 === void 0) { y1 = 0; }
  35552. if (x2 === void 0) { x2 = 1; }
  35553. if (y2 === void 0) { y2 = 1; }
  35554. var _this = _super.call(this) || this;
  35555. _this.x1 = x1;
  35556. _this.y1 = y1;
  35557. _this.x2 = x2;
  35558. _this.y2 = y2;
  35559. return _this;
  35560. }
  35561. BezierCurveEase.prototype.easeInCore = function (gradient) {
  35562. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  35563. };
  35564. return BezierCurveEase;
  35565. }(EasingFunction));
  35566. BABYLON.BezierCurveEase = BezierCurveEase;
  35567. })(BABYLON || (BABYLON = {}));
  35568. //# sourceMappingURL=babylon.easing.js.map
  35569. var BABYLON;
  35570. (function (BABYLON) {
  35571. var Condition = (function () {
  35572. function Condition(actionManager) {
  35573. this._actionManager = actionManager;
  35574. }
  35575. Condition.prototype.isValid = function () {
  35576. return true;
  35577. };
  35578. Condition.prototype._getProperty = function (propertyPath) {
  35579. return this._actionManager._getProperty(propertyPath);
  35580. };
  35581. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  35582. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35583. };
  35584. Condition.prototype.serialize = function () {
  35585. };
  35586. Condition.prototype._serialize = function (serializedCondition) {
  35587. return {
  35588. type: 2,
  35589. children: [],
  35590. name: serializedCondition.name,
  35591. properties: serializedCondition.properties
  35592. };
  35593. };
  35594. return Condition;
  35595. }());
  35596. BABYLON.Condition = Condition;
  35597. var ValueCondition = (function (_super) {
  35598. __extends(ValueCondition, _super);
  35599. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35600. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35601. var _this = _super.call(this, actionManager) || this;
  35602. _this.propertyPath = propertyPath;
  35603. _this.value = value;
  35604. _this.operator = operator;
  35605. _this._target = target;
  35606. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35607. _this._property = _this._getProperty(_this.propertyPath);
  35608. return _this;
  35609. }
  35610. Object.defineProperty(ValueCondition, "IsEqual", {
  35611. get: function () {
  35612. return ValueCondition._IsEqual;
  35613. },
  35614. enumerable: true,
  35615. configurable: true
  35616. });
  35617. Object.defineProperty(ValueCondition, "IsDifferent", {
  35618. get: function () {
  35619. return ValueCondition._IsDifferent;
  35620. },
  35621. enumerable: true,
  35622. configurable: true
  35623. });
  35624. Object.defineProperty(ValueCondition, "IsGreater", {
  35625. get: function () {
  35626. return ValueCondition._IsGreater;
  35627. },
  35628. enumerable: true,
  35629. configurable: true
  35630. });
  35631. Object.defineProperty(ValueCondition, "IsLesser", {
  35632. get: function () {
  35633. return ValueCondition._IsLesser;
  35634. },
  35635. enumerable: true,
  35636. configurable: true
  35637. });
  35638. // Methods
  35639. ValueCondition.prototype.isValid = function () {
  35640. switch (this.operator) {
  35641. case ValueCondition.IsGreater:
  35642. return this._effectiveTarget[this._property] > this.value;
  35643. case ValueCondition.IsLesser:
  35644. return this._effectiveTarget[this._property] < this.value;
  35645. case ValueCondition.IsEqual:
  35646. case ValueCondition.IsDifferent:
  35647. var check;
  35648. if (this.value.equals) {
  35649. check = this.value.equals(this._effectiveTarget[this._property]);
  35650. }
  35651. else {
  35652. check = this.value === this._effectiveTarget[this._property];
  35653. }
  35654. return this.operator === ValueCondition.IsEqual ? check : !check;
  35655. }
  35656. return false;
  35657. };
  35658. ValueCondition.prototype.serialize = function () {
  35659. return this._serialize({
  35660. name: "ValueCondition",
  35661. properties: [
  35662. BABYLON.Action._GetTargetProperty(this._target),
  35663. { name: "propertyPath", value: this.propertyPath },
  35664. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35665. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35666. ]
  35667. });
  35668. };
  35669. ValueCondition.GetOperatorName = function (operator) {
  35670. switch (operator) {
  35671. case ValueCondition._IsEqual: return "IsEqual";
  35672. case ValueCondition._IsDifferent: return "IsDifferent";
  35673. case ValueCondition._IsGreater: return "IsGreater";
  35674. case ValueCondition._IsLesser: return "IsLesser";
  35675. default: return "";
  35676. }
  35677. };
  35678. return ValueCondition;
  35679. }(Condition));
  35680. // Statics
  35681. ValueCondition._IsEqual = 0;
  35682. ValueCondition._IsDifferent = 1;
  35683. ValueCondition._IsGreater = 2;
  35684. ValueCondition._IsLesser = 3;
  35685. BABYLON.ValueCondition = ValueCondition;
  35686. var PredicateCondition = (function (_super) {
  35687. __extends(PredicateCondition, _super);
  35688. function PredicateCondition(actionManager, predicate) {
  35689. var _this = _super.call(this, actionManager) || this;
  35690. _this.predicate = predicate;
  35691. return _this;
  35692. }
  35693. PredicateCondition.prototype.isValid = function () {
  35694. return this.predicate();
  35695. };
  35696. return PredicateCondition;
  35697. }(Condition));
  35698. BABYLON.PredicateCondition = PredicateCondition;
  35699. var StateCondition = (function (_super) {
  35700. __extends(StateCondition, _super);
  35701. function StateCondition(actionManager, target, value) {
  35702. var _this = _super.call(this, actionManager) || this;
  35703. _this.value = value;
  35704. _this._target = target;
  35705. return _this;
  35706. }
  35707. // Methods
  35708. StateCondition.prototype.isValid = function () {
  35709. return this._target.state === this.value;
  35710. };
  35711. StateCondition.prototype.serialize = function () {
  35712. return this._serialize({
  35713. name: "StateCondition",
  35714. properties: [
  35715. BABYLON.Action._GetTargetProperty(this._target),
  35716. { name: "value", value: this.value }
  35717. ]
  35718. });
  35719. };
  35720. return StateCondition;
  35721. }(Condition));
  35722. BABYLON.StateCondition = StateCondition;
  35723. })(BABYLON || (BABYLON = {}));
  35724. //# sourceMappingURL=babylon.condition.js.map
  35725. var BABYLON;
  35726. (function (BABYLON) {
  35727. var Action = (function () {
  35728. function Action(triggerOptions, condition) {
  35729. this.triggerOptions = triggerOptions;
  35730. if (triggerOptions.parameter) {
  35731. this.trigger = triggerOptions.trigger;
  35732. this._triggerParameter = triggerOptions.parameter;
  35733. }
  35734. else {
  35735. this.trigger = triggerOptions;
  35736. }
  35737. this._nextActiveAction = this;
  35738. this._condition = condition;
  35739. }
  35740. // Methods
  35741. Action.prototype._prepare = function () {
  35742. };
  35743. Action.prototype.getTriggerParameter = function () {
  35744. return this._triggerParameter;
  35745. };
  35746. Action.prototype._executeCurrent = function (evt) {
  35747. if (this._nextActiveAction._condition) {
  35748. var condition = this._nextActiveAction._condition;
  35749. var currentRenderId = this._actionManager.getScene().getRenderId();
  35750. // We cache the current evaluation for the current frame
  35751. if (condition._evaluationId === currentRenderId) {
  35752. if (!condition._currentResult) {
  35753. return;
  35754. }
  35755. }
  35756. else {
  35757. condition._evaluationId = currentRenderId;
  35758. if (!condition.isValid()) {
  35759. condition._currentResult = false;
  35760. return;
  35761. }
  35762. condition._currentResult = true;
  35763. }
  35764. }
  35765. this._nextActiveAction.execute(evt);
  35766. this.skipToNextActiveAction();
  35767. };
  35768. Action.prototype.execute = function (evt) {
  35769. };
  35770. Action.prototype.skipToNextActiveAction = function () {
  35771. if (this._nextActiveAction._child) {
  35772. if (!this._nextActiveAction._child._actionManager) {
  35773. this._nextActiveAction._child._actionManager = this._actionManager;
  35774. }
  35775. this._nextActiveAction = this._nextActiveAction._child;
  35776. }
  35777. else {
  35778. this._nextActiveAction = this;
  35779. }
  35780. };
  35781. Action.prototype.then = function (action) {
  35782. this._child = action;
  35783. action._actionManager = this._actionManager;
  35784. action._prepare();
  35785. return action;
  35786. };
  35787. Action.prototype._getProperty = function (propertyPath) {
  35788. return this._actionManager._getProperty(propertyPath);
  35789. };
  35790. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35791. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35792. };
  35793. Action.prototype.serialize = function (parent) {
  35794. };
  35795. // Called by BABYLON.Action objects in serialize(...). Internal use
  35796. Action.prototype._serialize = function (serializedAction, parent) {
  35797. var serializationObject = {
  35798. type: 1,
  35799. children: [],
  35800. name: serializedAction.name,
  35801. properties: serializedAction.properties || []
  35802. };
  35803. // Serialize child
  35804. if (this._child) {
  35805. this._child.serialize(serializationObject);
  35806. }
  35807. // Check if "this" has a condition
  35808. if (this._condition) {
  35809. var serializedCondition = this._condition.serialize();
  35810. serializedCondition.children.push(serializationObject);
  35811. if (parent) {
  35812. parent.children.push(serializedCondition);
  35813. }
  35814. return serializedCondition;
  35815. }
  35816. if (parent) {
  35817. parent.children.push(serializationObject);
  35818. }
  35819. return serializationObject;
  35820. };
  35821. return Action;
  35822. }());
  35823. Action._SerializeValueAsString = function (value) {
  35824. if (typeof value === "number") {
  35825. return value.toString();
  35826. }
  35827. if (typeof value === "boolean") {
  35828. return value ? "true" : "false";
  35829. }
  35830. if (value instanceof BABYLON.Vector2) {
  35831. return value.x + ", " + value.y;
  35832. }
  35833. if (value instanceof BABYLON.Vector3) {
  35834. return value.x + ", " + value.y + ", " + value.z;
  35835. }
  35836. if (value instanceof BABYLON.Color3) {
  35837. return value.r + ", " + value.g + ", " + value.b;
  35838. }
  35839. if (value instanceof BABYLON.Color4) {
  35840. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35841. }
  35842. return value; // string
  35843. };
  35844. Action._GetTargetProperty = function (target) {
  35845. return {
  35846. name: "target",
  35847. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35848. : target instanceof BABYLON.Light ? "LightProperties"
  35849. : target instanceof BABYLON.Camera ? "CameraProperties"
  35850. : "SceneProperties",
  35851. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35852. };
  35853. };
  35854. BABYLON.Action = Action;
  35855. })(BABYLON || (BABYLON = {}));
  35856. //# sourceMappingURL=babylon.action.js.map
  35857. var BABYLON;
  35858. (function (BABYLON) {
  35859. /**
  35860. * ActionEvent is the event beint sent when an action is triggered.
  35861. */
  35862. var ActionEvent = (function () {
  35863. /**
  35864. * @constructor
  35865. * @param source The mesh or sprite that triggered the action.
  35866. * @param pointerX The X mouse cursor position at the time of the event
  35867. * @param pointerY The Y mouse cursor position at the time of the event
  35868. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35869. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35870. */
  35871. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35872. this.source = source;
  35873. this.pointerX = pointerX;
  35874. this.pointerY = pointerY;
  35875. this.meshUnderPointer = meshUnderPointer;
  35876. this.sourceEvent = sourceEvent;
  35877. this.additionalData = additionalData;
  35878. }
  35879. /**
  35880. * Helper function to auto-create an ActionEvent from a source mesh.
  35881. * @param source The source mesh that triggered the event
  35882. * @param evt {Event} The original (browser) event
  35883. */
  35884. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35885. var scene = source.getScene();
  35886. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35887. };
  35888. /**
  35889. * Helper function to auto-create an ActionEvent from a source mesh.
  35890. * @param source The source sprite that triggered the event
  35891. * @param scene Scene associated with the sprite
  35892. * @param evt {Event} The original (browser) event
  35893. */
  35894. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35895. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35896. };
  35897. /**
  35898. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35899. * @param scene the scene where the event occurred
  35900. * @param evt {Event} The original (browser) event
  35901. */
  35902. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35903. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35904. };
  35905. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35906. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35907. };
  35908. return ActionEvent;
  35909. }());
  35910. BABYLON.ActionEvent = ActionEvent;
  35911. /**
  35912. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35913. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35914. */
  35915. var ActionManager = (function () {
  35916. function ActionManager(scene) {
  35917. // Members
  35918. this.actions = new Array();
  35919. this.hoverCursor = '';
  35920. this._scene = scene;
  35921. scene._actionManagers.push(this);
  35922. }
  35923. Object.defineProperty(ActionManager, "NothingTrigger", {
  35924. get: function () {
  35925. return ActionManager._NothingTrigger;
  35926. },
  35927. enumerable: true,
  35928. configurable: true
  35929. });
  35930. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35931. get: function () {
  35932. return ActionManager._OnPickTrigger;
  35933. },
  35934. enumerable: true,
  35935. configurable: true
  35936. });
  35937. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35938. get: function () {
  35939. return ActionManager._OnLeftPickTrigger;
  35940. },
  35941. enumerable: true,
  35942. configurable: true
  35943. });
  35944. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35945. get: function () {
  35946. return ActionManager._OnRightPickTrigger;
  35947. },
  35948. enumerable: true,
  35949. configurable: true
  35950. });
  35951. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35952. get: function () {
  35953. return ActionManager._OnCenterPickTrigger;
  35954. },
  35955. enumerable: true,
  35956. configurable: true
  35957. });
  35958. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35959. get: function () {
  35960. return ActionManager._OnPickDownTrigger;
  35961. },
  35962. enumerable: true,
  35963. configurable: true
  35964. });
  35965. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  35966. get: function () {
  35967. return ActionManager._OnDoublePickTrigger;
  35968. },
  35969. enumerable: true,
  35970. configurable: true
  35971. });
  35972. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35973. get: function () {
  35974. return ActionManager._OnPickUpTrigger;
  35975. },
  35976. enumerable: true,
  35977. configurable: true
  35978. });
  35979. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35980. /// This trigger will only be raised if you also declared a OnPickDown
  35981. get: function () {
  35982. return ActionManager._OnPickOutTrigger;
  35983. },
  35984. enumerable: true,
  35985. configurable: true
  35986. });
  35987. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35988. get: function () {
  35989. return ActionManager._OnLongPressTrigger;
  35990. },
  35991. enumerable: true,
  35992. configurable: true
  35993. });
  35994. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35995. get: function () {
  35996. return ActionManager._OnPointerOverTrigger;
  35997. },
  35998. enumerable: true,
  35999. configurable: true
  36000. });
  36001. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36002. get: function () {
  36003. return ActionManager._OnPointerOutTrigger;
  36004. },
  36005. enumerable: true,
  36006. configurable: true
  36007. });
  36008. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36009. get: function () {
  36010. return ActionManager._OnEveryFrameTrigger;
  36011. },
  36012. enumerable: true,
  36013. configurable: true
  36014. });
  36015. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36016. get: function () {
  36017. return ActionManager._OnIntersectionEnterTrigger;
  36018. },
  36019. enumerable: true,
  36020. configurable: true
  36021. });
  36022. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36023. get: function () {
  36024. return ActionManager._OnIntersectionExitTrigger;
  36025. },
  36026. enumerable: true,
  36027. configurable: true
  36028. });
  36029. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36030. get: function () {
  36031. return ActionManager._OnKeyDownTrigger;
  36032. },
  36033. enumerable: true,
  36034. configurable: true
  36035. });
  36036. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36037. get: function () {
  36038. return ActionManager._OnKeyUpTrigger;
  36039. },
  36040. enumerable: true,
  36041. configurable: true
  36042. });
  36043. // Methods
  36044. ActionManager.prototype.dispose = function () {
  36045. var index = this._scene._actionManagers.indexOf(this);
  36046. for (var i = 0; i < this.actions.length; i++) {
  36047. var action = this.actions[i];
  36048. ActionManager.Triggers[action.trigger]--;
  36049. if (ActionManager.Triggers[action.trigger] === 0) {
  36050. delete ActionManager.Triggers[action.trigger];
  36051. }
  36052. }
  36053. if (index > -1) {
  36054. this._scene._actionManagers.splice(index, 1);
  36055. }
  36056. };
  36057. ActionManager.prototype.getScene = function () {
  36058. return this._scene;
  36059. };
  36060. /**
  36061. * Does this action manager handles actions of any of the given triggers
  36062. * @param {number[]} triggers - the triggers to be tested
  36063. * @return {boolean} whether one (or more) of the triggers is handeled
  36064. */
  36065. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36066. for (var index = 0; index < this.actions.length; index++) {
  36067. var action = this.actions[index];
  36068. if (triggers.indexOf(action.trigger) > -1) {
  36069. return true;
  36070. }
  36071. }
  36072. return false;
  36073. };
  36074. /**
  36075. * Does this action manager handles actions of a given trigger
  36076. * @param {number} trigger - the trigger to be tested
  36077. * @return {boolean} whether the trigger is handeled
  36078. */
  36079. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36080. for (var index = 0; index < this.actions.length; index++) {
  36081. var action = this.actions[index];
  36082. if (action.trigger === trigger) {
  36083. return true;
  36084. }
  36085. }
  36086. return false;
  36087. };
  36088. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36089. /**
  36090. * Does this action manager has pointer triggers
  36091. * @return {boolean} whether or not it has pointer triggers
  36092. */
  36093. get: function () {
  36094. for (var index = 0; index < this.actions.length; index++) {
  36095. var action = this.actions[index];
  36096. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36097. return true;
  36098. }
  36099. }
  36100. return false;
  36101. },
  36102. enumerable: true,
  36103. configurable: true
  36104. });
  36105. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36106. /**
  36107. * Does this action manager has pick triggers
  36108. * @return {boolean} whether or not it has pick triggers
  36109. */
  36110. get: function () {
  36111. for (var index = 0; index < this.actions.length; index++) {
  36112. var action = this.actions[index];
  36113. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36114. return true;
  36115. }
  36116. }
  36117. return false;
  36118. },
  36119. enumerable: true,
  36120. configurable: true
  36121. });
  36122. Object.defineProperty(ActionManager, "HasTriggers", {
  36123. /**
  36124. * Does exist one action manager with at least one trigger
  36125. * @return {boolean} whether or not it exists one action manager with one trigger
  36126. **/
  36127. get: function () {
  36128. for (var t in ActionManager.Triggers) {
  36129. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36130. return true;
  36131. }
  36132. }
  36133. return false;
  36134. },
  36135. enumerable: true,
  36136. configurable: true
  36137. });
  36138. Object.defineProperty(ActionManager, "HasPickTriggers", {
  36139. /**
  36140. * Does exist one action manager with at least one pick trigger
  36141. * @return {boolean} whether or not it exists one action manager with one pick trigger
  36142. **/
  36143. get: function () {
  36144. for (var t in ActionManager.Triggers) {
  36145. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36146. var t_int = parseInt(t);
  36147. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  36148. return true;
  36149. }
  36150. }
  36151. }
  36152. return false;
  36153. },
  36154. enumerable: true,
  36155. configurable: true
  36156. });
  36157. /**
  36158. * Does exist one action manager that handles actions of a given trigger
  36159. * @param {number} trigger - the trigger to be tested
  36160. * @return {boolean} whether the trigger is handeled by at least one action manager
  36161. **/
  36162. ActionManager.HasSpecificTrigger = function (trigger) {
  36163. for (var t in ActionManager.Triggers) {
  36164. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36165. var t_int = parseInt(t);
  36166. if (t_int === trigger) {
  36167. return true;
  36168. }
  36169. }
  36170. }
  36171. return false;
  36172. };
  36173. /**
  36174. * Registers an action to this action manager
  36175. * @param {BABYLON.Action} action - the action to be registered
  36176. * @return {BABYLON.Action} the action amended (prepared) after registration
  36177. */
  36178. ActionManager.prototype.registerAction = function (action) {
  36179. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36180. if (this.getScene().actionManager !== this) {
  36181. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36182. return null;
  36183. }
  36184. }
  36185. this.actions.push(action);
  36186. if (ActionManager.Triggers[action.trigger]) {
  36187. ActionManager.Triggers[action.trigger]++;
  36188. }
  36189. else {
  36190. ActionManager.Triggers[action.trigger] = 1;
  36191. }
  36192. action._actionManager = this;
  36193. action._prepare();
  36194. return action;
  36195. };
  36196. /**
  36197. * Process a specific trigger
  36198. * @param {number} trigger - the trigger to process
  36199. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36200. */
  36201. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36202. for (var index = 0; index < this.actions.length; index++) {
  36203. var action = this.actions[index];
  36204. if (action.trigger === trigger) {
  36205. if (trigger === ActionManager.OnKeyUpTrigger
  36206. || trigger === ActionManager.OnKeyDownTrigger) {
  36207. var parameter = action.getTriggerParameter();
  36208. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  36209. if (!parameter.toLowerCase) {
  36210. continue;
  36211. }
  36212. var lowerCase = parameter.toLowerCase();
  36213. if (lowerCase !== evt.sourceEvent.key) {
  36214. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  36215. var actualkey = String.fromCharCode(unicode).toLowerCase();
  36216. if (actualkey !== lowerCase) {
  36217. continue;
  36218. }
  36219. }
  36220. }
  36221. }
  36222. action._executeCurrent(evt);
  36223. }
  36224. }
  36225. };
  36226. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  36227. var properties = propertyPath.split(".");
  36228. for (var index = 0; index < properties.length - 1; index++) {
  36229. target = target[properties[index]];
  36230. }
  36231. return target;
  36232. };
  36233. ActionManager.prototype._getProperty = function (propertyPath) {
  36234. var properties = propertyPath.split(".");
  36235. return properties[properties.length - 1];
  36236. };
  36237. ActionManager.prototype.serialize = function (name) {
  36238. var root = {
  36239. children: [],
  36240. name: name,
  36241. type: 3,
  36242. properties: [] // Empty for root but required
  36243. };
  36244. for (var i = 0; i < this.actions.length; i++) {
  36245. var triggerObject = {
  36246. type: 0,
  36247. children: [],
  36248. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  36249. properties: []
  36250. };
  36251. var triggerOptions = this.actions[i].triggerOptions;
  36252. if (triggerOptions && typeof triggerOptions !== "number") {
  36253. if (triggerOptions.parameter instanceof BABYLON.Node) {
  36254. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  36255. }
  36256. else {
  36257. var parameter = {};
  36258. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  36259. if (triggerOptions.parameter.mesh) {
  36260. parameter._meshId = triggerOptions.parameter.mesh.id;
  36261. }
  36262. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  36263. }
  36264. }
  36265. // Serialize child action, recursively
  36266. this.actions[i].serialize(triggerObject);
  36267. // Add serialized trigger
  36268. root.children.push(triggerObject);
  36269. }
  36270. return root;
  36271. };
  36272. ActionManager.Parse = function (parsedActions, object, scene) {
  36273. var actionManager = new BABYLON.ActionManager(scene);
  36274. if (object === null)
  36275. scene.actionManager = actionManager;
  36276. else
  36277. object.actionManager = actionManager;
  36278. // instanciate a new object
  36279. var instanciate = function (name, params) {
  36280. var newInstance = Object.create(BABYLON[name].prototype);
  36281. newInstance.constructor.apply(newInstance, params);
  36282. return newInstance;
  36283. };
  36284. var parseParameter = function (name, value, target, propertyPath) {
  36285. if (propertyPath === null) {
  36286. // String, boolean or float
  36287. var floatValue = parseFloat(value);
  36288. if (value === "true" || value === "false")
  36289. return value === "true";
  36290. else
  36291. return isNaN(floatValue) ? value : floatValue;
  36292. }
  36293. var effectiveTarget = propertyPath.split(".");
  36294. var values = value.split(",");
  36295. // Get effective Target
  36296. for (var i = 0; i < effectiveTarget.length; i++) {
  36297. target = target[effectiveTarget[i]];
  36298. }
  36299. // Return appropriate value with its type
  36300. if (typeof (target) === "boolean")
  36301. return values[0] === "true";
  36302. if (typeof (target) === "string")
  36303. return values[0];
  36304. // Parameters with multiple values such as Vector3 etc.
  36305. var split = new Array();
  36306. for (var i = 0; i < values.length; i++)
  36307. split.push(parseFloat(values[i]));
  36308. if (target instanceof BABYLON.Vector3)
  36309. return BABYLON.Vector3.FromArray(split);
  36310. if (target instanceof BABYLON.Vector4)
  36311. return BABYLON.Vector4.FromArray(split);
  36312. if (target instanceof BABYLON.Color3)
  36313. return BABYLON.Color3.FromArray(split);
  36314. if (target instanceof BABYLON.Color4)
  36315. return BABYLON.Color4.FromArray(split);
  36316. return parseFloat(values[0]);
  36317. };
  36318. // traverse graph per trigger
  36319. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  36320. if (combineArray === void 0) { combineArray = null; }
  36321. if (parsedAction.detached)
  36322. return;
  36323. var parameters = new Array();
  36324. var target = null;
  36325. var propertyPath = null;
  36326. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  36327. // Parameters
  36328. if (parsedAction.type === 2)
  36329. parameters.push(actionManager);
  36330. else
  36331. parameters.push(trigger);
  36332. if (combine) {
  36333. var actions = new Array();
  36334. for (var j = 0; j < parsedAction.combine.length; j++) {
  36335. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  36336. }
  36337. parameters.push(actions);
  36338. }
  36339. else {
  36340. for (var i = 0; i < parsedAction.properties.length; i++) {
  36341. var value = parsedAction.properties[i].value;
  36342. var name = parsedAction.properties[i].name;
  36343. var targetType = parsedAction.properties[i].targetType;
  36344. if (name === "target")
  36345. if (targetType !== null && targetType === "SceneProperties")
  36346. value = target = scene;
  36347. else
  36348. value = target = scene.getNodeByName(value);
  36349. else if (name === "parent")
  36350. value = scene.getNodeByName(value);
  36351. else if (name === "sound")
  36352. value = scene.getSoundByName(value);
  36353. else if (name !== "propertyPath") {
  36354. if (parsedAction.type === 2 && name === "operator")
  36355. value = BABYLON.ValueCondition[value];
  36356. else
  36357. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  36358. }
  36359. else {
  36360. propertyPath = value;
  36361. }
  36362. parameters.push(value);
  36363. }
  36364. }
  36365. if (combineArray === null) {
  36366. parameters.push(condition);
  36367. }
  36368. else {
  36369. parameters.push(null);
  36370. }
  36371. // If interpolate value action
  36372. if (parsedAction.name === "InterpolateValueAction") {
  36373. var param = parameters[parameters.length - 2];
  36374. parameters[parameters.length - 1] = param;
  36375. parameters[parameters.length - 2] = condition;
  36376. }
  36377. // Action or condition(s) and not CombineAction
  36378. var newAction = instanciate(parsedAction.name, parameters);
  36379. if (newAction instanceof BABYLON.Condition && condition !== null) {
  36380. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  36381. if (action)
  36382. action.then(nothing);
  36383. else
  36384. actionManager.registerAction(nothing);
  36385. action = nothing;
  36386. }
  36387. if (combineArray === null) {
  36388. if (newAction instanceof BABYLON.Condition) {
  36389. condition = newAction;
  36390. newAction = action;
  36391. }
  36392. else {
  36393. condition = null;
  36394. if (action)
  36395. action.then(newAction);
  36396. else
  36397. actionManager.registerAction(newAction);
  36398. }
  36399. }
  36400. else {
  36401. combineArray.push(newAction);
  36402. }
  36403. for (var i = 0; i < parsedAction.children.length; i++)
  36404. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  36405. };
  36406. // triggers
  36407. for (var i = 0; i < parsedActions.children.length; i++) {
  36408. var triggerParams;
  36409. var trigger = parsedActions.children[i];
  36410. if (trigger.properties.length > 0) {
  36411. var param = trigger.properties[0].value;
  36412. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  36413. if (value._meshId) {
  36414. value.mesh = scene.getMeshByID(value._meshId);
  36415. }
  36416. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  36417. }
  36418. else
  36419. triggerParams = BABYLON.ActionManager[trigger.name];
  36420. for (var j = 0; j < trigger.children.length; j++) {
  36421. if (!trigger.detached)
  36422. traverse(trigger.children[j], triggerParams, null, null);
  36423. }
  36424. }
  36425. };
  36426. ActionManager.GetTriggerName = function (trigger) {
  36427. switch (trigger) {
  36428. case 0: return "NothingTrigger";
  36429. case 1: return "OnPickTrigger";
  36430. case 2: return "OnLeftPickTrigger";
  36431. case 3: return "OnRightPickTrigger";
  36432. case 4: return "OnCenterPickTrigger";
  36433. case 5: return "OnPickDownTrigger";
  36434. case 6: return "OnPickUpTrigger";
  36435. case 7: return "OnLongPressTrigger";
  36436. case 8: return "OnPointerOverTrigger";
  36437. case 9: return "OnPointerOutTrigger";
  36438. case 10: return "OnEveryFrameTrigger";
  36439. case 11: return "OnIntersectionEnterTrigger";
  36440. case 12: return "OnIntersectionExitTrigger";
  36441. case 13: return "OnKeyDownTrigger";
  36442. case 14: return "OnKeyUpTrigger";
  36443. case 15: return "OnPickOutTrigger";
  36444. default: return "";
  36445. }
  36446. };
  36447. return ActionManager;
  36448. }());
  36449. // Statics
  36450. ActionManager._NothingTrigger = 0;
  36451. ActionManager._OnPickTrigger = 1;
  36452. ActionManager._OnLeftPickTrigger = 2;
  36453. ActionManager._OnRightPickTrigger = 3;
  36454. ActionManager._OnCenterPickTrigger = 4;
  36455. ActionManager._OnPickDownTrigger = 5;
  36456. ActionManager._OnDoublePickTrigger = 6;
  36457. ActionManager._OnPickUpTrigger = 7;
  36458. ActionManager._OnLongPressTrigger = 8;
  36459. ActionManager._OnPointerOverTrigger = 9;
  36460. ActionManager._OnPointerOutTrigger = 10;
  36461. ActionManager._OnEveryFrameTrigger = 11;
  36462. ActionManager._OnIntersectionEnterTrigger = 12;
  36463. ActionManager._OnIntersectionExitTrigger = 13;
  36464. ActionManager._OnKeyDownTrigger = 14;
  36465. ActionManager._OnKeyUpTrigger = 15;
  36466. ActionManager._OnPickOutTrigger = 16;
  36467. ActionManager.Triggers = {};
  36468. BABYLON.ActionManager = ActionManager;
  36469. })(BABYLON || (BABYLON = {}));
  36470. //# sourceMappingURL=babylon.actionManager.js.map
  36471. var BABYLON;
  36472. (function (BABYLON) {
  36473. var InterpolateValueAction = (function (_super) {
  36474. __extends(InterpolateValueAction, _super);
  36475. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  36476. if (duration === void 0) { duration = 1000; }
  36477. var _this = _super.call(this, triggerOptions, condition) || this;
  36478. _this.propertyPath = propertyPath;
  36479. _this.value = value;
  36480. _this.duration = duration;
  36481. _this.stopOtherAnimations = stopOtherAnimations;
  36482. _this.onInterpolationDone = onInterpolationDone;
  36483. _this._target = _this._effectiveTarget = target;
  36484. return _this;
  36485. }
  36486. InterpolateValueAction.prototype._prepare = function () {
  36487. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36488. this._property = this._getProperty(this.propertyPath);
  36489. };
  36490. InterpolateValueAction.prototype.execute = function () {
  36491. var scene = this._actionManager.getScene();
  36492. var keys = [
  36493. {
  36494. frame: 0,
  36495. value: this._effectiveTarget[this._property]
  36496. }, {
  36497. frame: 100,
  36498. value: this.value
  36499. }
  36500. ];
  36501. var dataType;
  36502. if (typeof this.value === "number") {
  36503. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  36504. }
  36505. else if (this.value instanceof BABYLON.Color3) {
  36506. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  36507. }
  36508. else if (this.value instanceof BABYLON.Vector3) {
  36509. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  36510. }
  36511. else if (this.value instanceof BABYLON.Matrix) {
  36512. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  36513. }
  36514. else if (this.value instanceof BABYLON.Quaternion) {
  36515. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  36516. }
  36517. else {
  36518. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  36519. return;
  36520. }
  36521. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36522. animation.setKeys(keys);
  36523. if (this.stopOtherAnimations) {
  36524. scene.stopAnimation(this._effectiveTarget);
  36525. }
  36526. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  36527. };
  36528. InterpolateValueAction.prototype.serialize = function (parent) {
  36529. return _super.prototype._serialize.call(this, {
  36530. name: "InterpolateValueAction",
  36531. properties: [
  36532. BABYLON.Action._GetTargetProperty(this._target),
  36533. { name: "propertyPath", value: this.propertyPath },
  36534. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36535. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  36536. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  36537. ]
  36538. }, parent);
  36539. };
  36540. return InterpolateValueAction;
  36541. }(BABYLON.Action));
  36542. BABYLON.InterpolateValueAction = InterpolateValueAction;
  36543. })(BABYLON || (BABYLON = {}));
  36544. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  36545. var BABYLON;
  36546. (function (BABYLON) {
  36547. var SwitchBooleanAction = (function (_super) {
  36548. __extends(SwitchBooleanAction, _super);
  36549. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  36550. var _this = _super.call(this, triggerOptions, condition) || this;
  36551. _this.propertyPath = propertyPath;
  36552. _this._target = _this._effectiveTarget = target;
  36553. return _this;
  36554. }
  36555. SwitchBooleanAction.prototype._prepare = function () {
  36556. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36557. this._property = this._getProperty(this.propertyPath);
  36558. };
  36559. SwitchBooleanAction.prototype.execute = function () {
  36560. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  36561. };
  36562. SwitchBooleanAction.prototype.serialize = function (parent) {
  36563. return _super.prototype._serialize.call(this, {
  36564. name: "SwitchBooleanAction",
  36565. properties: [
  36566. BABYLON.Action._GetTargetProperty(this._target),
  36567. { name: "propertyPath", value: this.propertyPath }
  36568. ]
  36569. }, parent);
  36570. };
  36571. return SwitchBooleanAction;
  36572. }(BABYLON.Action));
  36573. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  36574. var SetStateAction = (function (_super) {
  36575. __extends(SetStateAction, _super);
  36576. function SetStateAction(triggerOptions, target, value, condition) {
  36577. var _this = _super.call(this, triggerOptions, condition) || this;
  36578. _this.value = value;
  36579. _this._target = target;
  36580. return _this;
  36581. }
  36582. SetStateAction.prototype.execute = function () {
  36583. this._target.state = this.value;
  36584. };
  36585. SetStateAction.prototype.serialize = function (parent) {
  36586. return _super.prototype._serialize.call(this, {
  36587. name: "SetStateAction",
  36588. properties: [
  36589. BABYLON.Action._GetTargetProperty(this._target),
  36590. { name: "value", value: this.value }
  36591. ]
  36592. }, parent);
  36593. };
  36594. return SetStateAction;
  36595. }(BABYLON.Action));
  36596. BABYLON.SetStateAction = SetStateAction;
  36597. var SetValueAction = (function (_super) {
  36598. __extends(SetValueAction, _super);
  36599. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  36600. var _this = _super.call(this, triggerOptions, condition) || this;
  36601. _this.propertyPath = propertyPath;
  36602. _this.value = value;
  36603. _this._target = _this._effectiveTarget = target;
  36604. return _this;
  36605. }
  36606. SetValueAction.prototype._prepare = function () {
  36607. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36608. this._property = this._getProperty(this.propertyPath);
  36609. };
  36610. SetValueAction.prototype.execute = function () {
  36611. this._effectiveTarget[this._property] = this.value;
  36612. if (this._target.markAsDirty) {
  36613. this._target.markAsDirty(this._property);
  36614. }
  36615. };
  36616. SetValueAction.prototype.serialize = function (parent) {
  36617. return _super.prototype._serialize.call(this, {
  36618. name: "SetValueAction",
  36619. properties: [
  36620. BABYLON.Action._GetTargetProperty(this._target),
  36621. { name: "propertyPath", value: this.propertyPath },
  36622. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36623. ]
  36624. }, parent);
  36625. };
  36626. return SetValueAction;
  36627. }(BABYLON.Action));
  36628. BABYLON.SetValueAction = SetValueAction;
  36629. var IncrementValueAction = (function (_super) {
  36630. __extends(IncrementValueAction, _super);
  36631. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36632. var _this = _super.call(this, triggerOptions, condition) || this;
  36633. _this.propertyPath = propertyPath;
  36634. _this.value = value;
  36635. _this._target = _this._effectiveTarget = target;
  36636. return _this;
  36637. }
  36638. IncrementValueAction.prototype._prepare = function () {
  36639. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36640. this._property = this._getProperty(this.propertyPath);
  36641. if (typeof this._effectiveTarget[this._property] !== "number") {
  36642. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36643. }
  36644. };
  36645. IncrementValueAction.prototype.execute = function () {
  36646. this._effectiveTarget[this._property] += this.value;
  36647. if (this._target.markAsDirty) {
  36648. this._target.markAsDirty(this._property);
  36649. }
  36650. };
  36651. IncrementValueAction.prototype.serialize = function (parent) {
  36652. return _super.prototype._serialize.call(this, {
  36653. name: "IncrementValueAction",
  36654. properties: [
  36655. BABYLON.Action._GetTargetProperty(this._target),
  36656. { name: "propertyPath", value: this.propertyPath },
  36657. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36658. ]
  36659. }, parent);
  36660. };
  36661. return IncrementValueAction;
  36662. }(BABYLON.Action));
  36663. BABYLON.IncrementValueAction = IncrementValueAction;
  36664. var PlayAnimationAction = (function (_super) {
  36665. __extends(PlayAnimationAction, _super);
  36666. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36667. var _this = _super.call(this, triggerOptions, condition) || this;
  36668. _this.from = from;
  36669. _this.to = to;
  36670. _this.loop = loop;
  36671. _this._target = target;
  36672. return _this;
  36673. }
  36674. PlayAnimationAction.prototype._prepare = function () {
  36675. };
  36676. PlayAnimationAction.prototype.execute = function () {
  36677. var scene = this._actionManager.getScene();
  36678. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36679. };
  36680. PlayAnimationAction.prototype.serialize = function (parent) {
  36681. return _super.prototype._serialize.call(this, {
  36682. name: "PlayAnimationAction",
  36683. properties: [
  36684. BABYLON.Action._GetTargetProperty(this._target),
  36685. { name: "from", value: String(this.from) },
  36686. { name: "to", value: String(this.to) },
  36687. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36688. ]
  36689. }, parent);
  36690. };
  36691. return PlayAnimationAction;
  36692. }(BABYLON.Action));
  36693. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36694. var StopAnimationAction = (function (_super) {
  36695. __extends(StopAnimationAction, _super);
  36696. function StopAnimationAction(triggerOptions, target, condition) {
  36697. var _this = _super.call(this, triggerOptions, condition) || this;
  36698. _this._target = target;
  36699. return _this;
  36700. }
  36701. StopAnimationAction.prototype._prepare = function () {
  36702. };
  36703. StopAnimationAction.prototype.execute = function () {
  36704. var scene = this._actionManager.getScene();
  36705. scene.stopAnimation(this._target);
  36706. };
  36707. StopAnimationAction.prototype.serialize = function (parent) {
  36708. return _super.prototype._serialize.call(this, {
  36709. name: "StopAnimationAction",
  36710. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36711. }, parent);
  36712. };
  36713. return StopAnimationAction;
  36714. }(BABYLON.Action));
  36715. BABYLON.StopAnimationAction = StopAnimationAction;
  36716. var DoNothingAction = (function (_super) {
  36717. __extends(DoNothingAction, _super);
  36718. function DoNothingAction(triggerOptions, condition) {
  36719. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36720. return _super.call(this, triggerOptions, condition) || this;
  36721. }
  36722. DoNothingAction.prototype.execute = function () {
  36723. };
  36724. DoNothingAction.prototype.serialize = function (parent) {
  36725. return _super.prototype._serialize.call(this, {
  36726. name: "DoNothingAction",
  36727. properties: []
  36728. }, parent);
  36729. };
  36730. return DoNothingAction;
  36731. }(BABYLON.Action));
  36732. BABYLON.DoNothingAction = DoNothingAction;
  36733. var CombineAction = (function (_super) {
  36734. __extends(CombineAction, _super);
  36735. function CombineAction(triggerOptions, children, condition) {
  36736. var _this = _super.call(this, triggerOptions, condition) || this;
  36737. _this.children = children;
  36738. return _this;
  36739. }
  36740. CombineAction.prototype._prepare = function () {
  36741. for (var index = 0; index < this.children.length; index++) {
  36742. this.children[index]._actionManager = this._actionManager;
  36743. this.children[index]._prepare();
  36744. }
  36745. };
  36746. CombineAction.prototype.execute = function (evt) {
  36747. for (var index = 0; index < this.children.length; index++) {
  36748. this.children[index].execute(evt);
  36749. }
  36750. };
  36751. CombineAction.prototype.serialize = function (parent) {
  36752. var serializationObject = _super.prototype._serialize.call(this, {
  36753. name: "CombineAction",
  36754. properties: [],
  36755. combine: []
  36756. }, parent);
  36757. for (var i = 0; i < this.children.length; i++) {
  36758. serializationObject.combine.push(this.children[i].serialize(null));
  36759. }
  36760. return serializationObject;
  36761. };
  36762. return CombineAction;
  36763. }(BABYLON.Action));
  36764. BABYLON.CombineAction = CombineAction;
  36765. var ExecuteCodeAction = (function (_super) {
  36766. __extends(ExecuteCodeAction, _super);
  36767. function ExecuteCodeAction(triggerOptions, func, condition) {
  36768. var _this = _super.call(this, triggerOptions, condition) || this;
  36769. _this.func = func;
  36770. return _this;
  36771. }
  36772. ExecuteCodeAction.prototype.execute = function (evt) {
  36773. this.func(evt);
  36774. };
  36775. return ExecuteCodeAction;
  36776. }(BABYLON.Action));
  36777. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36778. var SetParentAction = (function (_super) {
  36779. __extends(SetParentAction, _super);
  36780. function SetParentAction(triggerOptions, target, parent, condition) {
  36781. var _this = _super.call(this, triggerOptions, condition) || this;
  36782. _this._target = target;
  36783. _this._parent = parent;
  36784. return _this;
  36785. }
  36786. SetParentAction.prototype._prepare = function () {
  36787. };
  36788. SetParentAction.prototype.execute = function () {
  36789. if (this._target.parent === this._parent) {
  36790. return;
  36791. }
  36792. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36793. invertParentWorldMatrix.invert();
  36794. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36795. this._target.parent = this._parent;
  36796. };
  36797. SetParentAction.prototype.serialize = function (parent) {
  36798. return _super.prototype._serialize.call(this, {
  36799. name: "SetParentAction",
  36800. properties: [
  36801. BABYLON.Action._GetTargetProperty(this._target),
  36802. BABYLON.Action._GetTargetProperty(this._parent),
  36803. ]
  36804. }, parent);
  36805. };
  36806. return SetParentAction;
  36807. }(BABYLON.Action));
  36808. BABYLON.SetParentAction = SetParentAction;
  36809. var PlaySoundAction = (function (_super) {
  36810. __extends(PlaySoundAction, _super);
  36811. function PlaySoundAction(triggerOptions, sound, condition) {
  36812. var _this = _super.call(this, triggerOptions, condition) || this;
  36813. _this._sound = sound;
  36814. return _this;
  36815. }
  36816. PlaySoundAction.prototype._prepare = function () {
  36817. };
  36818. PlaySoundAction.prototype.execute = function () {
  36819. if (this._sound !== undefined)
  36820. this._sound.play();
  36821. };
  36822. PlaySoundAction.prototype.serialize = function (parent) {
  36823. return _super.prototype._serialize.call(this, {
  36824. name: "PlaySoundAction",
  36825. properties: [{ name: "sound", value: this._sound.name }]
  36826. }, parent);
  36827. };
  36828. return PlaySoundAction;
  36829. }(BABYLON.Action));
  36830. BABYLON.PlaySoundAction = PlaySoundAction;
  36831. var StopSoundAction = (function (_super) {
  36832. __extends(StopSoundAction, _super);
  36833. function StopSoundAction(triggerOptions, sound, condition) {
  36834. var _this = _super.call(this, triggerOptions, condition) || this;
  36835. _this._sound = sound;
  36836. return _this;
  36837. }
  36838. StopSoundAction.prototype._prepare = function () {
  36839. };
  36840. StopSoundAction.prototype.execute = function () {
  36841. if (this._sound !== undefined)
  36842. this._sound.stop();
  36843. };
  36844. StopSoundAction.prototype.serialize = function (parent) {
  36845. return _super.prototype._serialize.call(this, {
  36846. name: "StopSoundAction",
  36847. properties: [{ name: "sound", value: this._sound.name }]
  36848. }, parent);
  36849. };
  36850. return StopSoundAction;
  36851. }(BABYLON.Action));
  36852. BABYLON.StopSoundAction = StopSoundAction;
  36853. })(BABYLON || (BABYLON = {}));
  36854. //# sourceMappingURL=babylon.directActions.js.map
  36855. var BABYLON;
  36856. (function (BABYLON) {
  36857. var SpriteManager = (function () {
  36858. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  36859. if (epsilon === void 0) { epsilon = 0.01; }
  36860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36861. this.name = name;
  36862. this.sprites = new Array();
  36863. this.renderingGroupId = 0;
  36864. this.layerMask = 0x0FFFFFFF;
  36865. this.fogEnabled = true;
  36866. this.isPickable = false;
  36867. /**
  36868. * An event triggered when the manager is disposed.
  36869. * @type {BABYLON.Observable}
  36870. */
  36871. this.onDisposeObservable = new BABYLON.Observable();
  36872. this._vertexBuffers = {};
  36873. this._capacity = capacity;
  36874. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  36875. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36876. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36877. if (cellSize.width && cellSize.height) {
  36878. this.cellWidth = cellSize.width;
  36879. this.cellHeight = cellSize.height;
  36880. }
  36881. else if (cellSize !== undefined) {
  36882. this.cellWidth = cellSize;
  36883. this.cellHeight = cellSize;
  36884. }
  36885. else {
  36886. return;
  36887. }
  36888. this._epsilon = epsilon;
  36889. this._scene = scene;
  36890. this._scene.spriteManagers.push(this);
  36891. var indices = [];
  36892. var index = 0;
  36893. for (var count = 0; count < capacity; count++) {
  36894. indices.push(index);
  36895. indices.push(index + 1);
  36896. indices.push(index + 2);
  36897. indices.push(index);
  36898. indices.push(index + 2);
  36899. indices.push(index + 3);
  36900. index += 4;
  36901. }
  36902. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36903. // VBO
  36904. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  36905. this._vertexData = new Float32Array(capacity * 16 * 4);
  36906. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  36907. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  36908. var options = this._buffer.createVertexBuffer("options", 4, 4);
  36909. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  36910. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  36911. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36912. this._vertexBuffers["options"] = options;
  36913. this._vertexBuffers["cellInfo"] = cellInfo;
  36914. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36915. // Effects
  36916. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  36917. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  36918. }
  36919. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  36920. set: function (callback) {
  36921. if (this._onDisposeObserver) {
  36922. this.onDisposeObservable.remove(this._onDisposeObserver);
  36923. }
  36924. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36925. },
  36926. enumerable: true,
  36927. configurable: true
  36928. });
  36929. Object.defineProperty(SpriteManager.prototype, "texture", {
  36930. get: function () {
  36931. return this._spriteTexture;
  36932. },
  36933. set: function (value) {
  36934. this._spriteTexture = value;
  36935. },
  36936. enumerable: true,
  36937. configurable: true
  36938. });
  36939. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  36940. var arrayOffset = index * 16;
  36941. if (offsetX === 0)
  36942. offsetX = this._epsilon;
  36943. else if (offsetX === 1)
  36944. offsetX = 1 - this._epsilon;
  36945. if (offsetY === 0)
  36946. offsetY = this._epsilon;
  36947. else if (offsetY === 1)
  36948. offsetY = 1 - this._epsilon;
  36949. this._vertexData[arrayOffset] = sprite.position.x;
  36950. this._vertexData[arrayOffset + 1] = sprite.position.y;
  36951. this._vertexData[arrayOffset + 2] = sprite.position.z;
  36952. this._vertexData[arrayOffset + 3] = sprite.angle;
  36953. this._vertexData[arrayOffset + 4] = sprite.width;
  36954. this._vertexData[arrayOffset + 5] = sprite.height;
  36955. this._vertexData[arrayOffset + 6] = offsetX;
  36956. this._vertexData[arrayOffset + 7] = offsetY;
  36957. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  36958. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  36959. var offset = (sprite.cellIndex / rowSize) >> 0;
  36960. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  36961. this._vertexData[arrayOffset + 11] = offset;
  36962. // Color
  36963. this._vertexData[arrayOffset + 12] = sprite.color.r;
  36964. this._vertexData[arrayOffset + 13] = sprite.color.g;
  36965. this._vertexData[arrayOffset + 14] = sprite.color.b;
  36966. this._vertexData[arrayOffset + 15] = sprite.color.a;
  36967. };
  36968. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  36969. var count = Math.min(this._capacity, this.sprites.length);
  36970. var min = BABYLON.Vector3.Zero();
  36971. var max = BABYLON.Vector3.Zero();
  36972. var distance = Number.MAX_VALUE;
  36973. var currentSprite;
  36974. var cameraSpacePosition = BABYLON.Vector3.Zero();
  36975. var cameraView = camera.getViewMatrix();
  36976. for (var index = 0; index < count; index++) {
  36977. var sprite = this.sprites[index];
  36978. if (!sprite) {
  36979. continue;
  36980. }
  36981. if (predicate) {
  36982. if (!predicate(sprite)) {
  36983. continue;
  36984. }
  36985. }
  36986. else if (!sprite.isPickable) {
  36987. continue;
  36988. }
  36989. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  36990. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  36991. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  36992. if (ray.intersectsBoxMinMax(min, max)) {
  36993. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  36994. if (distance > currentDistance) {
  36995. distance = currentDistance;
  36996. currentSprite = sprite;
  36997. if (fastCheck) {
  36998. break;
  36999. }
  37000. }
  37001. }
  37002. }
  37003. if (currentSprite) {
  37004. var result = new BABYLON.PickingInfo();
  37005. result.hit = true;
  37006. result.pickedSprite = currentSprite;
  37007. result.distance = distance;
  37008. return result;
  37009. }
  37010. return null;
  37011. };
  37012. SpriteManager.prototype.render = function () {
  37013. // Check
  37014. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  37015. return;
  37016. var engine = this._scene.getEngine();
  37017. var baseSize = this._spriteTexture.getBaseSize();
  37018. // Sprites
  37019. var deltaTime = engine.getDeltaTime();
  37020. var max = Math.min(this._capacity, this.sprites.length);
  37021. var rowSize = baseSize.width / this.cellWidth;
  37022. var offset = 0;
  37023. for (var index = 0; index < max; index++) {
  37024. var sprite = this.sprites[index];
  37025. if (!sprite) {
  37026. continue;
  37027. }
  37028. sprite._animate(deltaTime);
  37029. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  37030. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  37031. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  37032. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  37033. }
  37034. this._buffer.update(this._vertexData);
  37035. // Render
  37036. var effect = this._effectBase;
  37037. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  37038. effect = this._effectFog;
  37039. }
  37040. engine.enableEffect(effect);
  37041. var viewMatrix = this._scene.getViewMatrix();
  37042. effect.setTexture("diffuseSampler", this._spriteTexture);
  37043. effect.setMatrix("view", viewMatrix);
  37044. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  37045. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  37046. // Fog
  37047. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  37048. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  37049. effect.setColor3("vFogColor", this._scene.fogColor);
  37050. }
  37051. // VBOs
  37052. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37053. // Draw order
  37054. engine.setDepthFunctionToLessOrEqual();
  37055. effect.setBool("alphaTest", true);
  37056. engine.setColorWrite(false);
  37057. engine.draw(true, 0, max * 6);
  37058. engine.setColorWrite(true);
  37059. effect.setBool("alphaTest", false);
  37060. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  37061. engine.draw(true, 0, max * 6);
  37062. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37063. };
  37064. SpriteManager.prototype.dispose = function () {
  37065. if (this._buffer) {
  37066. this._buffer.dispose();
  37067. this._buffer = null;
  37068. }
  37069. if (this._indexBuffer) {
  37070. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37071. this._indexBuffer = null;
  37072. }
  37073. if (this._spriteTexture) {
  37074. this._spriteTexture.dispose();
  37075. this._spriteTexture = null;
  37076. }
  37077. // Remove from scene
  37078. var index = this._scene.spriteManagers.indexOf(this);
  37079. this._scene.spriteManagers.splice(index, 1);
  37080. // Callback
  37081. this.onDisposeObservable.notifyObservers(this);
  37082. this.onDisposeObservable.clear();
  37083. };
  37084. return SpriteManager;
  37085. }());
  37086. BABYLON.SpriteManager = SpriteManager;
  37087. })(BABYLON || (BABYLON = {}));
  37088. //# sourceMappingURL=babylon.spriteManager.js.map
  37089. var BABYLON;
  37090. (function (BABYLON) {
  37091. var Sprite = (function () {
  37092. function Sprite(name, manager) {
  37093. this.name = name;
  37094. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37095. this.width = 1.0;
  37096. this.height = 1.0;
  37097. this.angle = 0;
  37098. this.cellIndex = 0;
  37099. this.invertU = 0;
  37100. this.invertV = 0;
  37101. this.animations = new Array();
  37102. this.isPickable = false;
  37103. this._animationStarted = false;
  37104. this._loopAnimation = false;
  37105. this._fromIndex = 0;
  37106. this._toIndex = 0;
  37107. this._delay = 0;
  37108. this._direction = 1;
  37109. this._frameCount = 0;
  37110. this._time = 0;
  37111. this._manager = manager;
  37112. this._manager.sprites.push(this);
  37113. this.position = BABYLON.Vector3.Zero();
  37114. }
  37115. Object.defineProperty(Sprite.prototype, "size", {
  37116. get: function () {
  37117. return this.width;
  37118. },
  37119. set: function (value) {
  37120. this.width = value;
  37121. this.height = value;
  37122. },
  37123. enumerable: true,
  37124. configurable: true
  37125. });
  37126. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  37127. this._fromIndex = from;
  37128. this._toIndex = to;
  37129. this._loopAnimation = loop;
  37130. this._delay = delay;
  37131. this._animationStarted = true;
  37132. this._direction = from < to ? 1 : -1;
  37133. this.cellIndex = from;
  37134. this._time = 0;
  37135. this._onAnimationEnd = onAnimationEnd;
  37136. };
  37137. Sprite.prototype.stopAnimation = function () {
  37138. this._animationStarted = false;
  37139. };
  37140. Sprite.prototype._animate = function (deltaTime) {
  37141. if (!this._animationStarted)
  37142. return;
  37143. this._time += deltaTime;
  37144. if (this._time > this._delay) {
  37145. this._time = this._time % this._delay;
  37146. this.cellIndex += this._direction;
  37147. if (this.cellIndex === this._toIndex) {
  37148. if (this._loopAnimation) {
  37149. this.cellIndex = this._fromIndex;
  37150. }
  37151. else {
  37152. this._animationStarted = false;
  37153. if (this._onAnimationEnd) {
  37154. this._onAnimationEnd();
  37155. }
  37156. if (this.disposeWhenFinishedAnimating) {
  37157. this.dispose();
  37158. }
  37159. }
  37160. }
  37161. }
  37162. };
  37163. Sprite.prototype.dispose = function () {
  37164. for (var i = 0; i < this._manager.sprites.length; i++) {
  37165. if (this._manager.sprites[i] == this) {
  37166. this._manager.sprites.splice(i, 1);
  37167. }
  37168. }
  37169. };
  37170. return Sprite;
  37171. }());
  37172. BABYLON.Sprite = Sprite;
  37173. })(BABYLON || (BABYLON = {}));
  37174. //# sourceMappingURL=babylon.sprite.js.map
  37175. var BABYLON;
  37176. (function (BABYLON) {
  37177. var IntersectionInfo = (function () {
  37178. function IntersectionInfo(bu, bv, distance) {
  37179. this.bu = bu;
  37180. this.bv = bv;
  37181. this.distance = distance;
  37182. this.faceId = 0;
  37183. this.subMeshId = 0;
  37184. }
  37185. return IntersectionInfo;
  37186. }());
  37187. BABYLON.IntersectionInfo = IntersectionInfo;
  37188. var PickingInfo = (function () {
  37189. function PickingInfo() {
  37190. this.hit = false;
  37191. this.distance = 0;
  37192. this.pickedPoint = null;
  37193. this.pickedMesh = null;
  37194. this.bu = 0;
  37195. this.bv = 0;
  37196. this.faceId = -1;
  37197. this.subMeshId = 0;
  37198. this.pickedSprite = null;
  37199. }
  37200. // Methods
  37201. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  37202. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  37203. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  37204. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37205. return null;
  37206. }
  37207. var indices = this.pickedMesh.getIndices();
  37208. var result;
  37209. if (useVerticesNormals) {
  37210. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37211. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  37212. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  37213. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  37214. normal0 = normal0.scale(this.bu);
  37215. normal1 = normal1.scale(this.bv);
  37216. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  37217. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  37218. }
  37219. else {
  37220. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37221. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  37222. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  37223. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  37224. var p1p2 = vertex1.subtract(vertex2);
  37225. var p3p2 = vertex3.subtract(vertex2);
  37226. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  37227. }
  37228. if (useWorldCoordinates) {
  37229. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  37230. }
  37231. return BABYLON.Vector3.Normalize(result);
  37232. };
  37233. PickingInfo.prototype.getTextureCoordinates = function () {
  37234. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37235. return null;
  37236. }
  37237. var indices = this.pickedMesh.getIndices();
  37238. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37239. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  37240. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  37241. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  37242. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  37243. uv1 = uv1.scale(this.bu);
  37244. uv2 = uv2.scale(this.bv);
  37245. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  37246. };
  37247. return PickingInfo;
  37248. }());
  37249. BABYLON.PickingInfo = PickingInfo;
  37250. })(BABYLON || (BABYLON = {}));
  37251. //# sourceMappingURL=babylon.pickingInfo.js.map
  37252. var BABYLON;
  37253. (function (BABYLON) {
  37254. var Ray = (function () {
  37255. function Ray(origin, direction, length) {
  37256. if (length === void 0) { length = Number.MAX_VALUE; }
  37257. this.origin = origin;
  37258. this.direction = direction;
  37259. this.length = length;
  37260. }
  37261. // Methods
  37262. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  37263. var d = 0.0;
  37264. var maxValue = Number.MAX_VALUE;
  37265. var inv;
  37266. var min;
  37267. var max;
  37268. var temp;
  37269. if (Math.abs(this.direction.x) < 0.0000001) {
  37270. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  37271. return false;
  37272. }
  37273. }
  37274. else {
  37275. inv = 1.0 / this.direction.x;
  37276. min = (minimum.x - this.origin.x) * inv;
  37277. max = (maximum.x - this.origin.x) * inv;
  37278. if (max === -Infinity) {
  37279. max = Infinity;
  37280. }
  37281. if (min > max) {
  37282. temp = min;
  37283. min = max;
  37284. max = temp;
  37285. }
  37286. d = Math.max(min, d);
  37287. maxValue = Math.min(max, maxValue);
  37288. if (d > maxValue) {
  37289. return false;
  37290. }
  37291. }
  37292. if (Math.abs(this.direction.y) < 0.0000001) {
  37293. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  37294. return false;
  37295. }
  37296. }
  37297. else {
  37298. inv = 1.0 / this.direction.y;
  37299. min = (minimum.y - this.origin.y) * inv;
  37300. max = (maximum.y - this.origin.y) * inv;
  37301. if (max === -Infinity) {
  37302. max = Infinity;
  37303. }
  37304. if (min > max) {
  37305. temp = min;
  37306. min = max;
  37307. max = temp;
  37308. }
  37309. d = Math.max(min, d);
  37310. maxValue = Math.min(max, maxValue);
  37311. if (d > maxValue) {
  37312. return false;
  37313. }
  37314. }
  37315. if (Math.abs(this.direction.z) < 0.0000001) {
  37316. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  37317. return false;
  37318. }
  37319. }
  37320. else {
  37321. inv = 1.0 / this.direction.z;
  37322. min = (minimum.z - this.origin.z) * inv;
  37323. max = (maximum.z - this.origin.z) * inv;
  37324. if (max === -Infinity) {
  37325. max = Infinity;
  37326. }
  37327. if (min > max) {
  37328. temp = min;
  37329. min = max;
  37330. max = temp;
  37331. }
  37332. d = Math.max(min, d);
  37333. maxValue = Math.min(max, maxValue);
  37334. if (d > maxValue) {
  37335. return false;
  37336. }
  37337. }
  37338. return true;
  37339. };
  37340. Ray.prototype.intersectsBox = function (box) {
  37341. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  37342. };
  37343. Ray.prototype.intersectsSphere = function (sphere) {
  37344. var x = sphere.center.x - this.origin.x;
  37345. var y = sphere.center.y - this.origin.y;
  37346. var z = sphere.center.z - this.origin.z;
  37347. var pyth = (x * x) + (y * y) + (z * z);
  37348. var rr = sphere.radius * sphere.radius;
  37349. if (pyth <= rr) {
  37350. return true;
  37351. }
  37352. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  37353. if (dot < 0.0) {
  37354. return false;
  37355. }
  37356. var temp = pyth - (dot * dot);
  37357. return temp <= rr;
  37358. };
  37359. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  37360. if (!this._edge1) {
  37361. this._edge1 = BABYLON.Vector3.Zero();
  37362. this._edge2 = BABYLON.Vector3.Zero();
  37363. this._pvec = BABYLON.Vector3.Zero();
  37364. this._tvec = BABYLON.Vector3.Zero();
  37365. this._qvec = BABYLON.Vector3.Zero();
  37366. }
  37367. vertex1.subtractToRef(vertex0, this._edge1);
  37368. vertex2.subtractToRef(vertex0, this._edge2);
  37369. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  37370. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  37371. if (det === 0) {
  37372. return null;
  37373. }
  37374. var invdet = 1 / det;
  37375. this.origin.subtractToRef(vertex0, this._tvec);
  37376. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  37377. if (bu < 0 || bu > 1.0) {
  37378. return null;
  37379. }
  37380. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  37381. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  37382. if (bv < 0 || bu + bv > 1.0) {
  37383. return null;
  37384. }
  37385. //check if the distance is longer than the predefined length.
  37386. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  37387. if (distance > this.length) {
  37388. return null;
  37389. }
  37390. return new BABYLON.IntersectionInfo(bu, bv, distance);
  37391. };
  37392. Ray.prototype.intersectsPlane = function (plane) {
  37393. var distance;
  37394. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  37395. if (Math.abs(result1) < 9.99999997475243E-07) {
  37396. return null;
  37397. }
  37398. else {
  37399. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  37400. distance = (-plane.d - result2) / result1;
  37401. if (distance < 0.0) {
  37402. if (distance < -9.99999997475243E-07) {
  37403. return null;
  37404. }
  37405. else {
  37406. return 0;
  37407. }
  37408. }
  37409. return distance;
  37410. }
  37411. };
  37412. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  37413. var tm = BABYLON.Tmp.Matrix[0];
  37414. mesh.getWorldMatrix().invertToRef(tm);
  37415. if (this._tmpRay) {
  37416. Ray.TransformToRef(this, tm, this._tmpRay);
  37417. }
  37418. else {
  37419. this._tmpRay = Ray.Transform(this, tm);
  37420. }
  37421. return mesh.intersects(this._tmpRay, fastCheck);
  37422. };
  37423. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  37424. if (results) {
  37425. results.length = 0;
  37426. }
  37427. else {
  37428. results = [];
  37429. }
  37430. for (var i = 0; i < meshes.length; i++) {
  37431. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  37432. if (pickInfo.hit) {
  37433. results.push(pickInfo);
  37434. }
  37435. }
  37436. results.sort(this._comparePickingInfo);
  37437. return results;
  37438. };
  37439. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  37440. if (pickingInfoA.distance < pickingInfoB.distance) {
  37441. return -1;
  37442. }
  37443. else if (pickingInfoA.distance > pickingInfoB.distance) {
  37444. return 1;
  37445. }
  37446. else {
  37447. return 0;
  37448. }
  37449. };
  37450. /**
  37451. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  37452. * @param sega the first point of the segment to test the intersection against
  37453. * @param segb the second point of the segment to test the intersection against
  37454. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  37455. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  37456. */
  37457. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  37458. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  37459. var u = segb.subtract(sega);
  37460. var v = rsegb.subtract(this.origin);
  37461. var w = sega.subtract(this.origin);
  37462. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  37463. var b = BABYLON.Vector3.Dot(u, v);
  37464. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  37465. var d = BABYLON.Vector3.Dot(u, w);
  37466. var e = BABYLON.Vector3.Dot(v, w);
  37467. var D = a * c - b * b; // always >= 0
  37468. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  37469. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  37470. // compute the line parameters of the two closest points
  37471. if (D < Ray.smallnum) {
  37472. sN = 0.0; // force using point P0 on segment S1
  37473. sD = 1.0; // to prevent possible division by 0.0 later
  37474. tN = e;
  37475. tD = c;
  37476. }
  37477. else {
  37478. sN = (b * e - c * d);
  37479. tN = (a * e - b * d);
  37480. if (sN < 0.0) {
  37481. sN = 0.0;
  37482. tN = e;
  37483. tD = c;
  37484. }
  37485. else if (sN > sD) {
  37486. sN = sD;
  37487. tN = e + b;
  37488. tD = c;
  37489. }
  37490. }
  37491. if (tN < 0.0) {
  37492. tN = 0.0;
  37493. // recompute sc for this edge
  37494. if (-d < 0.0) {
  37495. sN = 0.0;
  37496. }
  37497. else if (-d > a)
  37498. sN = sD;
  37499. else {
  37500. sN = -d;
  37501. sD = a;
  37502. }
  37503. }
  37504. else if (tN > tD) {
  37505. tN = tD;
  37506. // recompute sc for this edge
  37507. if ((-d + b) < 0.0) {
  37508. sN = 0;
  37509. }
  37510. else if ((-d + b) > a) {
  37511. sN = sD;
  37512. }
  37513. else {
  37514. sN = (-d + b);
  37515. sD = a;
  37516. }
  37517. }
  37518. // finally do the division to get sc and tc
  37519. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  37520. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  37521. // get the difference of the two closest points
  37522. var qtc = v.multiplyByFloats(tc, tc, tc);
  37523. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  37524. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  37525. if (isIntersected) {
  37526. return qtc.length();
  37527. }
  37528. return -1;
  37529. };
  37530. // Statics
  37531. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  37532. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  37533. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  37534. var direction = end.subtract(start);
  37535. direction.normalize();
  37536. return new Ray(start, direction);
  37537. };
  37538. /**
  37539. * 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
  37540. * transformed to the given world matrix.
  37541. * @param origin The origin point
  37542. * @param end The end point
  37543. * @param world a matrix to transform the ray to. Default is the identity matrix.
  37544. */
  37545. Ray.CreateNewFromTo = function (origin, end, world) {
  37546. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  37547. var direction = end.subtract(origin);
  37548. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  37549. direction.normalize();
  37550. return Ray.Transform(new Ray(origin, direction, length), world);
  37551. };
  37552. Ray.Transform = function (ray, matrix) {
  37553. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  37554. Ray.TransformToRef(ray, matrix, result);
  37555. return result;
  37556. };
  37557. Ray.TransformToRef = function (ray, matrix, result) {
  37558. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  37559. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  37560. result.length = ray.length;
  37561. var dir = result.direction;
  37562. var len = dir.length();
  37563. if (!(len === 0 || len === 1)) {
  37564. var num = 1.0 / len;
  37565. dir.x *= num;
  37566. dir.y *= num;
  37567. dir.z *= num;
  37568. result.length *= len;
  37569. }
  37570. };
  37571. return Ray;
  37572. }());
  37573. Ray.smallnum = 0.00000001;
  37574. Ray.rayl = 10e8;
  37575. BABYLON.Ray = Ray;
  37576. })(BABYLON || (BABYLON = {}));
  37577. //# sourceMappingURL=babylon.ray.js.map
  37578. var BABYLON;
  37579. (function (BABYLON) {
  37580. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  37581. if (boxMin.x > sphereCenter.x + sphereRadius)
  37582. return false;
  37583. if (sphereCenter.x - sphereRadius > boxMax.x)
  37584. return false;
  37585. if (boxMin.y > sphereCenter.y + sphereRadius)
  37586. return false;
  37587. if (sphereCenter.y - sphereRadius > boxMax.y)
  37588. return false;
  37589. if (boxMin.z > sphereCenter.z + sphereRadius)
  37590. return false;
  37591. if (sphereCenter.z - sphereRadius > boxMax.z)
  37592. return false;
  37593. return true;
  37594. };
  37595. var getLowestRoot = (function () {
  37596. var result = { root: 0, found: false };
  37597. return function (a, b, c, maxR) {
  37598. result.root = 0;
  37599. result.found = false;
  37600. var determinant = b * b - 4.0 * a * c;
  37601. if (determinant < 0)
  37602. return result;
  37603. var sqrtD = Math.sqrt(determinant);
  37604. var r1 = (-b - sqrtD) / (2.0 * a);
  37605. var r2 = (-b + sqrtD) / (2.0 * a);
  37606. if (r1 > r2) {
  37607. var temp = r2;
  37608. r2 = r1;
  37609. r1 = temp;
  37610. }
  37611. if (r1 > 0 && r1 < maxR) {
  37612. result.root = r1;
  37613. result.found = true;
  37614. return result;
  37615. }
  37616. if (r2 > 0 && r2 < maxR) {
  37617. result.root = r2;
  37618. result.found = true;
  37619. return result;
  37620. }
  37621. return result;
  37622. };
  37623. })();
  37624. var Collider = (function () {
  37625. function Collider() {
  37626. this.radius = BABYLON.Vector3.One();
  37627. this.retry = 0;
  37628. this.basePointWorld = BABYLON.Vector3.Zero();
  37629. this.velocityWorld = BABYLON.Vector3.Zero();
  37630. this.normalizedVelocity = BABYLON.Vector3.Zero();
  37631. this._collisionPoint = BABYLON.Vector3.Zero();
  37632. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  37633. this._tempVector = BABYLON.Vector3.Zero();
  37634. this._tempVector2 = BABYLON.Vector3.Zero();
  37635. this._tempVector3 = BABYLON.Vector3.Zero();
  37636. this._tempVector4 = BABYLON.Vector3.Zero();
  37637. this._edge = BABYLON.Vector3.Zero();
  37638. this._baseToVertex = BABYLON.Vector3.Zero();
  37639. this._destinationPoint = BABYLON.Vector3.Zero();
  37640. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  37641. this._displacementVector = BABYLON.Vector3.Zero();
  37642. this._collisionMask = -1;
  37643. }
  37644. Object.defineProperty(Collider.prototype, "collisionMask", {
  37645. get: function () {
  37646. return this._collisionMask;
  37647. },
  37648. set: function (mask) {
  37649. this._collisionMask = !isNaN(mask) ? mask : -1;
  37650. },
  37651. enumerable: true,
  37652. configurable: true
  37653. });
  37654. // Methods
  37655. Collider.prototype._initialize = function (source, dir, e) {
  37656. this.velocity = dir;
  37657. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  37658. this.basePoint = source;
  37659. source.multiplyToRef(this.radius, this.basePointWorld);
  37660. dir.multiplyToRef(this.radius, this.velocityWorld);
  37661. this.velocityWorldLength = this.velocityWorld.length();
  37662. this.epsilon = e;
  37663. this.collisionFound = false;
  37664. };
  37665. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  37666. pa.subtractToRef(point, this._tempVector);
  37667. pb.subtractToRef(point, this._tempVector2);
  37668. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  37669. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37670. if (d < 0)
  37671. return false;
  37672. pc.subtractToRef(point, this._tempVector3);
  37673. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  37674. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37675. if (d < 0)
  37676. return false;
  37677. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  37678. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37679. return d >= 0;
  37680. };
  37681. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  37682. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  37683. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  37684. if (distance > this.velocityWorldLength + max + sphereRadius) {
  37685. return false;
  37686. }
  37687. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  37688. return false;
  37689. return true;
  37690. };
  37691. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  37692. var t0;
  37693. var embeddedInPlane = false;
  37694. //defensive programming, actually not needed.
  37695. if (!trianglePlaneArray) {
  37696. trianglePlaneArray = [];
  37697. }
  37698. if (!trianglePlaneArray[faceIndex]) {
  37699. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  37700. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  37701. }
  37702. var trianglePlane = trianglePlaneArray[faceIndex];
  37703. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  37704. return;
  37705. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  37706. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  37707. if (normalDotVelocity == 0) {
  37708. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  37709. return;
  37710. embeddedInPlane = true;
  37711. t0 = 0;
  37712. }
  37713. else {
  37714. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37715. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37716. if (t0 > t1) {
  37717. var temp = t1;
  37718. t1 = t0;
  37719. t0 = temp;
  37720. }
  37721. if (t0 > 1.0 || t1 < 0.0)
  37722. return;
  37723. if (t0 < 0)
  37724. t0 = 0;
  37725. if (t0 > 1.0)
  37726. t0 = 1.0;
  37727. }
  37728. this._collisionPoint.copyFromFloats(0, 0, 0);
  37729. var found = false;
  37730. var t = 1.0;
  37731. if (!embeddedInPlane) {
  37732. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  37733. this.velocity.scaleToRef(t0, this._tempVector);
  37734. this._planeIntersectionPoint.addInPlace(this._tempVector);
  37735. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  37736. found = true;
  37737. t = t0;
  37738. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  37739. }
  37740. }
  37741. if (!found) {
  37742. var velocitySquaredLength = this.velocity.lengthSquared();
  37743. var a = velocitySquaredLength;
  37744. this.basePoint.subtractToRef(p1, this._tempVector);
  37745. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37746. var c = this._tempVector.lengthSquared() - 1.0;
  37747. var lowestRoot = getLowestRoot(a, b, c, t);
  37748. if (lowestRoot.found) {
  37749. t = lowestRoot.root;
  37750. found = true;
  37751. this._collisionPoint.copyFrom(p1);
  37752. }
  37753. this.basePoint.subtractToRef(p2, this._tempVector);
  37754. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37755. c = this._tempVector.lengthSquared() - 1.0;
  37756. lowestRoot = getLowestRoot(a, b, c, t);
  37757. if (lowestRoot.found) {
  37758. t = lowestRoot.root;
  37759. found = true;
  37760. this._collisionPoint.copyFrom(p2);
  37761. }
  37762. this.basePoint.subtractToRef(p3, this._tempVector);
  37763. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37764. c = this._tempVector.lengthSquared() - 1.0;
  37765. lowestRoot = getLowestRoot(a, b, c, t);
  37766. if (lowestRoot.found) {
  37767. t = lowestRoot.root;
  37768. found = true;
  37769. this._collisionPoint.copyFrom(p3);
  37770. }
  37771. p2.subtractToRef(p1, this._edge);
  37772. p1.subtractToRef(this.basePoint, this._baseToVertex);
  37773. var edgeSquaredLength = this._edge.lengthSquared();
  37774. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37775. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37776. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37777. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37778. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37779. lowestRoot = getLowestRoot(a, b, c, t);
  37780. if (lowestRoot.found) {
  37781. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37782. if (f >= 0.0 && f <= 1.0) {
  37783. t = lowestRoot.root;
  37784. found = true;
  37785. this._edge.scaleInPlace(f);
  37786. p1.addToRef(this._edge, this._collisionPoint);
  37787. }
  37788. }
  37789. p3.subtractToRef(p2, this._edge);
  37790. p2.subtractToRef(this.basePoint, this._baseToVertex);
  37791. edgeSquaredLength = this._edge.lengthSquared();
  37792. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37793. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37794. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37795. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37796. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37797. lowestRoot = getLowestRoot(a, b, c, t);
  37798. if (lowestRoot.found) {
  37799. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37800. if (f >= 0.0 && f <= 1.0) {
  37801. t = lowestRoot.root;
  37802. found = true;
  37803. this._edge.scaleInPlace(f);
  37804. p2.addToRef(this._edge, this._collisionPoint);
  37805. }
  37806. }
  37807. p1.subtractToRef(p3, this._edge);
  37808. p3.subtractToRef(this.basePoint, this._baseToVertex);
  37809. edgeSquaredLength = this._edge.lengthSquared();
  37810. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37811. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37812. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37813. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37814. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37815. lowestRoot = getLowestRoot(a, b, c, t);
  37816. if (lowestRoot.found) {
  37817. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37818. if (f >= 0.0 && f <= 1.0) {
  37819. t = lowestRoot.root;
  37820. found = true;
  37821. this._edge.scaleInPlace(f);
  37822. p3.addToRef(this._edge, this._collisionPoint);
  37823. }
  37824. }
  37825. }
  37826. if (found) {
  37827. var distToCollision = t * this.velocity.length();
  37828. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  37829. if (!this.intersectionPoint) {
  37830. this.intersectionPoint = this._collisionPoint.clone();
  37831. }
  37832. else {
  37833. this.intersectionPoint.copyFrom(this._collisionPoint);
  37834. }
  37835. this.nearestDistance = distToCollision;
  37836. this.collisionFound = true;
  37837. }
  37838. }
  37839. };
  37840. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  37841. for (var i = indexStart; i < indexEnd; i += 3) {
  37842. var p1 = pts[indices[i] - decal];
  37843. var p2 = pts[indices[i + 1] - decal];
  37844. var p3 = pts[indices[i + 2] - decal];
  37845. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  37846. }
  37847. };
  37848. Collider.prototype._getResponse = function (pos, vel) {
  37849. pos.addToRef(vel, this._destinationPoint);
  37850. vel.scaleInPlace((this.nearestDistance / vel.length()));
  37851. this.basePoint.addToRef(vel, pos);
  37852. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  37853. this._slidePlaneNormal.normalize();
  37854. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  37855. pos.addInPlace(this._displacementVector);
  37856. this.intersectionPoint.addInPlace(this._displacementVector);
  37857. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  37858. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  37859. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  37860. };
  37861. return Collider;
  37862. }());
  37863. BABYLON.Collider = Collider;
  37864. })(BABYLON || (BABYLON = {}));
  37865. //# sourceMappingURL=babylon.collider.js.map
  37866. var BABYLON;
  37867. (function (BABYLON) {
  37868. //WebWorker code will be inserted to this variable.
  37869. BABYLON.CollisionWorker = "";
  37870. var WorkerTaskType;
  37871. (function (WorkerTaskType) {
  37872. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  37873. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  37874. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  37875. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  37876. var WorkerReplyType;
  37877. (function (WorkerReplyType) {
  37878. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  37879. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  37880. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  37881. var CollisionCoordinatorWorker = (function () {
  37882. function CollisionCoordinatorWorker() {
  37883. var _this = this;
  37884. this._scaledPosition = BABYLON.Vector3.Zero();
  37885. this._scaledVelocity = BABYLON.Vector3.Zero();
  37886. this.onMeshUpdated = function (mesh) {
  37887. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  37888. };
  37889. this.onGeometryUpdated = function (geometry) {
  37890. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  37891. };
  37892. this._afterRender = function () {
  37893. if (!_this._init)
  37894. return;
  37895. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  37896. return;
  37897. }
  37898. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  37899. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  37900. if (_this._runningUpdated > 4) {
  37901. return;
  37902. }
  37903. ++_this._runningUpdated;
  37904. var payload = {
  37905. updatedMeshes: _this._addUpdateMeshesList,
  37906. updatedGeometries: _this._addUpdateGeometriesList,
  37907. removedGeometries: _this._toRemoveGeometryArray,
  37908. removedMeshes: _this._toRemoveMeshesArray
  37909. };
  37910. var message = {
  37911. payload: payload,
  37912. taskType: WorkerTaskType.UPDATE
  37913. };
  37914. var serializable = [];
  37915. for (var id in payload.updatedGeometries) {
  37916. if (payload.updatedGeometries.hasOwnProperty(id)) {
  37917. //prepare transferables
  37918. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  37919. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  37920. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  37921. }
  37922. }
  37923. _this._worker.postMessage(message, serializable);
  37924. _this._addUpdateMeshesList = {};
  37925. _this._addUpdateGeometriesList = {};
  37926. _this._toRemoveGeometryArray = [];
  37927. _this._toRemoveMeshesArray = [];
  37928. };
  37929. this._onMessageFromWorker = function (e) {
  37930. var returnData = e.data;
  37931. if (returnData.error != WorkerReplyType.SUCCESS) {
  37932. //TODO what errors can be returned from the worker?
  37933. BABYLON.Tools.Warn("error returned from worker!");
  37934. return;
  37935. }
  37936. switch (returnData.taskType) {
  37937. case WorkerTaskType.INIT:
  37938. _this._init = true;
  37939. //Update the worked with ALL of the scene's current state
  37940. _this._scene.meshes.forEach(function (mesh) {
  37941. _this.onMeshAdded(mesh);
  37942. });
  37943. _this._scene.getGeometries().forEach(function (geometry) {
  37944. _this.onGeometryAdded(geometry);
  37945. });
  37946. break;
  37947. case WorkerTaskType.UPDATE:
  37948. _this._runningUpdated--;
  37949. break;
  37950. case WorkerTaskType.COLLIDE:
  37951. _this._runningCollisionTask = false;
  37952. var returnPayload = returnData.payload;
  37953. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  37954. return;
  37955. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  37956. //cleanup
  37957. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  37958. break;
  37959. }
  37960. };
  37961. this._collisionsCallbackArray = [];
  37962. this._init = false;
  37963. this._runningUpdated = 0;
  37964. this._runningCollisionTask = false;
  37965. this._addUpdateMeshesList = {};
  37966. this._addUpdateGeometriesList = {};
  37967. this._toRemoveGeometryArray = [];
  37968. this._toRemoveMeshesArray = [];
  37969. }
  37970. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37971. if (!this._init)
  37972. return;
  37973. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  37974. return;
  37975. position.divideToRef(collider.radius, this._scaledPosition);
  37976. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37977. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  37978. var payload = {
  37979. collider: {
  37980. position: this._scaledPosition.asArray(),
  37981. velocity: this._scaledVelocity.asArray(),
  37982. radius: collider.radius.asArray()
  37983. },
  37984. collisionId: collisionIndex,
  37985. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  37986. maximumRetry: maximumRetry
  37987. };
  37988. var message = {
  37989. payload: payload,
  37990. taskType: WorkerTaskType.COLLIDE
  37991. };
  37992. this._worker.postMessage(message);
  37993. };
  37994. CollisionCoordinatorWorker.prototype.init = function (scene) {
  37995. this._scene = scene;
  37996. this._scene.registerAfterRender(this._afterRender);
  37997. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  37998. this._worker = new Worker(workerUrl);
  37999. this._worker.onmessage = this._onMessageFromWorker;
  38000. var message = {
  38001. payload: {},
  38002. taskType: WorkerTaskType.INIT
  38003. };
  38004. this._worker.postMessage(message);
  38005. };
  38006. CollisionCoordinatorWorker.prototype.destroy = function () {
  38007. this._scene.unregisterAfterRender(this._afterRender);
  38008. this._worker.terminate();
  38009. };
  38010. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  38011. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  38012. this.onMeshUpdated(mesh);
  38013. };
  38014. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  38015. this._toRemoveMeshesArray.push(mesh.uniqueId);
  38016. };
  38017. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  38018. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  38019. geometry.onGeometryUpdated = this.onGeometryUpdated;
  38020. this.onGeometryUpdated(geometry);
  38021. };
  38022. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  38023. this._toRemoveGeometryArray.push(geometry.id);
  38024. };
  38025. return CollisionCoordinatorWorker;
  38026. }());
  38027. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  38028. var submeshes = [];
  38029. if (mesh.subMeshes) {
  38030. submeshes = mesh.subMeshes.map(function (sm, idx) {
  38031. return {
  38032. position: idx,
  38033. verticesStart: sm.verticesStart,
  38034. verticesCount: sm.verticesCount,
  38035. indexStart: sm.indexStart,
  38036. indexCount: sm.indexCount,
  38037. hasMaterial: !!sm.getMaterial(),
  38038. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  38039. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  38040. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  38041. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  38042. };
  38043. });
  38044. }
  38045. var geometryId = null;
  38046. if (mesh instanceof BABYLON.Mesh) {
  38047. geometryId = mesh.geometry ? mesh.geometry.id : null;
  38048. }
  38049. else if (mesh instanceof BABYLON.InstancedMesh) {
  38050. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  38051. }
  38052. return {
  38053. uniqueId: mesh.uniqueId,
  38054. id: mesh.id,
  38055. name: mesh.name,
  38056. geometryId: geometryId,
  38057. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  38058. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  38059. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  38060. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  38061. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  38062. subMeshes: submeshes,
  38063. checkCollisions: mesh.checkCollisions
  38064. };
  38065. };
  38066. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  38067. return {
  38068. id: geometry.id,
  38069. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  38070. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  38071. indices: new Uint32Array(geometry.getIndices() || []),
  38072. };
  38073. };
  38074. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  38075. var CollisionCoordinatorLegacy = (function () {
  38076. function CollisionCoordinatorLegacy() {
  38077. this._scaledPosition = BABYLON.Vector3.Zero();
  38078. this._scaledVelocity = BABYLON.Vector3.Zero();
  38079. this._finalPosition = BABYLON.Vector3.Zero();
  38080. }
  38081. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  38082. position.divideToRef(collider.radius, this._scaledPosition);
  38083. velocity.divideToRef(collider.radius, this._scaledVelocity);
  38084. collider.collidedMesh = null;
  38085. collider.retry = 0;
  38086. collider.initialVelocity = this._scaledVelocity;
  38087. collider.initialPosition = this._scaledPosition;
  38088. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  38089. this._finalPosition.multiplyInPlace(collider.radius);
  38090. //run the callback
  38091. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  38092. };
  38093. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  38094. this._scene = scene;
  38095. };
  38096. CollisionCoordinatorLegacy.prototype.destroy = function () {
  38097. //Legacy need no destruction method.
  38098. };
  38099. //No update in legacy mode
  38100. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  38101. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  38102. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  38103. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  38104. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  38105. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  38106. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  38107. if (excludedMesh === void 0) { excludedMesh = null; }
  38108. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  38109. if (collider.retry >= maximumRetry) {
  38110. finalPosition.copyFrom(position);
  38111. return;
  38112. }
  38113. // Check if this is a mesh else camera or -1
  38114. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  38115. collider._initialize(position, velocity, closeDistance);
  38116. // Check all meshes
  38117. for (var index = 0; index < this._scene.meshes.length; index++) {
  38118. var mesh = this._scene.meshes[index];
  38119. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  38120. mesh._checkCollision(collider);
  38121. }
  38122. }
  38123. if (!collider.collisionFound) {
  38124. position.addToRef(velocity, finalPosition);
  38125. return;
  38126. }
  38127. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  38128. collider._getResponse(position, velocity);
  38129. }
  38130. if (velocity.length() <= closeDistance) {
  38131. finalPosition.copyFrom(position);
  38132. return;
  38133. }
  38134. collider.retry++;
  38135. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  38136. };
  38137. return CollisionCoordinatorLegacy;
  38138. }());
  38139. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  38140. })(BABYLON || (BABYLON = {}));
  38141. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  38142. var BABYLON;
  38143. (function (BABYLON) {
  38144. var Particle = (function () {
  38145. function Particle() {
  38146. this.position = BABYLON.Vector3.Zero();
  38147. this.direction = BABYLON.Vector3.Zero();
  38148. this.color = new BABYLON.Color4(0, 0, 0, 0);
  38149. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  38150. this.lifeTime = 1.0;
  38151. this.age = 0;
  38152. this.size = 0;
  38153. this.angle = 0;
  38154. this.angularSpeed = 0;
  38155. }
  38156. Particle.prototype.copyTo = function (other) {
  38157. other.position.copyFrom(this.position);
  38158. other.direction.copyFrom(this.direction);
  38159. other.color.copyFrom(this.color);
  38160. other.colorStep.copyFrom(this.colorStep);
  38161. other.lifeTime = this.lifeTime;
  38162. other.age = this.age;
  38163. other.size = this.size;
  38164. other.angle = this.angle;
  38165. other.angularSpeed = this.angularSpeed;
  38166. };
  38167. return Particle;
  38168. }());
  38169. BABYLON.Particle = Particle;
  38170. })(BABYLON || (BABYLON = {}));
  38171. //# sourceMappingURL=babylon.particle.js.map
  38172. var BABYLON;
  38173. (function (BABYLON) {
  38174. var randomNumber = function (min, max) {
  38175. if (min === max) {
  38176. return (min);
  38177. }
  38178. var random = Math.random();
  38179. return ((random * (max - min)) + min);
  38180. };
  38181. var ParticleSystem = (function () {
  38182. function ParticleSystem(name, capacity, scene, customEffect) {
  38183. var _this = this;
  38184. this.name = name;
  38185. // Members
  38186. this.animations = [];
  38187. this.renderingGroupId = 0;
  38188. this.emitter = null;
  38189. this.emitRate = 10;
  38190. this.manualEmitCount = -1;
  38191. this.updateSpeed = 0.01;
  38192. this.targetStopDuration = 0;
  38193. this.disposeOnStop = false;
  38194. this.minEmitPower = 1;
  38195. this.maxEmitPower = 1;
  38196. this.minLifeTime = 1;
  38197. this.maxLifeTime = 1;
  38198. this.minSize = 1;
  38199. this.maxSize = 1;
  38200. this.minAngularSpeed = 0;
  38201. this.maxAngularSpeed = 0;
  38202. this.layerMask = 0x0FFFFFFF;
  38203. this.customShader = null;
  38204. this.preventAutoStart = false;
  38205. /**
  38206. * An event triggered when the system is disposed.
  38207. * @type {BABYLON.Observable}
  38208. */
  38209. this.onDisposeObservable = new BABYLON.Observable();
  38210. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  38211. this.forceDepthWrite = false;
  38212. this.gravity = BABYLON.Vector3.Zero();
  38213. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  38214. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  38215. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  38216. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38217. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38218. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38219. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  38220. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38221. this.particles = new Array();
  38222. this._stockParticles = new Array();
  38223. this._newPartsExcess = 0;
  38224. this._vertexBuffers = {};
  38225. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  38226. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  38227. this._scaledDirection = BABYLON.Vector3.Zero();
  38228. this._scaledGravity = BABYLON.Vector3.Zero();
  38229. this._currentRenderId = -1;
  38230. this._started = false;
  38231. this._stopped = false;
  38232. this._actualFrame = 0;
  38233. this.id = name;
  38234. this._capacity = capacity;
  38235. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38236. this._customEffect = customEffect;
  38237. scene.particleSystems.push(this);
  38238. var indices = [];
  38239. var index = 0;
  38240. for (var count = 0; count < capacity; count++) {
  38241. indices.push(index);
  38242. indices.push(index + 1);
  38243. indices.push(index + 2);
  38244. indices.push(index);
  38245. indices.push(index + 2);
  38246. indices.push(index + 3);
  38247. index += 4;
  38248. }
  38249. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38250. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  38251. this._vertexData = new Float32Array(capacity * 11 * 4);
  38252. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  38253. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  38254. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  38255. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  38256. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  38257. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  38258. this._vertexBuffers["options"] = options;
  38259. // Default behaviors
  38260. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  38261. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  38262. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  38263. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  38264. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  38265. };
  38266. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  38267. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  38268. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  38269. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  38270. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  38271. };
  38272. this.updateFunction = function (particles) {
  38273. for (var index = 0; index < particles.length; index++) {
  38274. var particle = particles[index];
  38275. particle.age += _this._scaledUpdateSpeed;
  38276. if (particle.age >= particle.lifeTime) {
  38277. _this.recycleParticle(particle);
  38278. index--;
  38279. continue;
  38280. }
  38281. else {
  38282. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  38283. particle.color.addInPlace(_this._scaledColorStep);
  38284. if (particle.color.a < 0)
  38285. particle.color.a = 0;
  38286. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  38287. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  38288. particle.position.addInPlace(_this._scaledDirection);
  38289. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  38290. particle.direction.addInPlace(_this._scaledGravity);
  38291. }
  38292. }
  38293. };
  38294. }
  38295. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  38296. set: function (callback) {
  38297. if (this._onDisposeObserver) {
  38298. this.onDisposeObservable.remove(this._onDisposeObserver);
  38299. }
  38300. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38301. },
  38302. enumerable: true,
  38303. configurable: true
  38304. });
  38305. ParticleSystem.prototype.recycleParticle = function (particle) {
  38306. var lastParticle = this.particles.pop();
  38307. if (lastParticle !== particle) {
  38308. lastParticle.copyTo(particle);
  38309. this._stockParticles.push(lastParticle);
  38310. }
  38311. };
  38312. ParticleSystem.prototype.getCapacity = function () {
  38313. return this._capacity;
  38314. };
  38315. ParticleSystem.prototype.isAlive = function () {
  38316. return this._alive;
  38317. };
  38318. ParticleSystem.prototype.isStarted = function () {
  38319. return this._started;
  38320. };
  38321. ParticleSystem.prototype.start = function () {
  38322. this._started = true;
  38323. this._stopped = false;
  38324. this._actualFrame = 0;
  38325. };
  38326. ParticleSystem.prototype.stop = function () {
  38327. this._stopped = true;
  38328. };
  38329. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  38330. var offset = index * 11;
  38331. this._vertexData[offset] = particle.position.x;
  38332. this._vertexData[offset + 1] = particle.position.y;
  38333. this._vertexData[offset + 2] = particle.position.z;
  38334. this._vertexData[offset + 3] = particle.color.r;
  38335. this._vertexData[offset + 4] = particle.color.g;
  38336. this._vertexData[offset + 5] = particle.color.b;
  38337. this._vertexData[offset + 6] = particle.color.a;
  38338. this._vertexData[offset + 7] = particle.angle;
  38339. this._vertexData[offset + 8] = particle.size;
  38340. this._vertexData[offset + 9] = offsetX;
  38341. this._vertexData[offset + 10] = offsetY;
  38342. };
  38343. ParticleSystem.prototype._update = function (newParticles) {
  38344. // Update current
  38345. this._alive = this.particles.length > 0;
  38346. this.updateFunction(this.particles);
  38347. // Add new ones
  38348. var worldMatrix;
  38349. if (this.emitter.position) {
  38350. worldMatrix = this.emitter.getWorldMatrix();
  38351. }
  38352. else {
  38353. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  38354. }
  38355. var particle;
  38356. for (var index = 0; index < newParticles; index++) {
  38357. if (this.particles.length === this._capacity) {
  38358. break;
  38359. }
  38360. if (this._stockParticles.length !== 0) {
  38361. particle = this._stockParticles.pop();
  38362. particle.age = 0;
  38363. }
  38364. else {
  38365. particle = new BABYLON.Particle();
  38366. }
  38367. this.particles.push(particle);
  38368. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  38369. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  38370. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  38371. particle.size = randomNumber(this.minSize, this.maxSize);
  38372. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  38373. this.startPositionFunction(worldMatrix, particle.position, particle);
  38374. var step = randomNumber(0, 1.0);
  38375. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  38376. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  38377. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  38378. }
  38379. };
  38380. ParticleSystem.prototype._getEffect = function () {
  38381. if (this._customEffect) {
  38382. return this._customEffect;
  38383. }
  38384. ;
  38385. var defines = [];
  38386. if (this._scene.clipPlane) {
  38387. defines.push("#define CLIPPLANE");
  38388. }
  38389. // Effect
  38390. var join = defines.join("\n");
  38391. if (this._cachedDefines !== join) {
  38392. this._cachedDefines = join;
  38393. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  38394. }
  38395. return this._effect;
  38396. };
  38397. ParticleSystem.prototype.animate = function () {
  38398. if (!this._started)
  38399. return;
  38400. var effect = this._getEffect();
  38401. // Check
  38402. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  38403. return;
  38404. if (this._currentRenderId === this._scene.getRenderId()) {
  38405. return;
  38406. }
  38407. this._currentRenderId = this._scene.getRenderId();
  38408. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  38409. // determine the number of particles we need to create
  38410. var newParticles;
  38411. if (this.manualEmitCount > -1) {
  38412. newParticles = this.manualEmitCount;
  38413. this._newPartsExcess = 0;
  38414. this.manualEmitCount = 0;
  38415. }
  38416. else {
  38417. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  38418. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  38419. }
  38420. if (this._newPartsExcess > 1.0) {
  38421. newParticles += this._newPartsExcess >> 0;
  38422. this._newPartsExcess -= this._newPartsExcess >> 0;
  38423. }
  38424. this._alive = false;
  38425. if (!this._stopped) {
  38426. this._actualFrame += this._scaledUpdateSpeed;
  38427. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  38428. this.stop();
  38429. }
  38430. else {
  38431. newParticles = 0;
  38432. }
  38433. this._update(newParticles);
  38434. // Stopped?
  38435. if (this._stopped) {
  38436. if (!this._alive) {
  38437. this._started = false;
  38438. if (this.disposeOnStop) {
  38439. this._scene._toBeDisposed.push(this);
  38440. }
  38441. }
  38442. }
  38443. // Update VBO
  38444. var offset = 0;
  38445. for (var index = 0; index < this.particles.length; index++) {
  38446. var particle = this.particles[index];
  38447. this._appendParticleVertex(offset++, particle, 0, 0);
  38448. this._appendParticleVertex(offset++, particle, 1, 0);
  38449. this._appendParticleVertex(offset++, particle, 1, 1);
  38450. this._appendParticleVertex(offset++, particle, 0, 1);
  38451. }
  38452. this._vertexBuffer.update(this._vertexData);
  38453. };
  38454. ParticleSystem.prototype.render = function () {
  38455. var effect = this._getEffect();
  38456. // Check
  38457. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  38458. return 0;
  38459. var engine = this._scene.getEngine();
  38460. // Render
  38461. engine.enableEffect(effect);
  38462. engine.setState(false);
  38463. var viewMatrix = this._scene.getViewMatrix();
  38464. effect.setTexture("diffuseSampler", this.particleTexture);
  38465. effect.setMatrix("view", viewMatrix);
  38466. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  38467. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  38468. if (this._scene.clipPlane) {
  38469. var clipPlane = this._scene.clipPlane;
  38470. var invView = viewMatrix.clone();
  38471. invView.invert();
  38472. effect.setMatrix("invView", invView);
  38473. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38474. }
  38475. // VBOs
  38476. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  38477. // Draw order
  38478. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  38479. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38480. }
  38481. else {
  38482. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38483. }
  38484. if (this.forceDepthWrite) {
  38485. engine.setDepthWrite(true);
  38486. }
  38487. engine.draw(true, 0, this.particles.length * 6);
  38488. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38489. return this.particles.length;
  38490. };
  38491. ParticleSystem.prototype.dispose = function () {
  38492. if (this._vertexBuffer) {
  38493. this._vertexBuffer.dispose();
  38494. this._vertexBuffer = null;
  38495. }
  38496. if (this._indexBuffer) {
  38497. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38498. this._indexBuffer = null;
  38499. }
  38500. if (this.particleTexture) {
  38501. this.particleTexture.dispose();
  38502. this.particleTexture = null;
  38503. }
  38504. // Remove from scene
  38505. var index = this._scene.particleSystems.indexOf(this);
  38506. this._scene.particleSystems.splice(index, 1);
  38507. // Callback
  38508. this.onDisposeObservable.notifyObservers(this);
  38509. this.onDisposeObservable.clear();
  38510. };
  38511. // Clone
  38512. ParticleSystem.prototype.clone = function (name, newEmitter) {
  38513. var custom = null;
  38514. var program = null;
  38515. if (this.customShader != null) {
  38516. program = this.customShader;
  38517. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  38518. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  38519. }
  38520. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  38521. result.customShader = program;
  38522. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  38523. if (newEmitter === undefined) {
  38524. newEmitter = this.emitter;
  38525. }
  38526. result.emitter = newEmitter;
  38527. if (this.particleTexture) {
  38528. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  38529. }
  38530. if (!this.preventAutoStart) {
  38531. result.start();
  38532. }
  38533. return result;
  38534. };
  38535. ParticleSystem.prototype.serialize = function () {
  38536. var serializationObject = {};
  38537. serializationObject.name = this.name;
  38538. serializationObject.id = this.id;
  38539. // Emitter
  38540. if (this.emitter.position) {
  38541. serializationObject.emitterId = this.emitter.id;
  38542. }
  38543. else {
  38544. serializationObject.emitter = this.emitter.asArray();
  38545. }
  38546. serializationObject.capacity = this.getCapacity();
  38547. if (this.particleTexture) {
  38548. serializationObject.textureName = this.particleTexture.name;
  38549. }
  38550. // Animations
  38551. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  38552. // Particle system
  38553. serializationObject.minAngularSpeed = this.minAngularSpeed;
  38554. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  38555. serializationObject.minSize = this.minSize;
  38556. serializationObject.maxSize = this.maxSize;
  38557. serializationObject.minEmitPower = this.minEmitPower;
  38558. serializationObject.maxEmitPower = this.maxEmitPower;
  38559. serializationObject.minLifeTime = this.minLifeTime;
  38560. serializationObject.maxLifeTime = this.maxLifeTime;
  38561. serializationObject.emitRate = this.emitRate;
  38562. serializationObject.minEmitBox = this.minEmitBox.asArray();
  38563. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  38564. serializationObject.gravity = this.gravity.asArray();
  38565. serializationObject.direction1 = this.direction1.asArray();
  38566. serializationObject.direction2 = this.direction2.asArray();
  38567. serializationObject.color1 = this.color1.asArray();
  38568. serializationObject.color2 = this.color2.asArray();
  38569. serializationObject.colorDead = this.colorDead.asArray();
  38570. serializationObject.updateSpeed = this.updateSpeed;
  38571. serializationObject.targetStopDuration = this.targetStopDuration;
  38572. serializationObject.textureMask = this.textureMask.asArray();
  38573. serializationObject.blendMode = this.blendMode;
  38574. serializationObject.customShader = this.customShader;
  38575. serializationObject.preventAutoStart = this.preventAutoStart;
  38576. return serializationObject;
  38577. };
  38578. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  38579. var name = parsedParticleSystem.name;
  38580. var custom = null;
  38581. var program = null;
  38582. if (parsedParticleSystem.customShader) {
  38583. program = parsedParticleSystem.customShader;
  38584. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  38585. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  38586. }
  38587. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  38588. particleSystem.customShader = program;
  38589. if (parsedParticleSystem.id) {
  38590. particleSystem.id = parsedParticleSystem.id;
  38591. }
  38592. // Auto start
  38593. if (parsedParticleSystem.preventAutoStart) {
  38594. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  38595. }
  38596. // Texture
  38597. if (parsedParticleSystem.textureName) {
  38598. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  38599. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  38600. }
  38601. // Emitter
  38602. if (parsedParticleSystem.emitterId) {
  38603. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  38604. }
  38605. else {
  38606. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  38607. }
  38608. // Animations
  38609. if (parsedParticleSystem.animations) {
  38610. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  38611. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  38612. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  38613. }
  38614. }
  38615. if (parsedParticleSystem.autoAnimate) {
  38616. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  38617. }
  38618. // Particle system
  38619. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  38620. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  38621. particleSystem.minSize = parsedParticleSystem.minSize;
  38622. particleSystem.maxSize = parsedParticleSystem.maxSize;
  38623. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  38624. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  38625. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  38626. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  38627. particleSystem.emitRate = parsedParticleSystem.emitRate;
  38628. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  38629. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  38630. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  38631. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  38632. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  38633. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  38634. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  38635. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  38636. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  38637. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  38638. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  38639. particleSystem.blendMode = parsedParticleSystem.blendMode;
  38640. if (!particleSystem.preventAutoStart) {
  38641. particleSystem.start();
  38642. }
  38643. return particleSystem;
  38644. };
  38645. return ParticleSystem;
  38646. }());
  38647. // Statics
  38648. ParticleSystem.BLENDMODE_ONEONE = 0;
  38649. ParticleSystem.BLENDMODE_STANDARD = 1;
  38650. BABYLON.ParticleSystem = ParticleSystem;
  38651. })(BABYLON || (BABYLON = {}));
  38652. //# sourceMappingURL=babylon.particleSystem.js.map
  38653. var BABYLON;
  38654. (function (BABYLON) {
  38655. var SolidParticle = (function () {
  38656. /**
  38657. * Creates a Solid Particle object.
  38658. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  38659. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  38660. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  38661. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  38662. * `shapeId` (integer) is the model shape identifier in the SPS.
  38663. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  38664. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  38665. */
  38666. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  38667. this.idx = 0; // particle global index
  38668. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  38669. this.position = BABYLON.Vector3.Zero(); // position
  38670. this.rotation = BABYLON.Vector3.Zero(); // rotation
  38671. this.scaling = BABYLON.Vector3.One(); // scaling
  38672. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  38673. this.velocity = BABYLON.Vector3.Zero(); // velocity
  38674. this.alive = true; // alive
  38675. this.isVisible = true; // visibility
  38676. this._pos = 0; // index of this particle in the global "positions" array
  38677. this.shapeId = 0; // model shape id
  38678. this.idxInShape = 0; // index of the particle in its shape id
  38679. this.idx = particleIndex;
  38680. this._pos = positionIndex;
  38681. this._model = model;
  38682. this.shapeId = shapeId;
  38683. this.idxInShape = idxInShape;
  38684. this._sps = sps;
  38685. if (modelBoundingInfo) {
  38686. this._modelBoundingInfo = modelBoundingInfo;
  38687. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  38688. }
  38689. }
  38690. Object.defineProperty(SolidParticle.prototype, "scale", {
  38691. /**
  38692. * legacy support, changed scale to scaling
  38693. */
  38694. get: function () {
  38695. return this.scaling;
  38696. },
  38697. set: function (scale) {
  38698. this.scaling = scale;
  38699. },
  38700. enumerable: true,
  38701. configurable: true
  38702. });
  38703. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  38704. /**
  38705. * legacy support, changed quaternion to rotationQuaternion
  38706. */
  38707. get: function () {
  38708. return this.rotationQuaternion;
  38709. },
  38710. set: function (q) {
  38711. this.rotationQuaternion = q;
  38712. },
  38713. enumerable: true,
  38714. configurable: true
  38715. });
  38716. /**
  38717. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  38718. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  38719. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  38720. */
  38721. SolidParticle.prototype.intersectsMesh = function (target) {
  38722. if (!this._boundingInfo || !target._boundingInfo) {
  38723. return false;
  38724. }
  38725. if (this._sps._bSphereOnly) {
  38726. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  38727. }
  38728. return this._boundingInfo.intersects(target._boundingInfo, false);
  38729. };
  38730. return SolidParticle;
  38731. }());
  38732. BABYLON.SolidParticle = SolidParticle;
  38733. var ModelShape = (function () {
  38734. /**
  38735. * 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.
  38736. * SPS internal tool, don't use it manually.
  38737. */
  38738. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  38739. this.shapeID = id;
  38740. this._shape = shape;
  38741. this._shapeUV = shapeUV;
  38742. this._positionFunction = posFunction;
  38743. this._vertexFunction = vtxFunction;
  38744. }
  38745. return ModelShape;
  38746. }());
  38747. BABYLON.ModelShape = ModelShape;
  38748. })(BABYLON || (BABYLON = {}));
  38749. //# sourceMappingURL=babylon.solidParticle.js.map
  38750. var BABYLON;
  38751. (function (BABYLON) {
  38752. /**
  38753. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  38754. */
  38755. var SolidParticleSystem = (function () {
  38756. /**
  38757. * Creates a SPS (Solid Particle System) object.
  38758. * `name` (String) is the SPS name, this will be the underlying mesh name.
  38759. * `scene` (Scene) is the scene in which the SPS is added.
  38760. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  38761. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  38762. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  38763. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  38764. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  38765. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  38766. */
  38767. function SolidParticleSystem(name, scene, options) {
  38768. // public members
  38769. /**
  38770. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  38771. * Example : var p = SPS.particles[i];
  38772. */
  38773. this.particles = new Array();
  38774. /**
  38775. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  38776. */
  38777. this.nbParticles = 0;
  38778. /**
  38779. * If the particles must ever face the camera (default false). Useful for planar particles.
  38780. */
  38781. this.billboard = false;
  38782. /**
  38783. * Recompute normals when adding a shape
  38784. */
  38785. this.recomputeNormals = true;
  38786. /**
  38787. * This a counter ofr your own usage. It's not set by any SPS functions.
  38788. */
  38789. this.counter = 0;
  38790. /**
  38791. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  38792. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  38793. */
  38794. this.vars = {};
  38795. this._positions = new Array();
  38796. this._indices = new Array();
  38797. this._normals = new Array();
  38798. this._colors = new Array();
  38799. this._uvs = new Array();
  38800. this._index = 0; // indices index
  38801. this._updatable = true;
  38802. this._pickable = false;
  38803. this._isVisibilityBoxLocked = false;
  38804. this._alwaysVisible = false;
  38805. this._shapeCounter = 0;
  38806. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  38807. this._color = new BABYLON.Color4(0, 0, 0, 0);
  38808. this._computeParticleColor = true;
  38809. this._computeParticleTexture = true;
  38810. this._computeParticleRotation = true;
  38811. this._computeParticleVertex = false;
  38812. this._computeBoundingBox = false;
  38813. this._cam_axisZ = BABYLON.Vector3.Zero();
  38814. this._cam_axisY = BABYLON.Vector3.Zero();
  38815. this._cam_axisX = BABYLON.Vector3.Zero();
  38816. this._axisX = BABYLON.Axis.X;
  38817. this._axisY = BABYLON.Axis.Y;
  38818. this._axisZ = BABYLON.Axis.Z;
  38819. this._camDir = BABYLON.Vector3.Zero();
  38820. this._rotMatrix = new BABYLON.Matrix();
  38821. this._invertMatrix = new BABYLON.Matrix();
  38822. this._rotated = BABYLON.Vector3.Zero();
  38823. this._quaternion = new BABYLON.Quaternion();
  38824. this._vertex = BABYLON.Vector3.Zero();
  38825. this._normal = BABYLON.Vector3.Zero();
  38826. this._yaw = 0.0;
  38827. this._pitch = 0.0;
  38828. this._roll = 0.0;
  38829. this._halfroll = 0.0;
  38830. this._halfpitch = 0.0;
  38831. this._halfyaw = 0.0;
  38832. this._sinRoll = 0.0;
  38833. this._cosRoll = 0.0;
  38834. this._sinPitch = 0.0;
  38835. this._cosPitch = 0.0;
  38836. this._sinYaw = 0.0;
  38837. this._cosYaw = 0.0;
  38838. this._w = 0.0;
  38839. this._mustUnrotateFixedNormals = false;
  38840. this._minimum = BABYLON.Tmp.Vector3[0];
  38841. this._maximum = BABYLON.Tmp.Vector3[1];
  38842. this._scale = BABYLON.Tmp.Vector3[2];
  38843. this._translation = BABYLON.Tmp.Vector3[3];
  38844. this._minBbox = BABYLON.Tmp.Vector3[4];
  38845. this._maxBbox = BABYLON.Tmp.Vector3[5];
  38846. this._particlesIntersect = false;
  38847. this._bSphereOnly = false;
  38848. this._bSphereRadiusFactor = 1.0;
  38849. this.name = name;
  38850. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38851. this._camera = scene.activeCamera;
  38852. this._pickable = options ? options.isPickable : false;
  38853. this._particlesIntersect = options ? options.particleIntersection : false;
  38854. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  38855. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  38856. if (options && options.updatable) {
  38857. this._updatable = options.updatable;
  38858. }
  38859. else {
  38860. this._updatable = true;
  38861. }
  38862. if (this._pickable) {
  38863. this.pickedParticles = [];
  38864. }
  38865. }
  38866. /**
  38867. * Builds the SPS underlying mesh. Returns a standard Mesh.
  38868. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  38869. */
  38870. SolidParticleSystem.prototype.buildMesh = function () {
  38871. if (this.nbParticles === 0) {
  38872. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  38873. this.addShape(triangle, 1);
  38874. triangle.dispose();
  38875. }
  38876. this._positions32 = new Float32Array(this._positions);
  38877. this._uvs32 = new Float32Array(this._uvs);
  38878. this._colors32 = new Float32Array(this._colors);
  38879. if (this.recomputeNormals) {
  38880. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  38881. }
  38882. this._normals32 = new Float32Array(this._normals);
  38883. this._fixedNormal32 = new Float32Array(this._normals);
  38884. if (this._mustUnrotateFixedNormals) {
  38885. this._unrotateFixedNormals();
  38886. }
  38887. var vertexData = new BABYLON.VertexData();
  38888. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  38889. vertexData.indices = this._indices;
  38890. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  38891. if (this._uvs32) {
  38892. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  38893. ;
  38894. }
  38895. if (this._colors32) {
  38896. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  38897. }
  38898. var mesh = new BABYLON.Mesh(this.name, this._scene);
  38899. vertexData.applyToMesh(mesh, this._updatable);
  38900. this.mesh = mesh;
  38901. this.mesh.isPickable = this._pickable;
  38902. // free memory
  38903. this._positions = null;
  38904. this._normals = null;
  38905. this._uvs = null;
  38906. this._colors = null;
  38907. if (!this._updatable) {
  38908. this.particles.length = 0;
  38909. }
  38910. return mesh;
  38911. };
  38912. /**
  38913. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  38914. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  38915. * Thus the particles generated from `digest()` have their property `position` set yet.
  38916. * `mesh` ( Mesh ) is the mesh to be digested
  38917. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  38918. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  38919. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  38920. */
  38921. SolidParticleSystem.prototype.digest = function (mesh, options) {
  38922. var size = (options && options.facetNb) || 1;
  38923. var number = (options && options.number);
  38924. var delta = (options && options.delta) || 0;
  38925. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38926. var meshInd = mesh.getIndices();
  38927. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38928. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38929. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38930. var f = 0; // facet counter
  38931. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  38932. // compute size from number
  38933. if (number) {
  38934. number = (number > totalFacets) ? totalFacets : number;
  38935. size = Math.round(totalFacets / number);
  38936. delta = 0;
  38937. }
  38938. else {
  38939. size = (size > totalFacets) ? totalFacets : size;
  38940. }
  38941. var facetPos = []; // submesh positions
  38942. var facetInd = []; // submesh indices
  38943. var facetUV = []; // submesh UV
  38944. var facetCol = []; // submesh colors
  38945. var barycenter = BABYLON.Tmp.Vector3[0];
  38946. var rand;
  38947. var sizeO = size;
  38948. while (f < totalFacets) {
  38949. size = sizeO + Math.floor((1 + delta) * Math.random());
  38950. if (f > totalFacets - size) {
  38951. size = totalFacets - f;
  38952. }
  38953. // reset temp arrays
  38954. facetPos.length = 0;
  38955. facetInd.length = 0;
  38956. facetUV.length = 0;
  38957. facetCol.length = 0;
  38958. // iterate over "size" facets
  38959. var fi = 0;
  38960. for (var j = f * 3; j < (f + size) * 3; j++) {
  38961. facetInd.push(fi);
  38962. var i = meshInd[j];
  38963. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  38964. if (meshUV) {
  38965. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  38966. }
  38967. if (meshCol) {
  38968. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  38969. }
  38970. fi++;
  38971. }
  38972. // create a model shape for each single particle
  38973. var idx = this.nbParticles;
  38974. var shape = this._posToShape(facetPos);
  38975. var shapeUV = this._uvsToShapeUV(facetUV);
  38976. // compute the barycenter of the shape
  38977. var v;
  38978. for (v = 0; v < shape.length; v++) {
  38979. barycenter.addInPlace(shape[v]);
  38980. }
  38981. barycenter.scaleInPlace(1 / shape.length);
  38982. // shift the shape from its barycenter to the origin
  38983. for (v = 0; v < shape.length; v++) {
  38984. shape[v].subtractInPlace(barycenter);
  38985. }
  38986. var bInfo;
  38987. if (this._particlesIntersect) {
  38988. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  38989. }
  38990. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  38991. // add the particle in the SPS
  38992. var currentPos = this._positions.length;
  38993. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  38994. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  38995. // initialize the particle position
  38996. this.particles[this.nbParticles].position.addInPlace(barycenter);
  38997. this._index += shape.length;
  38998. idx++;
  38999. this.nbParticles++;
  39000. this._shapeCounter++;
  39001. f += size;
  39002. }
  39003. return this;
  39004. };
  39005. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  39006. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  39007. var index = 0;
  39008. var idx = 0;
  39009. for (var p = 0; p < this.particles.length; p++) {
  39010. this._particle = this.particles[p];
  39011. this._shape = this._particle._model._shape;
  39012. if (this._particle.rotationQuaternion) {
  39013. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  39014. }
  39015. else {
  39016. this._yaw = this._particle.rotation.y;
  39017. this._pitch = this._particle.rotation.x;
  39018. this._roll = this._particle.rotation.z;
  39019. this._quaternionRotationYPR();
  39020. }
  39021. this._quaternionToRotationMatrix();
  39022. this._rotMatrix.invertToRef(this._invertMatrix);
  39023. for (var pt = 0; pt < this._shape.length; pt++) {
  39024. idx = index + pt * 3;
  39025. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  39026. this._fixedNormal32[idx] = this._normal.x;
  39027. this._fixedNormal32[idx + 1] = this._normal.y;
  39028. this._fixedNormal32[idx + 2] = this._normal.z;
  39029. }
  39030. index = idx + 3;
  39031. }
  39032. };
  39033. //reset copy
  39034. SolidParticleSystem.prototype._resetCopy = function () {
  39035. this._copy.position.x = 0;
  39036. this._copy.position.y = 0;
  39037. this._copy.position.z = 0;
  39038. this._copy.rotation.x = 0;
  39039. this._copy.rotation.y = 0;
  39040. this._copy.rotation.z = 0;
  39041. this._copy.rotationQuaternion = null;
  39042. this._copy.scaling.x = 1;
  39043. this._copy.scaling.y = 1;
  39044. this._copy.scaling.z = 1;
  39045. this._copy.uvs.x = 0;
  39046. this._copy.uvs.y = 0;
  39047. this._copy.uvs.z = 1;
  39048. this._copy.uvs.w = 1;
  39049. this._copy.color = null;
  39050. };
  39051. // _meshBuilder : inserts the shape model in the global SPS mesh
  39052. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  39053. var i;
  39054. var u = 0;
  39055. var c = 0;
  39056. var n = 0;
  39057. this._resetCopy();
  39058. if (options && options.positionFunction) {
  39059. options.positionFunction(this._copy, idx, idxInShape);
  39060. this._mustUnrotateFixedNormals = true;
  39061. }
  39062. if (this._copy.rotationQuaternion) {
  39063. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  39064. }
  39065. else {
  39066. this._yaw = this._copy.rotation.y;
  39067. this._pitch = this._copy.rotation.x;
  39068. this._roll = this._copy.rotation.z;
  39069. this._quaternionRotationYPR();
  39070. }
  39071. this._quaternionToRotationMatrix();
  39072. for (i = 0; i < shape.length; i++) {
  39073. this._vertex.x = shape[i].x;
  39074. this._vertex.y = shape[i].y;
  39075. this._vertex.z = shape[i].z;
  39076. if (options && options.vertexFunction) {
  39077. options.vertexFunction(this._copy, this._vertex, i);
  39078. }
  39079. this._vertex.x *= this._copy.scaling.x;
  39080. this._vertex.y *= this._copy.scaling.y;
  39081. this._vertex.z *= this._copy.scaling.z;
  39082. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  39083. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  39084. if (meshUV) {
  39085. 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);
  39086. u += 2;
  39087. }
  39088. if (this._copy.color) {
  39089. this._color = this._copy.color;
  39090. }
  39091. else if (meshCol && meshCol[c] !== undefined) {
  39092. this._color.r = meshCol[c];
  39093. this._color.g = meshCol[c + 1];
  39094. this._color.b = meshCol[c + 2];
  39095. this._color.a = meshCol[c + 3];
  39096. }
  39097. else {
  39098. this._color.r = 1;
  39099. this._color.g = 1;
  39100. this._color.b = 1;
  39101. this._color.a = 1;
  39102. }
  39103. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  39104. c += 4;
  39105. if (!this.recomputeNormals && meshNor) {
  39106. this._normal.x = meshNor[n];
  39107. this._normal.y = meshNor[n + 1];
  39108. this._normal.z = meshNor[n + 2];
  39109. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  39110. normals.push(this._normal.x, this._normal.y, this._normal.z);
  39111. n += 3;
  39112. }
  39113. }
  39114. for (i = 0; i < meshInd.length; i++) {
  39115. indices.push(p + meshInd[i]);
  39116. }
  39117. if (this._pickable) {
  39118. var nbfaces = meshInd.length / 3;
  39119. for (i = 0; i < nbfaces; i++) {
  39120. this.pickedParticles.push({ idx: idx, faceId: i });
  39121. }
  39122. }
  39123. return this._copy;
  39124. };
  39125. // returns a shape array from positions array
  39126. SolidParticleSystem.prototype._posToShape = function (positions) {
  39127. var shape = [];
  39128. for (var i = 0; i < positions.length; i += 3) {
  39129. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  39130. }
  39131. return shape;
  39132. };
  39133. // returns a shapeUV array from a Vector4 uvs
  39134. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  39135. var shapeUV = [];
  39136. if (uvs) {
  39137. for (var i = 0; i < uvs.length; i++)
  39138. shapeUV.push(uvs[i]);
  39139. }
  39140. return shapeUV;
  39141. };
  39142. // adds a new particle object in the particles array
  39143. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  39144. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  39145. this.particles.push(sp);
  39146. return sp;
  39147. };
  39148. /**
  39149. * Adds some particles to the SPS from the model shape. Returns the shape id.
  39150. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  39151. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  39152. * `nb` (positive integer) the number of particles to be created from this model
  39153. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  39154. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  39155. */
  39156. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  39157. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39158. var meshInd = mesh.getIndices();
  39159. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39160. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39161. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39162. var bbInfo;
  39163. if (this._particlesIntersect) {
  39164. bbInfo = mesh.getBoundingInfo();
  39165. }
  39166. var shape = this._posToShape(meshPos);
  39167. var shapeUV = this._uvsToShapeUV(meshUV);
  39168. var posfunc = options ? options.positionFunction : null;
  39169. var vtxfunc = options ? options.vertexFunction : null;
  39170. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  39171. // particles
  39172. var sp;
  39173. var currentCopy;
  39174. var idx = this.nbParticles;
  39175. for (var i = 0; i < nb; i++) {
  39176. var currentPos = this._positions.length;
  39177. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  39178. if (this._updatable) {
  39179. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  39180. sp.position.copyFrom(currentCopy.position);
  39181. sp.rotation.copyFrom(currentCopy.rotation);
  39182. if (currentCopy.rotationQuaternion) {
  39183. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  39184. }
  39185. if (currentCopy.color) {
  39186. sp.color.copyFrom(currentCopy.color);
  39187. }
  39188. sp.scaling.copyFrom(currentCopy.scaling);
  39189. sp.uvs.copyFrom(currentCopy.uvs);
  39190. }
  39191. this._index += shape.length;
  39192. idx++;
  39193. }
  39194. this.nbParticles += nb;
  39195. this._shapeCounter++;
  39196. return this._shapeCounter - 1;
  39197. };
  39198. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  39199. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  39200. this._resetCopy();
  39201. if (particle._model._positionFunction) {
  39202. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  39203. }
  39204. if (this._copy.rotationQuaternion) {
  39205. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  39206. }
  39207. else {
  39208. this._yaw = this._copy.rotation.y;
  39209. this._pitch = this._copy.rotation.x;
  39210. this._roll = this._copy.rotation.z;
  39211. this._quaternionRotationYPR();
  39212. }
  39213. this._quaternionToRotationMatrix();
  39214. this._shape = particle._model._shape;
  39215. for (var pt = 0; pt < this._shape.length; pt++) {
  39216. this._vertex.x = this._shape[pt].x;
  39217. this._vertex.y = this._shape[pt].y;
  39218. this._vertex.z = this._shape[pt].z;
  39219. if (particle._model._vertexFunction) {
  39220. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  39221. }
  39222. this._vertex.x *= this._copy.scaling.x;
  39223. this._vertex.y *= this._copy.scaling.y;
  39224. this._vertex.z *= this._copy.scaling.z;
  39225. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  39226. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  39227. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  39228. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  39229. }
  39230. particle.position.x = 0.0;
  39231. particle.position.y = 0.0;
  39232. particle.position.z = 0.0;
  39233. particle.rotation.x = 0.0;
  39234. particle.rotation.y = 0.0;
  39235. particle.rotation.z = 0.0;
  39236. particle.rotationQuaternion = null;
  39237. particle.scaling.x = 1.0;
  39238. particle.scaling.y = 1.0;
  39239. particle.scaling.z = 1.0;
  39240. };
  39241. /**
  39242. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  39243. * Returns the SPS.
  39244. */
  39245. SolidParticleSystem.prototype.rebuildMesh = function () {
  39246. for (var p = 0; p < this.particles.length; p++) {
  39247. this._rebuildParticle(this.particles[p]);
  39248. }
  39249. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  39250. return this;
  39251. };
  39252. /**
  39253. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  39254. * This method calls `updateParticle()` for each particle of the SPS.
  39255. * For an animated SPS, it is usually called within the render loop.
  39256. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  39257. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  39258. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  39259. * Returns the SPS.
  39260. */
  39261. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  39262. if (start === void 0) { start = 0; }
  39263. if (end === void 0) { end = this.nbParticles - 1; }
  39264. if (update === void 0) { update = true; }
  39265. if (!this._updatable) {
  39266. return;
  39267. }
  39268. // custom beforeUpdate
  39269. this.beforeUpdateParticles(start, end, update);
  39270. this._cam_axisX.x = 1.0;
  39271. this._cam_axisX.y = 0.0;
  39272. this._cam_axisX.z = 0.0;
  39273. this._cam_axisY.x = 0.0;
  39274. this._cam_axisY.y = 1.0;
  39275. this._cam_axisY.z = 0.0;
  39276. this._cam_axisZ.x = 0.0;
  39277. this._cam_axisZ.y = 0.0;
  39278. this._cam_axisZ.z = 1.0;
  39279. // if the particles will always face the camera
  39280. if (this.billboard) {
  39281. this.mesh.computeWorldMatrix(true);
  39282. // compute the camera position and un-rotate it by the current mesh rotation
  39283. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  39284. this._quaternionToRotationMatrix();
  39285. this._rotMatrix.invertToRef(this._invertMatrix);
  39286. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  39287. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  39288. this._cam_axisZ.normalize();
  39289. // same for camera up vector extracted from the cam view matrix
  39290. var view = this._camera.getViewMatrix(true);
  39291. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  39292. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  39293. this._cam_axisY.normalize();
  39294. this._cam_axisX.normalize();
  39295. }
  39296. }
  39297. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  39298. var idx = 0; // current position index in the global array positions32
  39299. var index = 0; // position start index in the global array positions32 of the current particle
  39300. var colidx = 0; // current color index in the global array colors32
  39301. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  39302. var uvidx = 0; // current uv index in the global array uvs32
  39303. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  39304. var pt = 0; // current index in the particle model shape
  39305. if (this.mesh.isFacetDataEnabled) {
  39306. this._computeBoundingBox = true;
  39307. }
  39308. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  39309. if (this._computeBoundingBox) {
  39310. if (start == 0 && end == this.nbParticles - 1) {
  39311. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  39312. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  39313. }
  39314. else {
  39315. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  39316. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  39317. }
  39318. }
  39319. // particle loop
  39320. index = this.particles[start]._pos;
  39321. var vpos = (index / 3) | 0;
  39322. colorIndex = vpos * 4;
  39323. uvIndex = vpos * 2;
  39324. for (var p = start; p <= end; p++) {
  39325. this._particle = this.particles[p];
  39326. this._shape = this._particle._model._shape;
  39327. this._shapeUV = this._particle._model._shapeUV;
  39328. // call to custom user function to update the particle properties
  39329. this.updateParticle(this._particle);
  39330. if (this._particle.isVisible) {
  39331. // particle rotation matrix
  39332. if (this.billboard) {
  39333. this._particle.rotation.x = 0.0;
  39334. this._particle.rotation.y = 0.0;
  39335. }
  39336. if (this._computeParticleRotation || this.billboard) {
  39337. if (this._particle.rotationQuaternion) {
  39338. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  39339. }
  39340. else {
  39341. this._yaw = this._particle.rotation.y;
  39342. this._pitch = this._particle.rotation.x;
  39343. this._roll = this._particle.rotation.z;
  39344. this._quaternionRotationYPR();
  39345. }
  39346. this._quaternionToRotationMatrix();
  39347. }
  39348. // particle vertex loop
  39349. for (pt = 0; pt < this._shape.length; pt++) {
  39350. idx = index + pt * 3;
  39351. colidx = colorIndex + pt * 4;
  39352. uvidx = uvIndex + pt * 2;
  39353. this._vertex.x = this._shape[pt].x;
  39354. this._vertex.y = this._shape[pt].y;
  39355. this._vertex.z = this._shape[pt].z;
  39356. if (this._computeParticleVertex) {
  39357. this.updateParticleVertex(this._particle, this._vertex, pt);
  39358. }
  39359. // positions
  39360. this._vertex.x *= this._particle.scaling.x;
  39361. this._vertex.y *= this._particle.scaling.y;
  39362. this._vertex.z *= this._particle.scaling.z;
  39363. 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];
  39364. 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;
  39365. 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;
  39366. 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;
  39367. 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;
  39368. 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;
  39369. 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;
  39370. if (this._computeBoundingBox) {
  39371. if (this._positions32[idx] < this._minimum.x) {
  39372. this._minimum.x = this._positions32[idx];
  39373. }
  39374. if (this._positions32[idx] > this._maximum.x) {
  39375. this._maximum.x = this._positions32[idx];
  39376. }
  39377. if (this._positions32[idx + 1] < this._minimum.y) {
  39378. this._minimum.y = this._positions32[idx + 1];
  39379. }
  39380. if (this._positions32[idx + 1] > this._maximum.y) {
  39381. this._maximum.y = this._positions32[idx + 1];
  39382. }
  39383. if (this._positions32[idx + 2] < this._minimum.z) {
  39384. this._minimum.z = this._positions32[idx + 2];
  39385. }
  39386. if (this._positions32[idx + 2] > this._maximum.z) {
  39387. this._maximum.z = this._positions32[idx + 2];
  39388. }
  39389. }
  39390. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  39391. if (!this._computeParticleVertex) {
  39392. this._normal.x = this._fixedNormal32[idx];
  39393. this._normal.y = this._fixedNormal32[idx + 1];
  39394. this._normal.z = this._fixedNormal32[idx + 2];
  39395. 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]);
  39396. 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]);
  39397. 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]);
  39398. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  39399. 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;
  39400. 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;
  39401. }
  39402. if (this._computeParticleColor) {
  39403. this._colors32[colidx] = this._particle.color.r;
  39404. this._colors32[colidx + 1] = this._particle.color.g;
  39405. this._colors32[colidx + 2] = this._particle.color.b;
  39406. this._colors32[colidx + 3] = this._particle.color.a;
  39407. }
  39408. if (this._computeParticleTexture) {
  39409. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  39410. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  39411. }
  39412. }
  39413. }
  39414. else {
  39415. for (pt = 0; pt < this._shape.length; pt++) {
  39416. idx = index + pt * 3;
  39417. colidx = colorIndex + pt * 4;
  39418. uvidx = uvIndex + pt * 2;
  39419. this._positions32[idx] = this._camera.globalPosition.x;
  39420. this._positions32[idx + 1] = this._camera.globalPosition.y;
  39421. this._positions32[idx + 2] = this._camera.globalPosition.z;
  39422. this._normals32[idx] = 0.0;
  39423. this._normals32[idx + 1] = 0.0;
  39424. this._normals32[idx + 2] = 0.0;
  39425. if (this._computeParticleColor) {
  39426. this._colors32[colidx] = this._particle.color.r;
  39427. this._colors32[colidx + 1] = this._particle.color.g;
  39428. this._colors32[colidx + 2] = this._particle.color.b;
  39429. this._colors32[colidx + 3] = this._particle.color.a;
  39430. }
  39431. if (this._computeParticleTexture) {
  39432. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  39433. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  39434. }
  39435. }
  39436. }
  39437. // if the particle intersections must be computed : update the bbInfo
  39438. if (this._particlesIntersect) {
  39439. var bInfo = this._particle._boundingInfo;
  39440. var bBox = bInfo.boundingBox;
  39441. var bSphere = bInfo.boundingSphere;
  39442. if (!this._bSphereOnly) {
  39443. // place, scale and rotate the particle bbox within the SPS local system, then update it
  39444. for (var b = 0; b < bBox.vectors.length; b++) {
  39445. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  39446. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  39447. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  39448. 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];
  39449. 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;
  39450. 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;
  39451. 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;
  39452. 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;
  39453. 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;
  39454. 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;
  39455. }
  39456. bBox._update(this.mesh._worldMatrix);
  39457. }
  39458. // place and scale the particle bouding sphere in the SPS local system, then update it
  39459. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  39460. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  39461. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  39462. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  39463. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  39464. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  39465. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  39466. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  39467. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  39468. 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));
  39469. bSphere._update(this.mesh._worldMatrix);
  39470. }
  39471. // increment indexes for the next particle
  39472. index = idx + 3;
  39473. colorIndex = colidx + 4;
  39474. uvIndex = uvidx + 2;
  39475. }
  39476. // if the VBO must be updated
  39477. if (update) {
  39478. if (this._computeParticleColor) {
  39479. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  39480. }
  39481. if (this._computeParticleTexture) {
  39482. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  39483. }
  39484. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  39485. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  39486. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  39487. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  39488. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  39489. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  39490. for (var i = 0; i < this._normals32.length; i++) {
  39491. this._fixedNormal32[i] = this._normals32[i];
  39492. }
  39493. }
  39494. if (!this.mesh.areNormalsFrozen) {
  39495. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  39496. }
  39497. }
  39498. }
  39499. if (this._computeBoundingBox) {
  39500. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  39501. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  39502. }
  39503. this.afterUpdateParticles(start, end, update);
  39504. return this;
  39505. };
  39506. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  39507. this._halfroll = this._roll * 0.5;
  39508. this._halfpitch = this._pitch * 0.5;
  39509. this._halfyaw = this._yaw * 0.5;
  39510. this._sinRoll = Math.sin(this._halfroll);
  39511. this._cosRoll = Math.cos(this._halfroll);
  39512. this._sinPitch = Math.sin(this._halfpitch);
  39513. this._cosPitch = Math.cos(this._halfpitch);
  39514. this._sinYaw = Math.sin(this._halfyaw);
  39515. this._cosYaw = Math.cos(this._halfyaw);
  39516. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  39517. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  39518. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  39519. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  39520. };
  39521. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  39522. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  39523. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  39524. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  39525. this._rotMatrix.m[3] = 0;
  39526. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  39527. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  39528. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  39529. this._rotMatrix.m[7] = 0;
  39530. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  39531. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  39532. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  39533. this._rotMatrix.m[11] = 0;
  39534. this._rotMatrix.m[12] = 0;
  39535. this._rotMatrix.m[13] = 0;
  39536. this._rotMatrix.m[14] = 0;
  39537. this._rotMatrix.m[15] = 1.0;
  39538. };
  39539. /**
  39540. * Disposes the SPS.
  39541. * Returns nothing.
  39542. */
  39543. SolidParticleSystem.prototype.dispose = function () {
  39544. this.mesh.dispose();
  39545. this.vars = null;
  39546. // drop references to internal big arrays for the GC
  39547. this._positions = null;
  39548. this._indices = null;
  39549. this._normals = null;
  39550. this._uvs = null;
  39551. this._colors = null;
  39552. this._positions32 = null;
  39553. this._normals32 = null;
  39554. this._fixedNormal32 = null;
  39555. this._uvs32 = null;
  39556. this._colors32 = null;
  39557. this.pickedParticles = null;
  39558. };
  39559. /**
  39560. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  39561. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39562. * Returns the SPS.
  39563. */
  39564. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  39565. if (!this._isVisibilityBoxLocked) {
  39566. this.mesh.refreshBoundingInfo();
  39567. }
  39568. return this;
  39569. };
  39570. /**
  39571. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  39572. * @param size the size (float) of the visibility box
  39573. * note : this doesn't lock the SPS mesh bounding box.
  39574. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39575. */
  39576. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  39577. var vis = size / 2;
  39578. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  39579. };
  39580. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  39581. // getter and setter
  39582. get: function () {
  39583. return this._alwaysVisible;
  39584. },
  39585. /**
  39586. * Sets the SPS as always visible or not
  39587. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39588. */
  39589. set: function (val) {
  39590. this._alwaysVisible = val;
  39591. this.mesh.alwaysSelectAsActiveMesh = val;
  39592. },
  39593. enumerable: true,
  39594. configurable: true
  39595. });
  39596. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  39597. get: function () {
  39598. return this._isVisibilityBoxLocked;
  39599. },
  39600. /**
  39601. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  39602. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39603. */
  39604. set: function (val) {
  39605. this._isVisibilityBoxLocked = val;
  39606. this.mesh.getBoundingInfo().isLocked = val;
  39607. },
  39608. enumerable: true,
  39609. configurable: true
  39610. });
  39611. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  39612. // getters
  39613. get: function () {
  39614. return this._computeParticleRotation;
  39615. },
  39616. // Optimizer setters
  39617. /**
  39618. * Tells to `setParticles()` to compute the particle rotations or not.
  39619. * Default value : true. The SPS is faster when it's set to false.
  39620. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  39621. */
  39622. set: function (val) {
  39623. this._computeParticleRotation = val;
  39624. },
  39625. enumerable: true,
  39626. configurable: true
  39627. });
  39628. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  39629. get: function () {
  39630. return this._computeParticleColor;
  39631. },
  39632. /**
  39633. * Tells to `setParticles()` to compute the particle colors or not.
  39634. * Default value : true. The SPS is faster when it's set to false.
  39635. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  39636. */
  39637. set: function (val) {
  39638. this._computeParticleColor = val;
  39639. },
  39640. enumerable: true,
  39641. configurable: true
  39642. });
  39643. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  39644. get: function () {
  39645. return this._computeParticleTexture;
  39646. },
  39647. /**
  39648. * Tells to `setParticles()` to compute the particle textures or not.
  39649. * Default value : true. The SPS is faster when it's set to false.
  39650. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  39651. */
  39652. set: function (val) {
  39653. this._computeParticleTexture = val;
  39654. },
  39655. enumerable: true,
  39656. configurable: true
  39657. });
  39658. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  39659. get: function () {
  39660. return this._computeParticleVertex;
  39661. },
  39662. /**
  39663. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  39664. * Default value : false. The SPS is faster when it's set to false.
  39665. * Note : the particle custom vertex positions aren't stored values.
  39666. */
  39667. set: function (val) {
  39668. this._computeParticleVertex = val;
  39669. },
  39670. enumerable: true,
  39671. configurable: true
  39672. });
  39673. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  39674. get: function () {
  39675. return this._computeBoundingBox;
  39676. },
  39677. /**
  39678. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  39679. */
  39680. set: function (val) {
  39681. this._computeBoundingBox = val;
  39682. },
  39683. enumerable: true,
  39684. configurable: true
  39685. });
  39686. // =======================================================================
  39687. // Particle behavior logic
  39688. // these following methods may be overwritten by the user to fit his needs
  39689. /**
  39690. * This function does nothing. It may be overwritten to set all the particle first values.
  39691. * The SPS doesn't call this function, you may have to call it by your own.
  39692. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39693. */
  39694. SolidParticleSystem.prototype.initParticles = function () {
  39695. };
  39696. /**
  39697. * This function does nothing. It may be overwritten to recycle a particle.
  39698. * The SPS doesn't call this function, you may have to call it by your own.
  39699. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39700. */
  39701. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  39702. return particle;
  39703. };
  39704. /**
  39705. * Updates a particle : this function should be overwritten by the user.
  39706. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  39707. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39708. * ex : just set a particle position or velocity and recycle conditions
  39709. */
  39710. SolidParticleSystem.prototype.updateParticle = function (particle) {
  39711. return particle;
  39712. };
  39713. /**
  39714. * Updates a vertex of a particle : it can be overwritten by the user.
  39715. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  39716. * @param particle the current particle
  39717. * @param vertex the current index of the current particle
  39718. * @param pt the index of the current vertex in the particle shape
  39719. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  39720. * ex : just set a vertex particle position
  39721. */
  39722. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  39723. return vertex;
  39724. };
  39725. /**
  39726. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  39727. * This does nothing and may be overwritten by the user.
  39728. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39729. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39730. * @param update the boolean update value actually passed to setParticles()
  39731. */
  39732. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  39733. };
  39734. /**
  39735. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  39736. * This will be passed three parameters.
  39737. * This does nothing and may be overwritten by the user.
  39738. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39739. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39740. * @param update the boolean update value actually passed to setParticles()
  39741. */
  39742. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  39743. };
  39744. return SolidParticleSystem;
  39745. }());
  39746. BABYLON.SolidParticleSystem = SolidParticleSystem;
  39747. })(BABYLON || (BABYLON = {}));
  39748. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  39749. /// <reference path="babylon.mesh.ts" />
  39750. var BABYLON;
  39751. (function (BABYLON) {
  39752. var GroundMesh = (function (_super) {
  39753. __extends(GroundMesh, _super);
  39754. function GroundMesh(name, scene) {
  39755. var _this = _super.call(this, name, scene) || this;
  39756. _this.generateOctree = false;
  39757. _this._worldInverse = new BABYLON.Matrix();
  39758. return _this;
  39759. }
  39760. GroundMesh.prototype.getClassName = function () {
  39761. return "GroundMesh";
  39762. };
  39763. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  39764. get: function () {
  39765. return Math.min(this._subdivisionsX, this._subdivisionsY);
  39766. },
  39767. enumerable: true,
  39768. configurable: true
  39769. });
  39770. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  39771. get: function () {
  39772. return this._subdivisionsX;
  39773. },
  39774. enumerable: true,
  39775. configurable: true
  39776. });
  39777. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  39778. get: function () {
  39779. return this._subdivisionsY;
  39780. },
  39781. enumerable: true,
  39782. configurable: true
  39783. });
  39784. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  39785. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  39786. this._subdivisionsX = chunksCount;
  39787. this._subdivisionsY = chunksCount;
  39788. this.subdivide(chunksCount);
  39789. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  39790. };
  39791. /**
  39792. * Returns a height (y) value in the Worl system :
  39793. * the ground altitude at the coordinates (x, z) expressed in the World system.
  39794. * Returns the ground y position if (x, z) are outside the ground surface.
  39795. */
  39796. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  39797. var world = this.getWorldMatrix();
  39798. var invMat = BABYLON.Tmp.Matrix[5];
  39799. world.invertToRef(invMat);
  39800. var tmpVect = BABYLON.Tmp.Vector3[8];
  39801. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  39802. x = tmpVect.x;
  39803. z = tmpVect.z;
  39804. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39805. return this.position.y;
  39806. }
  39807. if (!this._heightQuads || this._heightQuads.length == 0) {
  39808. this._initHeightQuads();
  39809. this._computeHeightQuads();
  39810. }
  39811. var facet = this._getFacetAt(x, z);
  39812. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  39813. // return y in the World system
  39814. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  39815. return tmpVect.y;
  39816. };
  39817. /**
  39818. * Returns a normalized vector (Vector3) orthogonal to the ground
  39819. * at the ground coordinates (x, z) expressed in the World system.
  39820. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  39821. */
  39822. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  39823. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  39824. this.getNormalAtCoordinatesToRef(x, z, normal);
  39825. return normal;
  39826. };
  39827. /**
  39828. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  39829. * at the ground coordinates (x, z) expressed in the World system.
  39830. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  39831. * Returns the GroundMesh.
  39832. */
  39833. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  39834. var world = this.getWorldMatrix();
  39835. var tmpMat = BABYLON.Tmp.Matrix[5];
  39836. world.invertToRef(tmpMat);
  39837. var tmpVect = BABYLON.Tmp.Vector3[8];
  39838. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  39839. x = tmpVect.x;
  39840. z = tmpVect.z;
  39841. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39842. return this;
  39843. }
  39844. if (!this._heightQuads || this._heightQuads.length == 0) {
  39845. this._initHeightQuads();
  39846. this._computeHeightQuads();
  39847. }
  39848. var facet = this._getFacetAt(x, z);
  39849. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  39850. return this;
  39851. };
  39852. /**
  39853. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  39854. * if the ground has been updated.
  39855. * This can be used in the render loop.
  39856. * Returns the GroundMesh.
  39857. */
  39858. GroundMesh.prototype.updateCoordinateHeights = function () {
  39859. if (!this._heightQuads || this._heightQuads.length == 0) {
  39860. this._initHeightQuads();
  39861. }
  39862. this._computeHeightQuads();
  39863. return this;
  39864. };
  39865. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  39866. GroundMesh.prototype._getFacetAt = function (x, z) {
  39867. // retrieve col and row from x, z coordinates in the ground local system
  39868. var subdivisionsX = this._subdivisionsX;
  39869. var subdivisionsY = this._subdivisionsY;
  39870. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  39871. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  39872. var quad = this._heightQuads[row * this._subdivisionsX + col];
  39873. var facet;
  39874. if (z < quad.slope.x * x + quad.slope.y) {
  39875. facet = quad.facet1;
  39876. }
  39877. else {
  39878. facet = quad.facet2;
  39879. }
  39880. return facet;
  39881. };
  39882. // Creates and populates the heightMap array with "facet" elements :
  39883. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  39884. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39885. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39886. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39887. // Returns the GroundMesh.
  39888. GroundMesh.prototype._initHeightQuads = function () {
  39889. var subdivisionsX = this._subdivisionsX;
  39890. var subdivisionsY = this._subdivisionsY;
  39891. this._heightQuads = new Array();
  39892. for (var row = 0; row < subdivisionsY; row++) {
  39893. for (var col = 0; col < subdivisionsX; col++) {
  39894. 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) };
  39895. this._heightQuads[row * subdivisionsX + col] = quad;
  39896. }
  39897. }
  39898. return this;
  39899. };
  39900. // Compute each quad element values and update the the heightMap array :
  39901. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39902. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39903. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39904. // Returns the GroundMesh.
  39905. GroundMesh.prototype._computeHeightQuads = function () {
  39906. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39907. var v1 = BABYLON.Tmp.Vector3[3];
  39908. var v2 = BABYLON.Tmp.Vector3[2];
  39909. var v3 = BABYLON.Tmp.Vector3[1];
  39910. var v4 = BABYLON.Tmp.Vector3[0];
  39911. var v1v2 = BABYLON.Tmp.Vector3[4];
  39912. var v1v3 = BABYLON.Tmp.Vector3[5];
  39913. var v1v4 = BABYLON.Tmp.Vector3[6];
  39914. var norm1 = BABYLON.Tmp.Vector3[7];
  39915. var norm2 = BABYLON.Tmp.Vector3[8];
  39916. var i = 0;
  39917. var j = 0;
  39918. var k = 0;
  39919. var cd = 0; // 2D slope coefficient : z = cd * x + h
  39920. var h = 0;
  39921. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  39922. var d2 = 0;
  39923. var subdivisionsX = this._subdivisionsX;
  39924. var subdivisionsY = this._subdivisionsY;
  39925. for (var row = 0; row < subdivisionsY; row++) {
  39926. for (var col = 0; col < subdivisionsX; col++) {
  39927. i = col * 3;
  39928. j = row * (subdivisionsX + 1) * 3;
  39929. k = (row + 1) * (subdivisionsX + 1) * 3;
  39930. v1.x = positions[j + i];
  39931. v1.y = positions[j + i + 1];
  39932. v1.z = positions[j + i + 2];
  39933. v2.x = positions[j + i + 3];
  39934. v2.y = positions[j + i + 4];
  39935. v2.z = positions[j + i + 5];
  39936. v3.x = positions[k + i];
  39937. v3.y = positions[k + i + 1];
  39938. v3.z = positions[k + i + 2];
  39939. v4.x = positions[k + i + 3];
  39940. v4.y = positions[k + i + 4];
  39941. v4.z = positions[k + i + 5];
  39942. // 2D slope V1V4
  39943. cd = (v4.z - v1.z) / (v4.x - v1.x);
  39944. h = v1.z - cd * v1.x; // v1 belongs to the slope
  39945. // facet equations :
  39946. // we compute each facet normal vector
  39947. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  39948. // we compute the value d by applying the equation to v1 which belongs to the plane
  39949. // then we store the facet equation in a Vector4
  39950. v2.subtractToRef(v1, v1v2);
  39951. v3.subtractToRef(v1, v1v3);
  39952. v4.subtractToRef(v1, v1v4);
  39953. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  39954. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  39955. norm1.normalize();
  39956. norm2.normalize();
  39957. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  39958. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  39959. var quad = this._heightQuads[row * subdivisionsX + col];
  39960. quad.slope.copyFromFloats(cd, h);
  39961. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  39962. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  39963. }
  39964. }
  39965. return this;
  39966. };
  39967. GroundMesh.prototype.serialize = function (serializationObject) {
  39968. _super.prototype.serialize.call(this, serializationObject);
  39969. serializationObject.subdivisionsX = this._subdivisionsX;
  39970. serializationObject.subdivisionsY = this._subdivisionsY;
  39971. serializationObject.minX = this._minX;
  39972. serializationObject.maxX = this._maxX;
  39973. serializationObject.minZ = this._minZ;
  39974. serializationObject.maxZ = this._maxZ;
  39975. serializationObject.width = this._width;
  39976. serializationObject.height = this._height;
  39977. };
  39978. GroundMesh.Parse = function (parsedMesh, scene) {
  39979. var result = new GroundMesh(parsedMesh.name, scene);
  39980. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  39981. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  39982. result._minX = parsedMesh.minX;
  39983. result._maxX = parsedMesh.maxX;
  39984. result._minZ = parsedMesh.minZ;
  39985. result._maxZ = parsedMesh.maxZ;
  39986. result._width = parsedMesh.width;
  39987. result._height = parsedMesh.height;
  39988. return result;
  39989. };
  39990. return GroundMesh;
  39991. }(BABYLON.Mesh));
  39992. BABYLON.GroundMesh = GroundMesh;
  39993. })(BABYLON || (BABYLON = {}));
  39994. //# sourceMappingURL=babylon.groundMesh.js.map
  39995. var BABYLON;
  39996. (function (BABYLON) {
  39997. /**
  39998. * Creates an instance based on a source mesh.
  39999. */
  40000. var InstancedMesh = (function (_super) {
  40001. __extends(InstancedMesh, _super);
  40002. function InstancedMesh(name, source) {
  40003. var _this = _super.call(this, name, source.getScene()) || this;
  40004. source.instances.push(_this);
  40005. _this._sourceMesh = source;
  40006. _this.position.copyFrom(source.position);
  40007. _this.rotation.copyFrom(source.rotation);
  40008. _this.scaling.copyFrom(source.scaling);
  40009. if (source.rotationQuaternion) {
  40010. _this.rotationQuaternion = source.rotationQuaternion.clone();
  40011. }
  40012. _this.infiniteDistance = source.infiniteDistance;
  40013. _this.setPivotMatrix(source.getPivotMatrix());
  40014. _this.refreshBoundingInfo();
  40015. _this._syncSubMeshes();
  40016. return _this;
  40017. }
  40018. /**
  40019. * Returns the string "InstancedMesh".
  40020. */
  40021. InstancedMesh.prototype.getClassName = function () {
  40022. return "InstancedMesh";
  40023. };
  40024. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  40025. // Methods
  40026. get: function () {
  40027. return this._sourceMesh.receiveShadows;
  40028. },
  40029. enumerable: true,
  40030. configurable: true
  40031. });
  40032. Object.defineProperty(InstancedMesh.prototype, "material", {
  40033. get: function () {
  40034. return this._sourceMesh.material;
  40035. },
  40036. enumerable: true,
  40037. configurable: true
  40038. });
  40039. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  40040. get: function () {
  40041. return this._sourceMesh.visibility;
  40042. },
  40043. enumerable: true,
  40044. configurable: true
  40045. });
  40046. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  40047. get: function () {
  40048. return this._sourceMesh.skeleton;
  40049. },
  40050. enumerable: true,
  40051. configurable: true
  40052. });
  40053. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  40054. get: function () {
  40055. return this._sourceMesh.renderingGroupId;
  40056. },
  40057. enumerable: true,
  40058. configurable: true
  40059. });
  40060. /**
  40061. * Returns the total number of vertices (integer).
  40062. */
  40063. InstancedMesh.prototype.getTotalVertices = function () {
  40064. return this._sourceMesh.getTotalVertices();
  40065. };
  40066. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  40067. get: function () {
  40068. return this._sourceMesh;
  40069. },
  40070. enumerable: true,
  40071. configurable: true
  40072. });
  40073. /**
  40074. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  40075. */
  40076. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  40077. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  40078. };
  40079. /**
  40080. * Sets the vertex data of the mesh geometry for the requested `kind`.
  40081. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  40082. * The `data` are either a numeric array either a Float32Array.
  40083. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  40084. * 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).
  40085. * Note that a new underlying VertexBuffer object is created each call.
  40086. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  40087. *
  40088. * Possible `kind` values :
  40089. * - BABYLON.VertexBuffer.PositionKind
  40090. * - BABYLON.VertexBuffer.UVKind
  40091. * - BABYLON.VertexBuffer.UV2Kind
  40092. * - BABYLON.VertexBuffer.UV3Kind
  40093. * - BABYLON.VertexBuffer.UV4Kind
  40094. * - BABYLON.VertexBuffer.UV5Kind
  40095. * - BABYLON.VertexBuffer.UV6Kind
  40096. * - BABYLON.VertexBuffer.ColorKind
  40097. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40098. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40099. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40100. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40101. *
  40102. * Returns the Mesh.
  40103. */
  40104. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40105. if (this.sourceMesh) {
  40106. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  40107. }
  40108. return this.sourceMesh;
  40109. };
  40110. /**
  40111. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  40112. * If the mesh has no geometry, it is simply returned as it is.
  40113. * The `data` are either a numeric array either a Float32Array.
  40114. * No new underlying VertexBuffer object is created.
  40115. * 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.
  40116. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  40117. *
  40118. * Possible `kind` values :
  40119. * - BABYLON.VertexBuffer.PositionKind
  40120. * - BABYLON.VertexBuffer.UVKind
  40121. * - BABYLON.VertexBuffer.UV2Kind
  40122. * - BABYLON.VertexBuffer.UV3Kind
  40123. * - BABYLON.VertexBuffer.UV4Kind
  40124. * - BABYLON.VertexBuffer.UV5Kind
  40125. * - BABYLON.VertexBuffer.UV6Kind
  40126. * - BABYLON.VertexBuffer.ColorKind
  40127. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40128. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40129. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40130. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40131. *
  40132. * Returns the Mesh.
  40133. */
  40134. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  40135. if (this.sourceMesh) {
  40136. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  40137. }
  40138. return this.sourceMesh;
  40139. };
  40140. /**
  40141. * Sets the mesh indices.
  40142. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  40143. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  40144. * This method creates a new index buffer each call.
  40145. * Returns the Mesh.
  40146. */
  40147. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  40148. if (this.sourceMesh) {
  40149. this.sourceMesh.setIndices(indices, totalVertices);
  40150. }
  40151. return this.sourceMesh;
  40152. };
  40153. /**
  40154. * Boolean : True if the mesh owns the requested kind of data.
  40155. */
  40156. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  40157. return this._sourceMesh.isVerticesDataPresent(kind);
  40158. };
  40159. /**
  40160. * Returns an array of indices (IndicesArray).
  40161. */
  40162. InstancedMesh.prototype.getIndices = function () {
  40163. return this._sourceMesh.getIndices();
  40164. };
  40165. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  40166. get: function () {
  40167. return this._sourceMesh._positions;
  40168. },
  40169. enumerable: true,
  40170. configurable: true
  40171. });
  40172. /**
  40173. * Sets a new updated BoundingInfo to the mesh.
  40174. * Returns the mesh.
  40175. */
  40176. InstancedMesh.prototype.refreshBoundingInfo = function () {
  40177. var meshBB = this._sourceMesh.getBoundingInfo();
  40178. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  40179. this._updateBoundingInfo();
  40180. return this;
  40181. };
  40182. InstancedMesh.prototype._preActivate = function () {
  40183. if (this._currentLOD) {
  40184. this._currentLOD._preActivate();
  40185. }
  40186. return this;
  40187. };
  40188. InstancedMesh.prototype._activate = function (renderId) {
  40189. if (this._currentLOD) {
  40190. this._currentLOD._registerInstanceForRenderId(this, renderId);
  40191. }
  40192. return this;
  40193. };
  40194. /**
  40195. * Returns the current associated LOD AbstractMesh.
  40196. */
  40197. InstancedMesh.prototype.getLOD = function (camera) {
  40198. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  40199. if (this._currentLOD === this.sourceMesh) {
  40200. return this;
  40201. }
  40202. return this._currentLOD;
  40203. };
  40204. InstancedMesh.prototype._syncSubMeshes = function () {
  40205. this.releaseSubMeshes();
  40206. if (this._sourceMesh.subMeshes) {
  40207. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  40208. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  40209. }
  40210. }
  40211. return this;
  40212. };
  40213. InstancedMesh.prototype._generatePointsArray = function () {
  40214. return this._sourceMesh._generatePointsArray();
  40215. };
  40216. /**
  40217. * Creates a new InstancedMesh from the current mesh.
  40218. * - name (string) : the cloned mesh name
  40219. * - newParent (optional Node) : the optional Node to parent the clone to.
  40220. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  40221. *
  40222. * Returns the clone.
  40223. */
  40224. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40225. var result = this._sourceMesh.createInstance(name);
  40226. // Deep copy
  40227. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  40228. // Bounding info
  40229. this.refreshBoundingInfo();
  40230. // Parent
  40231. if (newParent) {
  40232. result.parent = newParent;
  40233. }
  40234. if (!doNotCloneChildren) {
  40235. // Children
  40236. for (var index = 0; index < this.getScene().meshes.length; index++) {
  40237. var mesh = this.getScene().meshes[index];
  40238. if (mesh.parent === this) {
  40239. mesh.clone(mesh.name, result);
  40240. }
  40241. }
  40242. }
  40243. result.computeWorldMatrix(true);
  40244. return result;
  40245. };
  40246. /**
  40247. * Disposes the InstancedMesh.
  40248. * Returns nothing.
  40249. */
  40250. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  40251. // Remove from mesh
  40252. var index = this._sourceMesh.instances.indexOf(this);
  40253. this._sourceMesh.instances.splice(index, 1);
  40254. _super.prototype.dispose.call(this, doNotRecurse);
  40255. };
  40256. return InstancedMesh;
  40257. }(BABYLON.AbstractMesh));
  40258. BABYLON.InstancedMesh = InstancedMesh;
  40259. })(BABYLON || (BABYLON = {}));
  40260. //# sourceMappingURL=babylon.instancedMesh.js.map
  40261. /// <reference path="babylon.mesh.ts" />
  40262. var BABYLON;
  40263. (function (BABYLON) {
  40264. var LinesMesh = (function (_super) {
  40265. __extends(LinesMesh, _super);
  40266. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  40267. if (parent === void 0) { parent = null; }
  40268. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  40269. _this.useVertexColor = useVertexColor;
  40270. _this.color = new BABYLON.Color3(1, 1, 1);
  40271. _this.alpha = 1;
  40272. if (source) {
  40273. _this.color = source.color.clone();
  40274. _this.alpha = source.alpha;
  40275. _this.useVertexColor = source.useVertexColor;
  40276. }
  40277. _this._intersectionThreshold = 0.1;
  40278. var options = {
  40279. attributes: [BABYLON.VertexBuffer.PositionKind],
  40280. uniforms: ["world", "viewProjection"],
  40281. needAlphaBlending: false,
  40282. };
  40283. if (!useVertexColor) {
  40284. options.uniforms.push("color");
  40285. options.needAlphaBlending = true;
  40286. }
  40287. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  40288. return _this;
  40289. }
  40290. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  40291. /**
  40292. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40293. * This margin is expressed in world space coordinates, so its value may vary.
  40294. * Default value is 0.1
  40295. * @returns the intersection Threshold value.
  40296. */
  40297. get: function () {
  40298. return this._intersectionThreshold;
  40299. },
  40300. /**
  40301. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40302. * This margin is expressed in world space coordinates, so its value may vary.
  40303. * @param value the new threshold to apply
  40304. */
  40305. set: function (value) {
  40306. if (this._intersectionThreshold === value) {
  40307. return;
  40308. }
  40309. this._intersectionThreshold = value;
  40310. if (this.geometry) {
  40311. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  40312. }
  40313. },
  40314. enumerable: true,
  40315. configurable: true
  40316. });
  40317. /**
  40318. * Returns the string "LineMesh"
  40319. */
  40320. LinesMesh.prototype.getClassName = function () {
  40321. return "LinesMesh";
  40322. };
  40323. Object.defineProperty(LinesMesh.prototype, "material", {
  40324. get: function () {
  40325. return this._colorShader;
  40326. },
  40327. enumerable: true,
  40328. configurable: true
  40329. });
  40330. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  40331. get: function () {
  40332. return false;
  40333. },
  40334. enumerable: true,
  40335. configurable: true
  40336. });
  40337. LinesMesh.prototype.createInstance = function (name) {
  40338. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  40339. return null;
  40340. };
  40341. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  40342. // VBOs
  40343. this._geometry._bind(this._colorShader.getEffect());
  40344. // Color
  40345. if (!this.useVertexColor) {
  40346. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  40347. }
  40348. return this;
  40349. };
  40350. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  40351. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  40352. return this;
  40353. }
  40354. var engine = this.getScene().getEngine();
  40355. // Draw order
  40356. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  40357. return this;
  40358. };
  40359. LinesMesh.prototype.dispose = function (doNotRecurse) {
  40360. this._colorShader.dispose();
  40361. _super.prototype.dispose.call(this, doNotRecurse);
  40362. };
  40363. /**
  40364. * Returns a new LineMesh object cloned from the current one.
  40365. */
  40366. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40367. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  40368. };
  40369. return LinesMesh;
  40370. }(BABYLON.Mesh));
  40371. BABYLON.LinesMesh = LinesMesh;
  40372. })(BABYLON || (BABYLON = {}));
  40373. //# sourceMappingURL=babylon.linesMesh.js.map
  40374. var BABYLON;
  40375. (function (BABYLON) {
  40376. var ShaderMaterial = (function (_super) {
  40377. __extends(ShaderMaterial, _super);
  40378. function ShaderMaterial(name, scene, shaderPath, options) {
  40379. var _this = _super.call(this, name, scene) || this;
  40380. _this._textures = {};
  40381. _this._textureArrays = {};
  40382. _this._floats = {};
  40383. _this._floatsArrays = {};
  40384. _this._colors3 = {};
  40385. _this._colors4 = {};
  40386. _this._vectors2 = {};
  40387. _this._vectors3 = {};
  40388. _this._vectors4 = {};
  40389. _this._matrices = {};
  40390. _this._matrices3x3 = {};
  40391. _this._matrices2x2 = {};
  40392. _this._vectors3Arrays = {};
  40393. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40394. _this._shaderPath = shaderPath;
  40395. options.needAlphaBlending = options.needAlphaBlending || false;
  40396. options.needAlphaTesting = options.needAlphaTesting || false;
  40397. options.attributes = options.attributes || ["position", "normal", "uv"];
  40398. options.uniforms = options.uniforms || ["worldViewProjection"];
  40399. options.uniformBuffers = options.uniformBuffers || [];
  40400. options.samplers = options.samplers || [];
  40401. options.defines = options.defines || [];
  40402. _this._options = options;
  40403. return _this;
  40404. }
  40405. ShaderMaterial.prototype.getClassName = function () {
  40406. return "ShaderMaterial";
  40407. };
  40408. ShaderMaterial.prototype.needAlphaBlending = function () {
  40409. return this._options.needAlphaBlending;
  40410. };
  40411. ShaderMaterial.prototype.needAlphaTesting = function () {
  40412. return this._options.needAlphaTesting;
  40413. };
  40414. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40415. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40416. this._options.uniforms.push(uniformName);
  40417. }
  40418. };
  40419. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40420. if (this._options.samplers.indexOf(name) === -1) {
  40421. this._options.samplers.push(name);
  40422. }
  40423. this._textures[name] = texture;
  40424. return this;
  40425. };
  40426. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40427. if (this._options.samplers.indexOf(name) === -1) {
  40428. this._options.samplers.push(name);
  40429. }
  40430. this._checkUniform(name);
  40431. this._textureArrays[name] = textures;
  40432. return this;
  40433. };
  40434. ShaderMaterial.prototype.setFloat = function (name, value) {
  40435. this._checkUniform(name);
  40436. this._floats[name] = value;
  40437. return this;
  40438. };
  40439. ShaderMaterial.prototype.setFloats = function (name, value) {
  40440. this._checkUniform(name);
  40441. this._floatsArrays[name] = value;
  40442. return this;
  40443. };
  40444. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40445. this._checkUniform(name);
  40446. this._colors3[name] = value;
  40447. return this;
  40448. };
  40449. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40450. this._checkUniform(name);
  40451. this._colors4[name] = value;
  40452. return this;
  40453. };
  40454. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40455. this._checkUniform(name);
  40456. this._vectors2[name] = value;
  40457. return this;
  40458. };
  40459. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40460. this._checkUniform(name);
  40461. this._vectors3[name] = value;
  40462. return this;
  40463. };
  40464. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40465. this._checkUniform(name);
  40466. this._vectors4[name] = value;
  40467. return this;
  40468. };
  40469. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40470. this._checkUniform(name);
  40471. this._matrices[name] = value;
  40472. return this;
  40473. };
  40474. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40475. this._checkUniform(name);
  40476. this._matrices3x3[name] = value;
  40477. return this;
  40478. };
  40479. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40480. this._checkUniform(name);
  40481. this._matrices2x2[name] = value;
  40482. return this;
  40483. };
  40484. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40485. this._checkUniform(name);
  40486. this._vectors3Arrays[name] = value;
  40487. return this;
  40488. };
  40489. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40490. if (!mesh) {
  40491. return true;
  40492. }
  40493. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40494. return false;
  40495. }
  40496. return false;
  40497. };
  40498. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40499. var scene = this.getScene();
  40500. var engine = scene.getEngine();
  40501. if (!this.checkReadyOnEveryCall) {
  40502. if (this._renderId === scene.getRenderId()) {
  40503. if (this._checkCache(scene, mesh, useInstances)) {
  40504. return true;
  40505. }
  40506. }
  40507. }
  40508. // Instances
  40509. var defines = [];
  40510. var attribs = [];
  40511. var fallbacks = new BABYLON.EffectFallbacks();
  40512. if (useInstances) {
  40513. defines.push("#define INSTANCES");
  40514. }
  40515. for (var index = 0; index < this._options.defines.length; index++) {
  40516. defines.push(this._options.defines[index]);
  40517. }
  40518. for (var index = 0; index < this._options.attributes.length; index++) {
  40519. attribs.push(this._options.attributes[index]);
  40520. }
  40521. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40522. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40523. defines.push("#define VERTEXCOLOR");
  40524. }
  40525. // Bones
  40526. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40527. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40528. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40529. if (mesh.numBoneInfluencers > 4) {
  40530. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40531. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40532. }
  40533. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40534. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40535. fallbacks.addCPUSkinningFallback(0, mesh);
  40536. if (this._options.uniforms.indexOf("mBones") === -1) {
  40537. this._options.uniforms.push("mBones");
  40538. }
  40539. }
  40540. else {
  40541. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40542. }
  40543. // Textures
  40544. for (var name in this._textures) {
  40545. if (!this._textures[name].isReady()) {
  40546. return false;
  40547. }
  40548. }
  40549. // Alpha test
  40550. if (engine.getAlphaTesting()) {
  40551. defines.push("#define ALPHATEST");
  40552. }
  40553. var previousEffect = this._effect;
  40554. var join = defines.join("\n");
  40555. this._effect = engine.createEffect(this._shaderPath, {
  40556. attributes: attribs,
  40557. uniformsNames: this._options.uniforms,
  40558. uniformBuffersNames: this._options.uniformBuffers,
  40559. samplers: this._options.samplers,
  40560. defines: join,
  40561. fallbacks: fallbacks,
  40562. onCompiled: this.onCompiled,
  40563. onError: this.onError
  40564. }, engine);
  40565. if (!this._effect.isReady()) {
  40566. return false;
  40567. }
  40568. if (previousEffect !== this._effect) {
  40569. scene.resetCachedMaterial();
  40570. }
  40571. this._renderId = scene.getRenderId();
  40572. return true;
  40573. };
  40574. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40575. var scene = this.getScene();
  40576. if (this._options.uniforms.indexOf("world") !== -1) {
  40577. this._effect.setMatrix("world", world);
  40578. }
  40579. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40580. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40581. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40582. }
  40583. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40584. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40585. }
  40586. };
  40587. ShaderMaterial.prototype.bind = function (world, mesh) {
  40588. // Std values
  40589. this.bindOnlyWorldMatrix(world);
  40590. if (this.getScene().getCachedMaterial() !== this) {
  40591. if (this._options.uniforms.indexOf("view") !== -1) {
  40592. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40593. }
  40594. if (this._options.uniforms.indexOf("projection") !== -1) {
  40595. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40596. }
  40597. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40598. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40599. }
  40600. // Bones
  40601. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40602. var name;
  40603. // Texture
  40604. for (name in this._textures) {
  40605. this._effect.setTexture(name, this._textures[name]);
  40606. }
  40607. // Texture arrays
  40608. for (name in this._textureArrays) {
  40609. this._effect.setTextureArray(name, this._textureArrays[name]);
  40610. }
  40611. // Float
  40612. for (name in this._floats) {
  40613. this._effect.setFloat(name, this._floats[name]);
  40614. }
  40615. // Float s
  40616. for (name in this._floatsArrays) {
  40617. this._effect.setArray(name, this._floatsArrays[name]);
  40618. }
  40619. // Color3
  40620. for (name in this._colors3) {
  40621. this._effect.setColor3(name, this._colors3[name]);
  40622. }
  40623. // Color4
  40624. for (name in this._colors4) {
  40625. var color = this._colors4[name];
  40626. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40627. }
  40628. // Vector2
  40629. for (name in this._vectors2) {
  40630. this._effect.setVector2(name, this._vectors2[name]);
  40631. }
  40632. // Vector3
  40633. for (name in this._vectors3) {
  40634. this._effect.setVector3(name, this._vectors3[name]);
  40635. }
  40636. // Vector4
  40637. for (name in this._vectors4) {
  40638. this._effect.setVector4(name, this._vectors4[name]);
  40639. }
  40640. // Matrix
  40641. for (name in this._matrices) {
  40642. this._effect.setMatrix(name, this._matrices[name]);
  40643. }
  40644. // Matrix 3x3
  40645. for (name in this._matrices3x3) {
  40646. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40647. }
  40648. // Matrix 2x2
  40649. for (name in this._matrices2x2) {
  40650. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40651. }
  40652. // Vector3Array
  40653. for (name in this._vectors3Arrays) {
  40654. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40655. }
  40656. }
  40657. this._afterBind(mesh);
  40658. };
  40659. ShaderMaterial.prototype.getActiveTextures = function () {
  40660. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40661. for (var name in this._textures) {
  40662. activeTextures.push(this._textures[name]);
  40663. }
  40664. for (var name in this._textureArrays) {
  40665. var array = this._textureArrays[name];
  40666. for (var index = 0; index < array.length; index++) {
  40667. activeTextures.push(array[index]);
  40668. }
  40669. }
  40670. return activeTextures;
  40671. };
  40672. ShaderMaterial.prototype.clone = function (name) {
  40673. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40674. return newShaderMaterial;
  40675. };
  40676. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40677. if (forceDisposeTextures) {
  40678. var name;
  40679. for (name in this._textures) {
  40680. this._textures[name].dispose();
  40681. }
  40682. for (name in this._textureArrays) {
  40683. var array = this._textureArrays[name];
  40684. for (var index = 0; index < array.length; index++) {
  40685. array[index].dispose();
  40686. }
  40687. }
  40688. }
  40689. this._textures = {};
  40690. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40691. };
  40692. ShaderMaterial.prototype.serialize = function () {
  40693. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40694. serializationObject.customType = "BABYLON.ShaderMaterial";
  40695. serializationObject.options = this._options;
  40696. serializationObject.shaderPath = this._shaderPath;
  40697. var name;
  40698. // Texture
  40699. serializationObject.textures = {};
  40700. for (name in this._textures) {
  40701. serializationObject.textures[name] = this._textures[name].serialize();
  40702. }
  40703. // Texture arrays
  40704. serializationObject.textureArrays = {};
  40705. for (name in this._textureArrays) {
  40706. serializationObject.textureArrays[name] = [];
  40707. var array = this._textureArrays[name];
  40708. for (var index = 0; index < array.length; index++) {
  40709. serializationObject.textureArrays[name].push(array[index].serialize());
  40710. }
  40711. }
  40712. // Float
  40713. serializationObject.floats = {};
  40714. for (name in this._floats) {
  40715. serializationObject.floats[name] = this._floats[name];
  40716. }
  40717. // Float s
  40718. serializationObject.floatArrays = {};
  40719. for (name in this._floatsArrays) {
  40720. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40721. }
  40722. // Color3
  40723. serializationObject.colors3 = {};
  40724. for (name in this._colors3) {
  40725. serializationObject.colors3[name] = this._colors3[name].asArray();
  40726. }
  40727. // Color4
  40728. serializationObject.colors4 = {};
  40729. for (name in this._colors4) {
  40730. serializationObject.colors4[name] = this._colors4[name].asArray();
  40731. }
  40732. // Vector2
  40733. serializationObject.vectors2 = {};
  40734. for (name in this._vectors2) {
  40735. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40736. }
  40737. // Vector3
  40738. serializationObject.vectors3 = {};
  40739. for (name in this._vectors3) {
  40740. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40741. }
  40742. // Vector4
  40743. serializationObject.vectors4 = {};
  40744. for (name in this._vectors4) {
  40745. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40746. }
  40747. // Matrix
  40748. serializationObject.matrices = {};
  40749. for (name in this._matrices) {
  40750. serializationObject.matrices[name] = this._matrices[name].asArray();
  40751. }
  40752. // Matrix 3x3
  40753. serializationObject.matrices3x3 = {};
  40754. for (name in this._matrices3x3) {
  40755. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40756. }
  40757. // Matrix 2x2
  40758. serializationObject.matrices2x2 = {};
  40759. for (name in this._matrices2x2) {
  40760. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40761. }
  40762. // Vector3Array
  40763. serializationObject.vectors3Arrays = {};
  40764. for (name in this._vectors3Arrays) {
  40765. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40766. }
  40767. return serializationObject;
  40768. };
  40769. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40770. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40771. var name;
  40772. // Texture
  40773. for (name in source.textures) {
  40774. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40775. }
  40776. // Texture arrays
  40777. for (name in source.textureArrays) {
  40778. var array = source.textureArrays[name];
  40779. var textureArray = new Array();
  40780. for (var index = 0; index < array.length; index++) {
  40781. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40782. }
  40783. material.setTextureArray(name, textureArray);
  40784. }
  40785. // Float
  40786. for (name in source.floats) {
  40787. material.setFloat(name, source.floats[name]);
  40788. }
  40789. // Float s
  40790. for (name in source.floatsArrays) {
  40791. material.setFloats(name, source.floatsArrays[name]);
  40792. }
  40793. // Color3
  40794. for (name in source.colors3) {
  40795. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40796. }
  40797. // Color4
  40798. for (name in source.colors4) {
  40799. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40800. }
  40801. // Vector2
  40802. for (name in source.vectors2) {
  40803. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40804. }
  40805. // Vector3
  40806. for (name in source.vectors3) {
  40807. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40808. }
  40809. // Vector4
  40810. for (name in source.vectors4) {
  40811. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40812. }
  40813. // Matrix
  40814. for (name in source.matrices) {
  40815. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40816. }
  40817. // Matrix 3x3
  40818. for (name in source.matrices3x3) {
  40819. material.setMatrix3x3(name, source.matrices3x3[name]);
  40820. }
  40821. // Matrix 2x2
  40822. for (name in source.matrices2x2) {
  40823. material.setMatrix2x2(name, source.matrices2x2[name]);
  40824. }
  40825. // Vector3Array
  40826. for (name in source.vectors3Arrays) {
  40827. material.setArray3(name, source.vectors3Arrays[name]);
  40828. }
  40829. return material;
  40830. };
  40831. return ShaderMaterial;
  40832. }(BABYLON.Material));
  40833. BABYLON.ShaderMaterial = ShaderMaterial;
  40834. })(BABYLON || (BABYLON = {}));
  40835. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40836. var BABYLON;
  40837. (function (BABYLON) {
  40838. var MeshBuilder = (function () {
  40839. function MeshBuilder() {
  40840. }
  40841. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  40842. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  40843. return BABYLON.Mesh.DOUBLESIDE;
  40844. }
  40845. if (orientation === undefined || orientation === null) {
  40846. return BABYLON.Mesh.FRONTSIDE;
  40847. }
  40848. return orientation;
  40849. };
  40850. /**
  40851. * Creates a box mesh.
  40852. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  40853. * The parameter `size` sets the size (float) of each box side (default 1).
  40854. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  40855. * 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).
  40856. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40857. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40858. * 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).
  40859. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40860. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40861. */
  40862. MeshBuilder.CreateBox = function (name, options, scene) {
  40863. var box = new BABYLON.Mesh(name, scene);
  40864. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40865. box.sideOrientation = options.sideOrientation;
  40866. var vertexData = BABYLON.VertexData.CreateBox(options);
  40867. vertexData.applyToMesh(box, options.updatable);
  40868. return box;
  40869. };
  40870. /**
  40871. * Creates a sphere mesh.
  40872. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  40873. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  40874. * 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`).
  40875. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  40876. * 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
  40877. * 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).
  40878. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40879. * 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).
  40880. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40881. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40882. */
  40883. MeshBuilder.CreateSphere = function (name, options, scene) {
  40884. var sphere = new BABYLON.Mesh(name, scene);
  40885. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40886. sphere.sideOrientation = options.sideOrientation;
  40887. var vertexData = BABYLON.VertexData.CreateSphere(options);
  40888. vertexData.applyToMesh(sphere, options.updatable);
  40889. return sphere;
  40890. };
  40891. /**
  40892. * Creates a plane polygonal mesh. By default, this is a disc.
  40893. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  40894. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  40895. * 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.
  40896. * 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
  40897. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40898. * 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).
  40899. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40900. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40901. */
  40902. MeshBuilder.CreateDisc = function (name, options, scene) {
  40903. var disc = new BABYLON.Mesh(name, scene);
  40904. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40905. disc.sideOrientation = options.sideOrientation;
  40906. var vertexData = BABYLON.VertexData.CreateDisc(options);
  40907. vertexData.applyToMesh(disc, options.updatable);
  40908. return disc;
  40909. };
  40910. /**
  40911. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  40912. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  40913. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  40914. * 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`).
  40915. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  40916. * 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.
  40917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40918. * 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).
  40919. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40921. */
  40922. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  40923. var sphere = new BABYLON.Mesh(name, scene);
  40924. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40925. sphere.sideOrientation = options.sideOrientation;
  40926. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  40927. vertexData.applyToMesh(sphere, options.updatable);
  40928. return sphere;
  40929. };
  40930. ;
  40931. /**
  40932. * Creates a ribbon mesh.
  40933. * 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.
  40934. *
  40935. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  40936. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  40937. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  40938. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  40939. * 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.
  40940. * 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.
  40941. * 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
  40942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40943. * 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).
  40944. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40945. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40946. * 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.
  40947. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  40948. * 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
  40949. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  40950. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  40951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40952. */
  40953. MeshBuilder.CreateRibbon = function (name, options, scene) {
  40954. var pathArray = options.pathArray;
  40955. var closeArray = options.closeArray;
  40956. var closePath = options.closePath;
  40957. var offset = options.offset;
  40958. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40959. var instance = options.instance;
  40960. var updatable = options.updatable;
  40961. if (instance) {
  40962. // positionFunction : ribbon case
  40963. // only pathArray and sideOrientation parameters are taken into account for positions update
  40964. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  40965. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  40966. var positionFunction = function (positions) {
  40967. var minlg = pathArray[0].length;
  40968. var i = 0;
  40969. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  40970. for (var si = 1; si <= ns; si++) {
  40971. for (var p = 0; p < pathArray.length; p++) {
  40972. var path = pathArray[p];
  40973. var l = path.length;
  40974. minlg = (minlg < l) ? minlg : l;
  40975. var j = 0;
  40976. while (j < minlg) {
  40977. positions[i] = path[j].x;
  40978. positions[i + 1] = path[j].y;
  40979. positions[i + 2] = path[j].z;
  40980. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  40981. BABYLON.Tmp.Vector3[0].x = path[j].x;
  40982. }
  40983. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  40984. BABYLON.Tmp.Vector3[1].x = path[j].x;
  40985. }
  40986. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  40987. BABYLON.Tmp.Vector3[0].y = path[j].y;
  40988. }
  40989. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  40990. BABYLON.Tmp.Vector3[1].y = path[j].y;
  40991. }
  40992. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  40993. BABYLON.Tmp.Vector3[0].z = path[j].z;
  40994. }
  40995. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  40996. BABYLON.Tmp.Vector3[1].z = path[j].z;
  40997. }
  40998. j++;
  40999. i += 3;
  41000. }
  41001. if (instance._closePath) {
  41002. positions[i] = path[0].x;
  41003. positions[i + 1] = path[0].y;
  41004. positions[i + 2] = path[0].z;
  41005. i += 3;
  41006. }
  41007. }
  41008. }
  41009. };
  41010. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41011. positionFunction(positions);
  41012. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  41013. instance._boundingInfo.update(instance._worldMatrix);
  41014. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  41015. if (options.colors) {
  41016. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41017. for (var c = 0; c < options.colors.length; c++) {
  41018. colors[c * 4] = options.colors[c].r;
  41019. colors[c * 4 + 1] = options.colors[c].g;
  41020. colors[c * 4 + 2] = options.colors[c].b;
  41021. colors[c * 4 + 3] = options.colors[c].a;
  41022. }
  41023. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  41024. }
  41025. if (options.uvs) {
  41026. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41027. for (var i = 0; i < options.uvs.length; i++) {
  41028. uvs[i * 2] = options.uvs[i].x;
  41029. uvs[i * 2 + 1] = options.uvs[i].y;
  41030. }
  41031. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  41032. }
  41033. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  41034. var indices = instance.getIndices();
  41035. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41036. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  41037. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  41038. if (instance._closePath) {
  41039. var indexFirst = 0;
  41040. var indexLast = 0;
  41041. for (var p = 0; p < pathArray.length; p++) {
  41042. indexFirst = instance._idx[p] * 3;
  41043. if (p + 1 < pathArray.length) {
  41044. indexLast = (instance._idx[p + 1] - 1) * 3;
  41045. }
  41046. else {
  41047. indexLast = normals.length - 3;
  41048. }
  41049. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  41050. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  41051. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  41052. normals[indexLast] = normals[indexFirst];
  41053. normals[indexLast + 1] = normals[indexFirst + 1];
  41054. normals[indexLast + 2] = normals[indexFirst + 2];
  41055. }
  41056. }
  41057. if (!(instance.areNormalsFrozen)) {
  41058. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  41059. }
  41060. }
  41061. return instance;
  41062. }
  41063. else {
  41064. var ribbon = new BABYLON.Mesh(name, scene);
  41065. ribbon.sideOrientation = sideOrientation;
  41066. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  41067. if (closePath) {
  41068. ribbon._idx = vertexData._idx;
  41069. }
  41070. ribbon._closePath = closePath;
  41071. ribbon._closeArray = closeArray;
  41072. vertexData.applyToMesh(ribbon, updatable);
  41073. return ribbon;
  41074. }
  41075. };
  41076. /**
  41077. * Creates a cylinder or a cone mesh.
  41078. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  41079. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  41080. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  41081. * 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.
  41082. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  41083. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  41084. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  41085. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  41086. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  41087. * 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).
  41088. * 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
  41089. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  41090. * 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
  41091. * 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.
  41092. * If `enclose` is false, a ring surface is one element.
  41093. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  41094. * 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
  41095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41096. * 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).
  41097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41099. */
  41100. MeshBuilder.CreateCylinder = function (name, options, scene) {
  41101. var cylinder = new BABYLON.Mesh(name, scene);
  41102. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41103. cylinder.sideOrientation = options.sideOrientation;
  41104. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  41105. vertexData.applyToMesh(cylinder, options.updatable);
  41106. return cylinder;
  41107. };
  41108. /**
  41109. * Creates a torus mesh.
  41110. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  41111. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  41112. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  41113. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  41114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41115. * 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).
  41116. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41117. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41118. */
  41119. MeshBuilder.CreateTorus = function (name, options, scene) {
  41120. var torus = new BABYLON.Mesh(name, scene);
  41121. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41122. torus.sideOrientation = options.sideOrientation;
  41123. var vertexData = BABYLON.VertexData.CreateTorus(options);
  41124. vertexData.applyToMesh(torus, options.updatable);
  41125. return torus;
  41126. };
  41127. /**
  41128. * Creates a torus knot mesh.
  41129. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  41130. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  41131. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  41132. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  41133. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  41134. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41135. * 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).
  41136. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41138. */
  41139. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  41140. var torusKnot = new BABYLON.Mesh(name, scene);
  41141. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41142. torusKnot.sideOrientation = options.sideOrientation;
  41143. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  41144. vertexData.applyToMesh(torusKnot, options.updatable);
  41145. return torusKnot;
  41146. };
  41147. /**
  41148. * Creates a line system mesh.
  41149. * A line system is a pool of many lines gathered in a single mesh.
  41150. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  41151. * 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.
  41152. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  41153. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  41154. * 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
  41155. * 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
  41156. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  41157. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41158. */
  41159. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  41160. var instance = options.instance;
  41161. var lines = options.lines;
  41162. if (instance) {
  41163. var positionFunction = function (positions) {
  41164. var i = 0;
  41165. for (var l = 0; l < lines.length; l++) {
  41166. var points = lines[l];
  41167. for (var p = 0; p < points.length; p++) {
  41168. positions[i] = points[p].x;
  41169. positions[i + 1] = points[p].y;
  41170. positions[i + 2] = points[p].z;
  41171. i += 3;
  41172. }
  41173. }
  41174. };
  41175. instance.updateMeshPositions(positionFunction, false);
  41176. return instance;
  41177. }
  41178. // line system creation
  41179. var lineSystem = new BABYLON.LinesMesh(name, scene);
  41180. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  41181. vertexData.applyToMesh(lineSystem, options.updatable);
  41182. return lineSystem;
  41183. };
  41184. /**
  41185. * Creates a line mesh.
  41186. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  41187. * 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.
  41188. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  41189. * The parameter `points` is an array successive Vector3.
  41190. * 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
  41191. * When updating an instance, remember that only point positions can change, not the number of points.
  41192. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41193. */
  41194. MeshBuilder.CreateLines = function (name, options, scene) {
  41195. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  41196. return lines;
  41197. };
  41198. /**
  41199. * Creates a dashed line mesh.
  41200. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  41201. * 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.
  41202. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  41203. * The parameter `points` is an array successive Vector3.
  41204. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  41205. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  41206. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  41207. * 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
  41208. * When updating an instance, remember that only point positions can change, not the number of points.
  41209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41210. */
  41211. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  41212. var points = options.points;
  41213. var instance = options.instance;
  41214. var gapSize = options.gapSize;
  41215. var dashNb = options.dashNb;
  41216. var dashSize = options.dashSize;
  41217. if (instance) {
  41218. var positionFunction = function (positions) {
  41219. var curvect = BABYLON.Vector3.Zero();
  41220. var nbSeg = positions.length / 6;
  41221. var lg = 0;
  41222. var nb = 0;
  41223. var shft = 0;
  41224. var dashshft = 0;
  41225. var curshft = 0;
  41226. var p = 0;
  41227. var i = 0;
  41228. var j = 0;
  41229. for (i = 0; i < points.length - 1; i++) {
  41230. points[i + 1].subtractToRef(points[i], curvect);
  41231. lg += curvect.length();
  41232. }
  41233. shft = lg / nbSeg;
  41234. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  41235. for (i = 0; i < points.length - 1; i++) {
  41236. points[i + 1].subtractToRef(points[i], curvect);
  41237. nb = Math.floor(curvect.length() / shft);
  41238. curvect.normalize();
  41239. j = 0;
  41240. while (j < nb && p < positions.length) {
  41241. curshft = shft * j;
  41242. positions[p] = points[i].x + curshft * curvect.x;
  41243. positions[p + 1] = points[i].y + curshft * curvect.y;
  41244. positions[p + 2] = points[i].z + curshft * curvect.z;
  41245. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  41246. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  41247. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  41248. p += 6;
  41249. j++;
  41250. }
  41251. }
  41252. while (p < positions.length) {
  41253. positions[p] = points[i].x;
  41254. positions[p + 1] = points[i].y;
  41255. positions[p + 2] = points[i].z;
  41256. p += 3;
  41257. }
  41258. };
  41259. instance.updateMeshPositions(positionFunction, false);
  41260. return instance;
  41261. }
  41262. // dashed lines creation
  41263. var dashedLines = new BABYLON.LinesMesh(name, scene);
  41264. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  41265. vertexData.applyToMesh(dashedLines, options.updatable);
  41266. dashedLines.dashSize = dashSize;
  41267. dashedLines.gapSize = gapSize;
  41268. return dashedLines;
  41269. };
  41270. /**
  41271. * Creates an extruded shape mesh.
  41272. * 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.
  41273. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  41274. *
  41275. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  41276. * 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
  41277. * extruded along the Z axis.
  41278. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  41279. * 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.
  41280. * The parameter `scale` (float, default 1) is the value to scale the shape.
  41281. * 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
  41282. * 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
  41283. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  41284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41285. * 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).
  41286. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41287. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41288. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41289. */
  41290. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  41291. var path = options.path;
  41292. var shape = options.shape;
  41293. var scale = options.scale || 1;
  41294. var rotation = options.rotation || 0;
  41295. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  41296. var updatable = options.updatable;
  41297. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41298. var instance = options.instance;
  41299. var invertUV = options.invertUV || false;
  41300. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  41301. };
  41302. /**
  41303. * Creates an custom extruded shape mesh.
  41304. * 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.
  41305. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  41306. *
  41307. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  41308. * 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
  41309. * extruded along the Z axis.
  41310. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  41311. * 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
  41312. * and the distance of this point from the begining of the path :
  41313. * ```javascript
  41314. * var rotationFunction = function(i, distance) {
  41315. * // do things
  41316. * return rotationValue; }
  41317. * ```
  41318. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  41319. * 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
  41320. * and the distance of this point from the begining of the path :
  41321. * ```javascript
  41322. * var scaleFunction = function(i, distance) {
  41323. * // do things
  41324. * return scaleValue;}
  41325. * ```
  41326. * It must returns a float value that will be the scale value applied to the shape on each path point.
  41327. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  41328. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  41329. * 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
  41330. * 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
  41331. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  41332. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41333. * 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).
  41334. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41335. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41336. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41337. */
  41338. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  41339. var path = options.path;
  41340. var shape = options.shape;
  41341. var scaleFunction = options.scaleFunction || (function () { return 1; });
  41342. var rotationFunction = options.rotationFunction || (function () { return 0; });
  41343. var ribbonCloseArray = options.ribbonCloseArray || false;
  41344. var ribbonClosePath = options.ribbonClosePath || false;
  41345. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  41346. var updatable = options.updatable;
  41347. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41348. var instance = options.instance;
  41349. var invertUV = options.invertUV || false;
  41350. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  41351. };
  41352. /**
  41353. * Creates lathe mesh.
  41354. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  41355. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  41356. *
  41357. * 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
  41358. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  41359. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  41360. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  41361. * 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.
  41362. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  41363. * 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
  41364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41365. * 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).
  41366. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41367. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41369. */
  41370. MeshBuilder.CreateLathe = function (name, options, scene) {
  41371. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  41372. var closed = (options.closed === undefined) ? true : options.closed;
  41373. var shape = options.shape;
  41374. var radius = options.radius || 1;
  41375. var tessellation = options.tessellation || 64;
  41376. var updatable = options.updatable;
  41377. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41378. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  41379. var pi2 = Math.PI * 2;
  41380. var paths = new Array();
  41381. var invertUV = options.invertUV || false;
  41382. var i = 0;
  41383. var p = 0;
  41384. var step = pi2 / tessellation * arc;
  41385. var rotated;
  41386. var path = new Array();
  41387. ;
  41388. for (i = 0; i <= tessellation; i++) {
  41389. var path = [];
  41390. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  41391. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  41392. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  41393. }
  41394. for (p = 0; p < shape.length; p++) {
  41395. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  41396. path.push(rotated);
  41397. }
  41398. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  41399. 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));
  41400. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  41401. }
  41402. paths.push(path);
  41403. }
  41404. // lathe ribbon
  41405. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  41406. return lathe;
  41407. };
  41408. /**
  41409. * Creates a plane mesh.
  41410. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  41411. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  41412. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  41413. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  41414. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41415. * 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).
  41416. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41418. */
  41419. MeshBuilder.CreatePlane = function (name, options, scene) {
  41420. var plane = new BABYLON.Mesh(name, scene);
  41421. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41422. plane.sideOrientation = options.sideOrientation;
  41423. var vertexData = BABYLON.VertexData.CreatePlane(options);
  41424. vertexData.applyToMesh(plane, options.updatable);
  41425. if (options.sourcePlane) {
  41426. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  41427. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  41428. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  41429. plane.rotate(vectorProduct, product);
  41430. }
  41431. return plane;
  41432. };
  41433. /**
  41434. * Creates a ground mesh.
  41435. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  41436. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  41437. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  41438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41439. */
  41440. MeshBuilder.CreateGround = function (name, options, scene) {
  41441. var ground = new BABYLON.GroundMesh(name, scene);
  41442. ground._setReady(false);
  41443. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  41444. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  41445. ground._width = options.width || 1;
  41446. ground._height = options.height || 1;
  41447. ground._maxX = ground._width / 2;
  41448. ground._maxZ = ground._height / 2;
  41449. ground._minX = -ground._maxX;
  41450. ground._minZ = -ground._maxZ;
  41451. var vertexData = BABYLON.VertexData.CreateGround(options);
  41452. vertexData.applyToMesh(ground, options.updatable);
  41453. ground._setReady(true);
  41454. return ground;
  41455. };
  41456. /**
  41457. * Creates a tiled ground mesh.
  41458. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  41459. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  41460. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  41461. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  41462. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  41463. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  41464. * numbers of subdivisions on the ground width and height of each tile.
  41465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41466. */
  41467. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  41468. var tiledGround = new BABYLON.Mesh(name, scene);
  41469. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  41470. vertexData.applyToMesh(tiledGround, options.updatable);
  41471. return tiledGround;
  41472. };
  41473. /**
  41474. * Creates a ground mesh from a height map.
  41475. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  41476. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  41477. * The parameter `url` sets the URL of the height map image resource.
  41478. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  41479. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  41480. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  41481. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  41482. * 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.
  41483. * 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).
  41484. * This function is passed the newly built mesh :
  41485. * ```javascript
  41486. * function(mesh) { // do things
  41487. * return; }
  41488. * ```
  41489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41490. */
  41491. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  41492. var width = options.width || 10.0;
  41493. var height = options.height || 10.0;
  41494. var subdivisions = options.subdivisions || 1 | 0;
  41495. var minHeight = options.minHeight || 0.0;
  41496. var maxHeight = options.maxHeight || 10.0;
  41497. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  41498. var updatable = options.updatable;
  41499. var onReady = options.onReady;
  41500. var ground = new BABYLON.GroundMesh(name, scene);
  41501. ground._subdivisionsX = subdivisions;
  41502. ground._subdivisionsY = subdivisions;
  41503. ground._width = width;
  41504. ground._height = height;
  41505. ground._maxX = ground._width / 2.0;
  41506. ground._maxZ = ground._height / 2.0;
  41507. ground._minX = -ground._maxX;
  41508. ground._minZ = -ground._maxZ;
  41509. ground._setReady(false);
  41510. var onload = function (img) {
  41511. // Getting height map data
  41512. var canvas = document.createElement("canvas");
  41513. var context = canvas.getContext("2d");
  41514. var bufferWidth = img.width;
  41515. var bufferHeight = img.height;
  41516. canvas.width = bufferWidth;
  41517. canvas.height = bufferHeight;
  41518. context.drawImage(img, 0, 0);
  41519. // Create VertexData from map data
  41520. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  41521. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  41522. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  41523. width: width, height: height,
  41524. subdivisions: subdivisions,
  41525. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  41526. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  41527. });
  41528. vertexData.applyToMesh(ground, updatable);
  41529. ground._setReady(true);
  41530. //execute ready callback, if set
  41531. if (onReady) {
  41532. onReady(ground);
  41533. }
  41534. };
  41535. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  41536. return ground;
  41537. };
  41538. /**
  41539. * Creates a polygon mesh.
  41540. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  41541. * 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.
  41542. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  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. * Remember you can only change the shape positions, not their number when updating a polygon.
  41546. */
  41547. MeshBuilder.CreatePolygon = function (name, options, scene) {
  41548. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41549. var shape = options.shape;
  41550. var holes = options.holes || [];
  41551. var depth = options.depth || 0;
  41552. var contours = [];
  41553. var hole = [];
  41554. for (var i = 0; i < shape.length; i++) {
  41555. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  41556. }
  41557. var epsilon = 0.00000001;
  41558. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  41559. contours.pop();
  41560. }
  41561. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  41562. for (var hNb = 0; hNb < holes.length; hNb++) {
  41563. hole = [];
  41564. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  41565. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  41566. }
  41567. polygonTriangulation.addHole(hole);
  41568. }
  41569. var polygon = polygonTriangulation.build(options.updatable, depth);
  41570. polygon.sideOrientation = options.sideOrientation;
  41571. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  41572. vertexData.applyToMesh(polygon, options.updatable);
  41573. return polygon;
  41574. };
  41575. ;
  41576. /**
  41577. * Creates an extruded polygon mesh, with depth in the Y direction.
  41578. * 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).
  41579. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  41580. */
  41581. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  41582. return MeshBuilder.CreatePolygon(name, options, scene);
  41583. };
  41584. ;
  41585. /**
  41586. * Creates a tube mesh.
  41587. * 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.
  41588. *
  41589. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  41590. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  41591. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  41592. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  41593. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  41594. * 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.
  41595. * It must return a radius value (positive float) :
  41596. * ```javascript
  41597. * var radiusFunction = function(i, distance) {
  41598. * // do things
  41599. * return radius; }
  41600. * ```
  41601. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  41602. * 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
  41603. * 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
  41604. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41605. * 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).
  41606. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41607. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41609. */
  41610. MeshBuilder.CreateTube = function (name, options, scene) {
  41611. var path = options.path;
  41612. var radius = options.radius || 1.0;
  41613. var tessellation = options.tessellation || 64 | 0;
  41614. var radiusFunction = options.radiusFunction;
  41615. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  41616. var invertUV = options.invertUV || false;
  41617. var updatable = options.updatable;
  41618. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41619. var instance = options.instance;
  41620. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  41621. // tube geometry
  41622. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  41623. var tangents = path3D.getTangents();
  41624. var normals = path3D.getNormals();
  41625. var distances = path3D.getDistances();
  41626. var pi2 = Math.PI * 2;
  41627. var step = pi2 / tessellation * arc;
  41628. var returnRadius = function () { return radius; };
  41629. var radiusFunctionFinal = radiusFunction || returnRadius;
  41630. var circlePath;
  41631. var rad;
  41632. var normal;
  41633. var rotated;
  41634. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41635. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41636. for (var i = 0; i < path.length; i++) {
  41637. rad = radiusFunctionFinal(i, distances[i]); // current radius
  41638. circlePath = Array(); // current circle array
  41639. normal = normals[i]; // current normal
  41640. for (var t = 0; t < tessellation; t++) {
  41641. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  41642. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  41643. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  41644. rotated.scaleInPlace(rad).addInPlace(path[i]);
  41645. circlePath[t] = rotated;
  41646. }
  41647. circlePaths[index] = circlePath;
  41648. index++;
  41649. }
  41650. // cap
  41651. var capPath = function (nbPoints, pathIndex) {
  41652. var pointCap = Array();
  41653. for (var i = 0; i < nbPoints; i++) {
  41654. pointCap.push(path[pathIndex]);
  41655. }
  41656. return pointCap;
  41657. };
  41658. switch (cap) {
  41659. case BABYLON.Mesh.NO_CAP:
  41660. break;
  41661. case BABYLON.Mesh.CAP_START:
  41662. circlePaths[0] = capPath(tessellation, 0);
  41663. circlePaths[1] = circlePaths[2].slice(0);
  41664. break;
  41665. case BABYLON.Mesh.CAP_END:
  41666. circlePaths[index] = circlePaths[index - 1].slice(0);
  41667. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41668. break;
  41669. case BABYLON.Mesh.CAP_ALL:
  41670. circlePaths[0] = capPath(tessellation, 0);
  41671. circlePaths[1] = circlePaths[2].slice(0);
  41672. circlePaths[index] = circlePaths[index - 1].slice(0);
  41673. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41674. break;
  41675. default:
  41676. break;
  41677. }
  41678. return circlePaths;
  41679. };
  41680. var path3D;
  41681. var pathArray;
  41682. if (instance) {
  41683. var arc = options.arc || instance.arc;
  41684. path3D = (instance.path3D).update(path);
  41685. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  41686. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  41687. instance.path3D = path3D;
  41688. instance.pathArray = pathArray;
  41689. instance.arc = arc;
  41690. return instance;
  41691. }
  41692. // tube creation
  41693. path3D = new BABYLON.Path3D(path);
  41694. var newPathArray = new Array();
  41695. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41696. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  41697. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  41698. tube.pathArray = pathArray;
  41699. tube.path3D = path3D;
  41700. tube.tessellation = tessellation;
  41701. tube.cap = cap;
  41702. tube.arc = options.arc;
  41703. return tube;
  41704. };
  41705. /**
  41706. * Creates a polyhedron mesh.
  41707. *
  41708. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  41709. * 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
  41710. * to choose the wanted type.
  41711. * The parameter `size` (positive float, default 1) sets the polygon size.
  41712. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  41713. * 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`.
  41714. * 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
  41715. * 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)`).
  41716. * 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
  41717. * 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.
  41718. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41719. * 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).
  41720. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41722. */
  41723. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  41724. var polyhedron = new BABYLON.Mesh(name, scene);
  41725. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41726. polyhedron.sideOrientation = options.sideOrientation;
  41727. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  41728. vertexData.applyToMesh(polyhedron, options.updatable);
  41729. return polyhedron;
  41730. };
  41731. /**
  41732. * Creates a decal mesh.
  41733. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  41734. * 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.
  41735. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  41736. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  41737. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  41738. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  41739. */
  41740. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  41741. var indices = sourceMesh.getIndices();
  41742. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41743. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41744. var position = options.position || BABYLON.Vector3.Zero();
  41745. var normal = options.normal || BABYLON.Vector3.Up();
  41746. var size = options.size || BABYLON.Vector3.One();
  41747. var angle = options.angle || 0;
  41748. // Getting correct rotation
  41749. if (!normal) {
  41750. var target = new BABYLON.Vector3(0, 0, 1);
  41751. var camera = sourceMesh.getScene().activeCamera;
  41752. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  41753. normal = camera.globalPosition.subtract(cameraWorldTarget);
  41754. }
  41755. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  41756. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  41757. var pitch = Math.atan2(normal.y, len);
  41758. // Matrix
  41759. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  41760. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  41761. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  41762. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  41763. var vertexData = new BABYLON.VertexData();
  41764. vertexData.indices = [];
  41765. vertexData.positions = [];
  41766. vertexData.normals = [];
  41767. vertexData.uvs = [];
  41768. var currentVertexDataIndex = 0;
  41769. var extractDecalVector3 = function (indexId) {
  41770. var vertexId = indices[indexId];
  41771. var result = new BABYLON.PositionNormalVertex();
  41772. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  41773. // Send vector to decal local world
  41774. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  41775. // Get normal
  41776. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  41777. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  41778. return result;
  41779. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  41780. var clip = function (vertices, axis) {
  41781. if (vertices.length === 0) {
  41782. return vertices;
  41783. }
  41784. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  41785. var clipVertices = function (v0, v1) {
  41786. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  41787. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  41788. };
  41789. var result = new Array();
  41790. for (var index = 0; index < vertices.length; index += 3) {
  41791. var v1Out;
  41792. var v2Out;
  41793. var v3Out;
  41794. var total = 0;
  41795. var nV1, nV2, nV3, nV4;
  41796. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  41797. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  41798. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  41799. v1Out = d1 > 0;
  41800. v2Out = d2 > 0;
  41801. v3Out = d3 > 0;
  41802. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  41803. switch (total) {
  41804. case 0:
  41805. result.push(vertices[index]);
  41806. result.push(vertices[index + 1]);
  41807. result.push(vertices[index + 2]);
  41808. break;
  41809. case 1:
  41810. if (v1Out) {
  41811. nV1 = vertices[index + 1];
  41812. nV2 = vertices[index + 2];
  41813. nV3 = clipVertices(vertices[index], nV1);
  41814. nV4 = clipVertices(vertices[index], nV2);
  41815. }
  41816. if (v2Out) {
  41817. nV1 = vertices[index];
  41818. nV2 = vertices[index + 2];
  41819. nV3 = clipVertices(vertices[index + 1], nV1);
  41820. nV4 = clipVertices(vertices[index + 1], nV2);
  41821. result.push(nV3);
  41822. result.push(nV2.clone());
  41823. result.push(nV1.clone());
  41824. result.push(nV2.clone());
  41825. result.push(nV3.clone());
  41826. result.push(nV4);
  41827. break;
  41828. }
  41829. if (v3Out) {
  41830. nV1 = vertices[index];
  41831. nV2 = vertices[index + 1];
  41832. nV3 = clipVertices(vertices[index + 2], nV1);
  41833. nV4 = clipVertices(vertices[index + 2], nV2);
  41834. }
  41835. result.push(nV1.clone());
  41836. result.push(nV2.clone());
  41837. result.push(nV3);
  41838. result.push(nV4);
  41839. result.push(nV3.clone());
  41840. result.push(nV2.clone());
  41841. break;
  41842. case 2:
  41843. if (!v1Out) {
  41844. nV1 = vertices[index].clone();
  41845. nV2 = clipVertices(nV1, vertices[index + 1]);
  41846. nV3 = clipVertices(nV1, vertices[index + 2]);
  41847. result.push(nV1);
  41848. result.push(nV2);
  41849. result.push(nV3);
  41850. }
  41851. if (!v2Out) {
  41852. nV1 = vertices[index + 1].clone();
  41853. nV2 = clipVertices(nV1, vertices[index + 2]);
  41854. nV3 = clipVertices(nV1, vertices[index]);
  41855. result.push(nV1);
  41856. result.push(nV2);
  41857. result.push(nV3);
  41858. }
  41859. if (!v3Out) {
  41860. nV1 = vertices[index + 2].clone();
  41861. nV2 = clipVertices(nV1, vertices[index]);
  41862. nV3 = clipVertices(nV1, vertices[index + 1]);
  41863. result.push(nV1);
  41864. result.push(nV2);
  41865. result.push(nV3);
  41866. }
  41867. break;
  41868. case 3:
  41869. break;
  41870. }
  41871. }
  41872. return result;
  41873. };
  41874. for (var index = 0; index < indices.length; index += 3) {
  41875. var faceVertices = new Array();
  41876. faceVertices.push(extractDecalVector3(index));
  41877. faceVertices.push(extractDecalVector3(index + 1));
  41878. faceVertices.push(extractDecalVector3(index + 2));
  41879. // Clip
  41880. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  41881. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  41882. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  41883. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  41884. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  41885. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  41886. if (faceVertices.length === 0) {
  41887. continue;
  41888. }
  41889. // Add UVs and get back to world
  41890. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  41891. var vertex = faceVertices[vIndex];
  41892. //TODO check for Int32Array | Uint32Array | Uint16Array
  41893. vertexData.indices.push(currentVertexDataIndex);
  41894. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  41895. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  41896. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  41897. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  41898. currentVertexDataIndex++;
  41899. }
  41900. }
  41901. // Return mesh
  41902. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  41903. vertexData.applyToMesh(decal);
  41904. decal.position = position.clone();
  41905. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  41906. return decal;
  41907. };
  41908. // Privates
  41909. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  41910. // extrusion geometry
  41911. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  41912. var tangents = path3D.getTangents();
  41913. var normals = path3D.getNormals();
  41914. var binormals = path3D.getBinormals();
  41915. var distances = path3D.getDistances();
  41916. var angle = 0;
  41917. var returnScale = function () { return scale; };
  41918. var returnRotation = function () { return rotation; };
  41919. var rotate = custom ? rotateFunction : returnRotation;
  41920. var scl = custom ? scaleFunction : returnScale;
  41921. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41922. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41923. for (var i = 0; i < curve.length; i++) {
  41924. var shapePath = new Array();
  41925. var angleStep = rotate(i, distances[i]);
  41926. var scaleRatio = scl(i, distances[i]);
  41927. for (var p = 0; p < shape.length; p++) {
  41928. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  41929. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  41930. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  41931. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  41932. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  41933. shapePath[p] = rotated;
  41934. }
  41935. shapePaths[index] = shapePath;
  41936. angle += angleStep;
  41937. index++;
  41938. }
  41939. // cap
  41940. var capPath = function (shapePath) {
  41941. var pointCap = Array();
  41942. var barycenter = BABYLON.Vector3.Zero();
  41943. var i;
  41944. for (i = 0; i < shapePath.length; i++) {
  41945. barycenter.addInPlace(shapePath[i]);
  41946. }
  41947. barycenter.scaleInPlace(1.0 / shapePath.length);
  41948. for (i = 0; i < shapePath.length; i++) {
  41949. pointCap.push(barycenter);
  41950. }
  41951. return pointCap;
  41952. };
  41953. switch (cap) {
  41954. case BABYLON.Mesh.NO_CAP:
  41955. break;
  41956. case BABYLON.Mesh.CAP_START:
  41957. shapePaths[0] = capPath(shapePaths[2]);
  41958. shapePaths[1] = shapePaths[2];
  41959. break;
  41960. case BABYLON.Mesh.CAP_END:
  41961. shapePaths[index] = shapePaths[index - 1];
  41962. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41963. break;
  41964. case BABYLON.Mesh.CAP_ALL:
  41965. shapePaths[0] = capPath(shapePaths[2]);
  41966. shapePaths[1] = shapePaths[2];
  41967. shapePaths[index] = shapePaths[index - 1];
  41968. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41969. break;
  41970. default:
  41971. break;
  41972. }
  41973. return shapePaths;
  41974. };
  41975. var path3D;
  41976. var pathArray;
  41977. if (instance) {
  41978. path3D = (instance.path3D).update(curve);
  41979. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  41980. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  41981. return instance;
  41982. }
  41983. // extruded shape creation
  41984. path3D = new BABYLON.Path3D(curve);
  41985. var newShapePaths = new Array();
  41986. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41987. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  41988. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  41989. extrudedGeneric.pathArray = pathArray;
  41990. extrudedGeneric.path3D = path3D;
  41991. extrudedGeneric.cap = cap;
  41992. return extrudedGeneric;
  41993. };
  41994. return MeshBuilder;
  41995. }());
  41996. BABYLON.MeshBuilder = MeshBuilder;
  41997. })(BABYLON || (BABYLON = {}));
  41998. //# sourceMappingURL=babylon.meshBuilder.js.map
  41999. var BABYLON;
  42000. (function (BABYLON) {
  42001. var AudioEngine = (function () {
  42002. function AudioEngine() {
  42003. this._audioContext = null;
  42004. this._audioContextInitialized = false;
  42005. this.canUseWebAudio = false;
  42006. this.WarnedWebAudioUnsupported = false;
  42007. this.unlocked = false;
  42008. this.isMP3supported = false;
  42009. this.isOGGsupported = false;
  42010. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  42011. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  42012. this.canUseWebAudio = true;
  42013. }
  42014. var audioElem = document.createElement('audio');
  42015. try {
  42016. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  42017. this.isMP3supported = true;
  42018. }
  42019. }
  42020. catch (e) {
  42021. // protect error during capability check.
  42022. }
  42023. try {
  42024. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  42025. this.isOGGsupported = true;
  42026. }
  42027. }
  42028. catch (e) {
  42029. // protect error during capability check.
  42030. }
  42031. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  42032. this._unlockiOSaudio();
  42033. }
  42034. else {
  42035. this.unlocked = true;
  42036. }
  42037. }
  42038. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  42039. get: function () {
  42040. if (!this._audioContextInitialized) {
  42041. this._initializeAudioContext();
  42042. }
  42043. return this._audioContext;
  42044. },
  42045. enumerable: true,
  42046. configurable: true
  42047. });
  42048. AudioEngine.prototype._unlockiOSaudio = function () {
  42049. var _this = this;
  42050. var unlockaudio = function () {
  42051. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  42052. var source = _this.audioContext.createBufferSource();
  42053. source.buffer = buffer;
  42054. source.connect(_this.audioContext.destination);
  42055. source.start(0);
  42056. setTimeout(function () {
  42057. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  42058. _this.unlocked = true;
  42059. window.removeEventListener('touchend', unlockaudio, false);
  42060. if (_this.onAudioUnlocked) {
  42061. _this.onAudioUnlocked();
  42062. }
  42063. }
  42064. }, 0);
  42065. };
  42066. window.addEventListener('touchend', unlockaudio, false);
  42067. };
  42068. AudioEngine.prototype._initializeAudioContext = function () {
  42069. try {
  42070. if (this.canUseWebAudio) {
  42071. this._audioContext = new AudioContext();
  42072. // create a global volume gain node
  42073. this.masterGain = this._audioContext.createGain();
  42074. this.masterGain.gain.value = 1;
  42075. this.masterGain.connect(this._audioContext.destination);
  42076. this._audioContextInitialized = true;
  42077. }
  42078. }
  42079. catch (e) {
  42080. this.canUseWebAudio = false;
  42081. BABYLON.Tools.Error("Web Audio: " + e.message);
  42082. }
  42083. };
  42084. AudioEngine.prototype.dispose = function () {
  42085. if (this.canUseWebAudio && this._audioContextInitialized) {
  42086. if (this._connectedAnalyser) {
  42087. this._connectedAnalyser.stopDebugCanvas();
  42088. this._connectedAnalyser.dispose();
  42089. this.masterGain.disconnect();
  42090. this.masterGain.connect(this._audioContext.destination);
  42091. this._connectedAnalyser = null;
  42092. }
  42093. this.masterGain.gain.value = 1;
  42094. }
  42095. this.WarnedWebAudioUnsupported = false;
  42096. };
  42097. AudioEngine.prototype.getGlobalVolume = function () {
  42098. if (this.canUseWebAudio && this._audioContextInitialized) {
  42099. return this.masterGain.gain.value;
  42100. }
  42101. else {
  42102. return -1;
  42103. }
  42104. };
  42105. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  42106. if (this.canUseWebAudio && this._audioContextInitialized) {
  42107. this.masterGain.gain.value = newVolume;
  42108. }
  42109. };
  42110. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  42111. if (this._connectedAnalyser) {
  42112. this._connectedAnalyser.stopDebugCanvas();
  42113. }
  42114. if (this.canUseWebAudio && this._audioContextInitialized) {
  42115. this._connectedAnalyser = analyser;
  42116. this.masterGain.disconnect();
  42117. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  42118. }
  42119. };
  42120. return AudioEngine;
  42121. }());
  42122. BABYLON.AudioEngine = AudioEngine;
  42123. })(BABYLON || (BABYLON = {}));
  42124. //# sourceMappingURL=babylon.audioEngine.js.map
  42125. var BABYLON;
  42126. (function (BABYLON) {
  42127. var Sound = (function () {
  42128. /**
  42129. * Create a sound and attach it to a scene
  42130. * @param name Name of your sound
  42131. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  42132. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  42133. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  42134. */
  42135. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  42136. var _this = this;
  42137. this.autoplay = false;
  42138. this.loop = false;
  42139. this.useCustomAttenuation = false;
  42140. this.spatialSound = false;
  42141. this.refDistance = 1;
  42142. this.rolloffFactor = 1;
  42143. this.maxDistance = 100;
  42144. this.distanceModel = "linear";
  42145. this._panningModel = "equalpower";
  42146. this._playbackRate = 1;
  42147. this._streaming = false;
  42148. this._startTime = 0;
  42149. this._startOffset = 0;
  42150. this._position = BABYLON.Vector3.Zero();
  42151. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  42152. this._volume = 1;
  42153. this._isLoaded = false;
  42154. this._isReadyToPlay = false;
  42155. this.isPlaying = false;
  42156. this.isPaused = false;
  42157. this._isDirectional = false;
  42158. // Used if you'd like to create a directional sound.
  42159. // If not set, the sound will be omnidirectional
  42160. this._coneInnerAngle = 360;
  42161. this._coneOuterAngle = 360;
  42162. this._coneOuterGain = 0;
  42163. this._isOutputConnected = false;
  42164. this._urlType = "Unknown";
  42165. this.name = name;
  42166. this._scene = scene;
  42167. this._readyToPlayCallback = readyToPlayCallback;
  42168. // Default custom attenuation function is a linear attenuation
  42169. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  42170. if (currentDistance < maxDistance) {
  42171. return currentVolume * (1 - currentDistance / maxDistance);
  42172. }
  42173. else {
  42174. return 0;
  42175. }
  42176. };
  42177. if (options) {
  42178. this.autoplay = options.autoplay || false;
  42179. this.loop = options.loop || false;
  42180. // if volume === 0, we need another way to check this option
  42181. if (options.volume !== undefined) {
  42182. this._volume = options.volume;
  42183. }
  42184. this.spatialSound = options.spatialSound || false;
  42185. this.maxDistance = options.maxDistance || 100;
  42186. this.useCustomAttenuation = options.useCustomAttenuation || false;
  42187. this.rolloffFactor = options.rolloffFactor || 1;
  42188. this.refDistance = options.refDistance || 1;
  42189. this.distanceModel = options.distanceModel || "linear";
  42190. this._playbackRate = options.playbackRate || 1;
  42191. this._streaming = options.streaming || false;
  42192. }
  42193. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42194. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  42195. this._soundGain.gain.value = this._volume;
  42196. this._inputAudioNode = this._soundGain;
  42197. this._ouputAudioNode = this._soundGain;
  42198. if (this.spatialSound) {
  42199. this._createSpatialParameters();
  42200. }
  42201. this._scene.mainSoundTrack.AddSound(this);
  42202. var validParameter = true;
  42203. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  42204. if (urlOrArrayBuffer) {
  42205. if (typeof (urlOrArrayBuffer) === "string")
  42206. this._urlType = "String";
  42207. if (Array.isArray(urlOrArrayBuffer))
  42208. this._urlType = "Array";
  42209. if (urlOrArrayBuffer instanceof ArrayBuffer)
  42210. this._urlType = "ArrayBuffer";
  42211. var urls = [];
  42212. var codecSupportedFound = false;
  42213. switch (this._urlType) {
  42214. case "ArrayBuffer":
  42215. if (urlOrArrayBuffer.byteLength > 0) {
  42216. codecSupportedFound = true;
  42217. this._soundLoaded(urlOrArrayBuffer);
  42218. }
  42219. break;
  42220. case "String":
  42221. urls.push(urlOrArrayBuffer);
  42222. case "Array":
  42223. if (urls.length === 0)
  42224. urls = urlOrArrayBuffer;
  42225. // If we found a supported format, we load it immediately and stop the loop
  42226. for (var i = 0; i < urls.length; i++) {
  42227. var url = urls[i];
  42228. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  42229. codecSupportedFound = true;
  42230. }
  42231. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  42232. codecSupportedFound = true;
  42233. }
  42234. if (url.indexOf(".wav", url.length - 4) !== -1) {
  42235. codecSupportedFound = true;
  42236. }
  42237. if (codecSupportedFound) {
  42238. // Loading sound using XHR2
  42239. if (!this._streaming) {
  42240. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  42241. }
  42242. else {
  42243. this._htmlAudioElement = new Audio(url);
  42244. this._htmlAudioElement.controls = false;
  42245. this._htmlAudioElement.loop = this.loop;
  42246. this._htmlAudioElement.crossOrigin = "anonymous";
  42247. this._htmlAudioElement.preload = "auto";
  42248. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  42249. _this._isReadyToPlay = true;
  42250. if (_this.autoplay) {
  42251. _this.play();
  42252. }
  42253. if (_this._readyToPlayCallback) {
  42254. _this._readyToPlayCallback();
  42255. }
  42256. });
  42257. document.body.appendChild(this._htmlAudioElement);
  42258. }
  42259. break;
  42260. }
  42261. }
  42262. break;
  42263. default:
  42264. validParameter = false;
  42265. break;
  42266. }
  42267. if (!validParameter) {
  42268. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  42269. }
  42270. else {
  42271. if (!codecSupportedFound) {
  42272. this._isReadyToPlay = true;
  42273. // Simulating a ready to play event to avoid breaking code path
  42274. if (this._readyToPlayCallback) {
  42275. window.setTimeout(function () {
  42276. _this._readyToPlayCallback();
  42277. }, 1000);
  42278. }
  42279. }
  42280. }
  42281. }
  42282. }
  42283. else {
  42284. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  42285. this._scene.mainSoundTrack.AddSound(this);
  42286. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  42287. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  42288. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  42289. }
  42290. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  42291. if (this._readyToPlayCallback) {
  42292. window.setTimeout(function () {
  42293. _this._readyToPlayCallback();
  42294. }, 1000);
  42295. }
  42296. }
  42297. }
  42298. Sound.prototype.dispose = function () {
  42299. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  42300. if (this.isPlaying) {
  42301. this.stop();
  42302. }
  42303. this._isReadyToPlay = false;
  42304. if (this.soundTrackId === -1) {
  42305. this._scene.mainSoundTrack.RemoveSound(this);
  42306. }
  42307. else {
  42308. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  42309. }
  42310. if (this._soundGain) {
  42311. this._soundGain.disconnect();
  42312. this._soundGain = null;
  42313. }
  42314. if (this._soundPanner) {
  42315. this._soundPanner.disconnect();
  42316. this._soundPanner = null;
  42317. }
  42318. if (this._soundSource) {
  42319. this._soundSource.disconnect();
  42320. this._soundSource = null;
  42321. }
  42322. this._audioBuffer = null;
  42323. if (this._htmlAudioElement) {
  42324. this._htmlAudioElement.pause();
  42325. this._htmlAudioElement.src = "";
  42326. document.body.removeChild(this._htmlAudioElement);
  42327. }
  42328. if (this._connectedMesh) {
  42329. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42330. this._connectedMesh = null;
  42331. }
  42332. }
  42333. };
  42334. Sound.prototype.isReady = function () {
  42335. return this._isReadyToPlay;
  42336. };
  42337. Sound.prototype._soundLoaded = function (audioData) {
  42338. var _this = this;
  42339. this._isLoaded = true;
  42340. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  42341. _this._audioBuffer = buffer;
  42342. _this._isReadyToPlay = true;
  42343. if (_this.autoplay) {
  42344. _this.play();
  42345. }
  42346. if (_this._readyToPlayCallback) {
  42347. _this._readyToPlayCallback();
  42348. }
  42349. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  42350. };
  42351. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  42352. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42353. this._audioBuffer = audioBuffer;
  42354. this._isReadyToPlay = true;
  42355. }
  42356. };
  42357. Sound.prototype.updateOptions = function (options) {
  42358. if (options) {
  42359. this.loop = options.loop || this.loop;
  42360. this.maxDistance = options.maxDistance || this.maxDistance;
  42361. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  42362. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  42363. this.refDistance = options.refDistance || this.refDistance;
  42364. this.distanceModel = options.distanceModel || this.distanceModel;
  42365. this._playbackRate = options.playbackRate || this._playbackRate;
  42366. this._updateSpatialParameters();
  42367. if (this.isPlaying) {
  42368. if (this._streaming) {
  42369. this._htmlAudioElement.playbackRate = this._playbackRate;
  42370. }
  42371. else {
  42372. this._soundSource.playbackRate.value = this._playbackRate;
  42373. }
  42374. }
  42375. }
  42376. };
  42377. Sound.prototype._createSpatialParameters = function () {
  42378. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42379. if (this._scene.headphone) {
  42380. this._panningModel = "HRTF";
  42381. }
  42382. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  42383. this._updateSpatialParameters();
  42384. this._soundPanner.connect(this._ouputAudioNode);
  42385. this._inputAudioNode = this._soundPanner;
  42386. }
  42387. };
  42388. Sound.prototype._updateSpatialParameters = function () {
  42389. if (this.spatialSound) {
  42390. if (this.useCustomAttenuation) {
  42391. // Tricks to disable in a way embedded Web Audio attenuation
  42392. this._soundPanner.distanceModel = "linear";
  42393. this._soundPanner.maxDistance = Number.MAX_VALUE;
  42394. this._soundPanner.refDistance = 1;
  42395. this._soundPanner.rolloffFactor = 1;
  42396. this._soundPanner.panningModel = this._panningModel;
  42397. }
  42398. else {
  42399. this._soundPanner.distanceModel = this.distanceModel;
  42400. this._soundPanner.maxDistance = this.maxDistance;
  42401. this._soundPanner.refDistance = this.refDistance;
  42402. this._soundPanner.rolloffFactor = this.rolloffFactor;
  42403. this._soundPanner.panningModel = this._panningModel;
  42404. }
  42405. }
  42406. };
  42407. Sound.prototype.switchPanningModelToHRTF = function () {
  42408. this._panningModel = "HRTF";
  42409. this._switchPanningModel();
  42410. };
  42411. Sound.prototype.switchPanningModelToEqualPower = function () {
  42412. this._panningModel = "equalpower";
  42413. this._switchPanningModel();
  42414. };
  42415. Sound.prototype._switchPanningModel = function () {
  42416. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42417. this._soundPanner.panningModel = this._panningModel;
  42418. }
  42419. };
  42420. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  42421. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42422. if (this._isOutputConnected) {
  42423. this._ouputAudioNode.disconnect();
  42424. }
  42425. this._ouputAudioNode.connect(soundTrackAudioNode);
  42426. this._isOutputConnected = true;
  42427. }
  42428. };
  42429. /**
  42430. * Transform this sound into a directional source
  42431. * @param coneInnerAngle Size of the inner cone in degree
  42432. * @param coneOuterAngle Size of the outer cone in degree
  42433. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  42434. */
  42435. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  42436. if (coneOuterAngle < coneInnerAngle) {
  42437. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  42438. return;
  42439. }
  42440. this._coneInnerAngle = coneInnerAngle;
  42441. this._coneOuterAngle = coneOuterAngle;
  42442. this._coneOuterGain = coneOuterGain;
  42443. this._isDirectional = true;
  42444. if (this.isPlaying && this.loop) {
  42445. this.stop();
  42446. this.play();
  42447. }
  42448. };
  42449. Sound.prototype.setPosition = function (newPosition) {
  42450. this._position = newPosition;
  42451. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42452. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42453. }
  42454. };
  42455. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  42456. this._localDirection = newLocalDirection;
  42457. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  42458. this._updateDirection();
  42459. }
  42460. };
  42461. Sound.prototype._updateDirection = function () {
  42462. var mat = this._connectedMesh.getWorldMatrix();
  42463. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  42464. direction.normalize();
  42465. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  42466. };
  42467. Sound.prototype.updateDistanceFromListener = function () {
  42468. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  42469. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  42470. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  42471. }
  42472. };
  42473. Sound.prototype.setAttenuationFunction = function (callback) {
  42474. this._customAttenuationFunction = callback;
  42475. };
  42476. /**
  42477. * Play the sound
  42478. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  42479. * @param offset (optional) Start the sound setting it at a specific time
  42480. */
  42481. Sound.prototype.play = function (time, offset) {
  42482. var _this = this;
  42483. if (this._isReadyToPlay && this._scene.audioEnabled) {
  42484. try {
  42485. if (this._startOffset < 0) {
  42486. time = -this._startOffset;
  42487. this._startOffset = 0;
  42488. }
  42489. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42490. if (!this._soundSource || !this._streamingSource) {
  42491. if (this.spatialSound) {
  42492. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42493. if (this._isDirectional) {
  42494. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  42495. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  42496. this._soundPanner.coneOuterGain = this._coneOuterGain;
  42497. if (this._connectedMesh) {
  42498. this._updateDirection();
  42499. }
  42500. else {
  42501. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  42502. }
  42503. }
  42504. }
  42505. }
  42506. if (this._streaming) {
  42507. if (!this._streamingSource) {
  42508. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  42509. this._htmlAudioElement.onended = function () { _this._onended(); };
  42510. this._htmlAudioElement.playbackRate = this._playbackRate;
  42511. }
  42512. this._streamingSource.disconnect();
  42513. this._streamingSource.connect(this._inputAudioNode);
  42514. this._htmlAudioElement.play();
  42515. }
  42516. else {
  42517. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  42518. this._soundSource.buffer = this._audioBuffer;
  42519. this._soundSource.connect(this._inputAudioNode);
  42520. this._soundSource.loop = this.loop;
  42521. this._soundSource.playbackRate.value = this._playbackRate;
  42522. this._soundSource.onended = function () { _this._onended(); };
  42523. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  42524. }
  42525. this._startTime = startTime;
  42526. this.isPlaying = true;
  42527. this.isPaused = false;
  42528. }
  42529. catch (ex) {
  42530. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  42531. }
  42532. }
  42533. };
  42534. Sound.prototype._onended = function () {
  42535. this.isPlaying = false;
  42536. if (this.onended) {
  42537. this.onended();
  42538. }
  42539. };
  42540. /**
  42541. * Stop the sound
  42542. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  42543. */
  42544. Sound.prototype.stop = function (time) {
  42545. if (this.isPlaying) {
  42546. if (this._streaming) {
  42547. this._htmlAudioElement.pause();
  42548. // Test needed for Firefox or it will generate an Invalid State Error
  42549. if (this._htmlAudioElement.currentTime > 0) {
  42550. this._htmlAudioElement.currentTime = 0;
  42551. }
  42552. }
  42553. else {
  42554. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42555. this._soundSource.stop(stopTime);
  42556. this._soundSource.onended = null;
  42557. if (!this.isPaused) {
  42558. this._startOffset = 0;
  42559. }
  42560. }
  42561. this.isPlaying = false;
  42562. }
  42563. };
  42564. Sound.prototype.pause = function () {
  42565. if (this.isPlaying) {
  42566. this.isPaused = true;
  42567. if (this._streaming) {
  42568. this._htmlAudioElement.pause();
  42569. }
  42570. else {
  42571. this.stop(0);
  42572. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  42573. }
  42574. }
  42575. };
  42576. Sound.prototype.setVolume = function (newVolume, time) {
  42577. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42578. if (time) {
  42579. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  42580. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  42581. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  42582. }
  42583. else {
  42584. this._soundGain.gain.value = newVolume;
  42585. }
  42586. }
  42587. this._volume = newVolume;
  42588. };
  42589. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  42590. this._playbackRate = newPlaybackRate;
  42591. if (this.isPlaying) {
  42592. if (this._streaming) {
  42593. this._htmlAudioElement.playbackRate = this._playbackRate;
  42594. }
  42595. else {
  42596. this._soundSource.playbackRate.value = this._playbackRate;
  42597. }
  42598. }
  42599. };
  42600. Sound.prototype.getVolume = function () {
  42601. return this._volume;
  42602. };
  42603. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  42604. var _this = this;
  42605. if (this._connectedMesh) {
  42606. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42607. this._registerFunc = null;
  42608. }
  42609. this._connectedMesh = meshToConnectTo;
  42610. if (!this.spatialSound) {
  42611. this.spatialSound = true;
  42612. this._createSpatialParameters();
  42613. if (this.isPlaying && this.loop) {
  42614. this.stop();
  42615. this.play();
  42616. }
  42617. }
  42618. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  42619. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  42620. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  42621. };
  42622. Sound.prototype.detachFromMesh = function () {
  42623. if (this._connectedMesh) {
  42624. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42625. this._registerFunc = null;
  42626. this._connectedMesh = null;
  42627. }
  42628. };
  42629. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  42630. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  42631. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  42632. this._updateDirection();
  42633. }
  42634. };
  42635. Sound.prototype.clone = function () {
  42636. var _this = this;
  42637. if (!this._streaming) {
  42638. var setBufferAndRun = function () {
  42639. if (_this._isReadyToPlay) {
  42640. clonedSound._audioBuffer = _this.getAudioBuffer();
  42641. clonedSound._isReadyToPlay = true;
  42642. if (clonedSound.autoplay) {
  42643. clonedSound.play();
  42644. }
  42645. }
  42646. else {
  42647. window.setTimeout(setBufferAndRun, 300);
  42648. }
  42649. };
  42650. var currentOptions = {
  42651. autoplay: this.autoplay, loop: this.loop,
  42652. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  42653. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  42654. refDistance: this.refDistance, distanceModel: this.distanceModel
  42655. };
  42656. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  42657. if (this.useCustomAttenuation) {
  42658. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  42659. }
  42660. clonedSound.setPosition(this._position);
  42661. clonedSound.setPlaybackRate(this._playbackRate);
  42662. setBufferAndRun();
  42663. return clonedSound;
  42664. }
  42665. else {
  42666. return null;
  42667. }
  42668. };
  42669. Sound.prototype.getAudioBuffer = function () {
  42670. return this._audioBuffer;
  42671. };
  42672. Sound.prototype.serialize = function () {
  42673. var serializationObject = {
  42674. name: this.name,
  42675. url: this.name,
  42676. autoplay: this.autoplay,
  42677. loop: this.loop,
  42678. volume: this._volume,
  42679. spatialSound: this.spatialSound,
  42680. maxDistance: this.maxDistance,
  42681. rolloffFactor: this.rolloffFactor,
  42682. refDistance: this.refDistance,
  42683. distanceModel: this.distanceModel,
  42684. playbackRate: this._playbackRate,
  42685. panningModel: this._panningModel,
  42686. soundTrackId: this.soundTrackId
  42687. };
  42688. if (this.spatialSound) {
  42689. if (this._connectedMesh)
  42690. serializationObject.connectedMeshId = this._connectedMesh.id;
  42691. serializationObject.position = this._position.asArray();
  42692. serializationObject.refDistance = this.refDistance;
  42693. serializationObject.distanceModel = this.distanceModel;
  42694. serializationObject.isDirectional = this._isDirectional;
  42695. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  42696. serializationObject.coneInnerAngle = this._coneInnerAngle;
  42697. serializationObject.coneOuterAngle = this._coneOuterAngle;
  42698. serializationObject.coneOuterGain = this._coneOuterGain;
  42699. }
  42700. return serializationObject;
  42701. };
  42702. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  42703. var soundName = parsedSound.name;
  42704. var soundUrl;
  42705. if (parsedSound.url) {
  42706. soundUrl = rootUrl + parsedSound.url;
  42707. }
  42708. else {
  42709. soundUrl = rootUrl + soundName;
  42710. }
  42711. var options = {
  42712. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  42713. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  42714. rolloffFactor: parsedSound.rolloffFactor,
  42715. refDistance: parsedSound.refDistance,
  42716. distanceModel: parsedSound.distanceModel,
  42717. playbackRate: parsedSound.playbackRate
  42718. };
  42719. var newSound;
  42720. if (!sourceSound) {
  42721. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  42722. scene._addPendingData(newSound);
  42723. }
  42724. else {
  42725. var setBufferAndRun = function () {
  42726. if (sourceSound._isReadyToPlay) {
  42727. newSound._audioBuffer = sourceSound.getAudioBuffer();
  42728. newSound._isReadyToPlay = true;
  42729. if (newSound.autoplay) {
  42730. newSound.play();
  42731. }
  42732. }
  42733. else {
  42734. window.setTimeout(setBufferAndRun, 300);
  42735. }
  42736. };
  42737. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  42738. setBufferAndRun();
  42739. }
  42740. if (parsedSound.position) {
  42741. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  42742. newSound.setPosition(soundPosition);
  42743. }
  42744. if (parsedSound.isDirectional) {
  42745. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  42746. if (parsedSound.localDirectionToMesh) {
  42747. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  42748. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  42749. }
  42750. }
  42751. if (parsedSound.connectedMeshId) {
  42752. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  42753. if (connectedMesh) {
  42754. newSound.attachToMesh(connectedMesh);
  42755. }
  42756. }
  42757. return newSound;
  42758. };
  42759. return Sound;
  42760. }());
  42761. BABYLON.Sound = Sound;
  42762. })(BABYLON || (BABYLON = {}));
  42763. //# sourceMappingURL=babylon.sound.js.map
  42764. var BABYLON;
  42765. (function (BABYLON) {
  42766. var SoundTrack = (function () {
  42767. function SoundTrack(scene, options) {
  42768. this.id = -1;
  42769. this._isMainTrack = false;
  42770. this._isInitialized = false;
  42771. this._scene = scene;
  42772. this.soundCollection = new Array();
  42773. this._options = options;
  42774. if (!this._isMainTrack) {
  42775. this._scene.soundTracks.push(this);
  42776. this.id = this._scene.soundTracks.length - 1;
  42777. }
  42778. }
  42779. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  42780. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42781. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  42782. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  42783. if (this._options) {
  42784. if (this._options.volume) {
  42785. this._outputAudioNode.gain.value = this._options.volume;
  42786. }
  42787. if (this._options.mainTrack) {
  42788. this._isMainTrack = this._options.mainTrack;
  42789. }
  42790. }
  42791. this._isInitialized = true;
  42792. }
  42793. };
  42794. SoundTrack.prototype.dispose = function () {
  42795. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42796. if (this._connectedAnalyser) {
  42797. this._connectedAnalyser.stopDebugCanvas();
  42798. }
  42799. while (this.soundCollection.length) {
  42800. this.soundCollection[0].dispose();
  42801. }
  42802. if (this._outputAudioNode) {
  42803. this._outputAudioNode.disconnect();
  42804. }
  42805. this._outputAudioNode = null;
  42806. }
  42807. };
  42808. SoundTrack.prototype.AddSound = function (sound) {
  42809. if (!this._isInitialized) {
  42810. this._initializeSoundTrackAudioGraph();
  42811. }
  42812. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42813. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  42814. }
  42815. if (sound.soundTrackId) {
  42816. if (sound.soundTrackId === -1) {
  42817. this._scene.mainSoundTrack.RemoveSound(sound);
  42818. }
  42819. else {
  42820. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  42821. }
  42822. }
  42823. this.soundCollection.push(sound);
  42824. sound.soundTrackId = this.id;
  42825. };
  42826. SoundTrack.prototype.RemoveSound = function (sound) {
  42827. var index = this.soundCollection.indexOf(sound);
  42828. if (index !== -1) {
  42829. this.soundCollection.splice(index, 1);
  42830. }
  42831. };
  42832. SoundTrack.prototype.setVolume = function (newVolume) {
  42833. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42834. this._outputAudioNode.gain.value = newVolume;
  42835. }
  42836. };
  42837. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  42838. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42839. for (var i = 0; i < this.soundCollection.length; i++) {
  42840. this.soundCollection[i].switchPanningModelToHRTF();
  42841. }
  42842. }
  42843. };
  42844. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  42845. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42846. for (var i = 0; i < this.soundCollection.length; i++) {
  42847. this.soundCollection[i].switchPanningModelToEqualPower();
  42848. }
  42849. }
  42850. };
  42851. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  42852. if (this._connectedAnalyser) {
  42853. this._connectedAnalyser.stopDebugCanvas();
  42854. }
  42855. this._connectedAnalyser = analyser;
  42856. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42857. this._outputAudioNode.disconnect();
  42858. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  42859. }
  42860. };
  42861. return SoundTrack;
  42862. }());
  42863. BABYLON.SoundTrack = SoundTrack;
  42864. })(BABYLON || (BABYLON = {}));
  42865. //# sourceMappingURL=babylon.soundtrack.js.map
  42866. var BABYLON;
  42867. (function (BABYLON) {
  42868. var Analyser = (function () {
  42869. function Analyser(scene) {
  42870. this.SMOOTHING = 0.75;
  42871. this.FFT_SIZE = 512;
  42872. this.BARGRAPHAMPLITUDE = 256;
  42873. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  42874. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  42875. this._scene = scene;
  42876. this._audioEngine = BABYLON.Engine.audioEngine;
  42877. if (this._audioEngine.canUseWebAudio) {
  42878. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  42879. this._webAudioAnalyser.minDecibels = -140;
  42880. this._webAudioAnalyser.maxDecibels = 0;
  42881. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42882. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42883. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  42884. }
  42885. }
  42886. Analyser.prototype.getFrequencyBinCount = function () {
  42887. if (this._audioEngine.canUseWebAudio) {
  42888. return this._webAudioAnalyser.frequencyBinCount;
  42889. }
  42890. else {
  42891. return 0;
  42892. }
  42893. };
  42894. Analyser.prototype.getByteFrequencyData = function () {
  42895. if (this._audioEngine.canUseWebAudio) {
  42896. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42897. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42898. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  42899. }
  42900. return this._byteFreqs;
  42901. };
  42902. Analyser.prototype.getByteTimeDomainData = function () {
  42903. if (this._audioEngine.canUseWebAudio) {
  42904. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42905. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42906. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  42907. }
  42908. return this._byteTime;
  42909. };
  42910. Analyser.prototype.getFloatFrequencyData = function () {
  42911. if (this._audioEngine.canUseWebAudio) {
  42912. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42913. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42914. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  42915. }
  42916. return this._floatFreqs;
  42917. };
  42918. Analyser.prototype.drawDebugCanvas = function () {
  42919. var _this = this;
  42920. if (this._audioEngine.canUseWebAudio) {
  42921. if (!this._debugCanvas) {
  42922. this._debugCanvas = document.createElement("canvas");
  42923. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  42924. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  42925. this._debugCanvas.style.position = "absolute";
  42926. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  42927. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  42928. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  42929. document.body.appendChild(this._debugCanvas);
  42930. this._registerFunc = function () {
  42931. _this.drawDebugCanvas();
  42932. };
  42933. this._scene.registerBeforeRender(this._registerFunc);
  42934. }
  42935. if (this._registerFunc) {
  42936. var workingArray = this.getByteFrequencyData();
  42937. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  42938. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  42939. // Draw the frequency domain chart.
  42940. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  42941. var value = workingArray[i];
  42942. var percent = value / this.BARGRAPHAMPLITUDE;
  42943. var height = this.DEBUGCANVASSIZE.height * percent;
  42944. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  42945. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  42946. var hue = i / this.getFrequencyBinCount() * 360;
  42947. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  42948. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  42949. }
  42950. }
  42951. }
  42952. };
  42953. Analyser.prototype.stopDebugCanvas = function () {
  42954. if (this._debugCanvas) {
  42955. this._scene.unregisterBeforeRender(this._registerFunc);
  42956. this._registerFunc = null;
  42957. document.body.removeChild(this._debugCanvas);
  42958. this._debugCanvas = null;
  42959. this._debugCanvasContext = null;
  42960. }
  42961. };
  42962. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  42963. if (this._audioEngine.canUseWebAudio) {
  42964. inputAudioNode.connect(this._webAudioAnalyser);
  42965. this._webAudioAnalyser.connect(outputAudioNode);
  42966. }
  42967. };
  42968. Analyser.prototype.dispose = function () {
  42969. if (this._audioEngine.canUseWebAudio) {
  42970. this._webAudioAnalyser.disconnect();
  42971. }
  42972. };
  42973. return Analyser;
  42974. }());
  42975. BABYLON.Analyser = Analyser;
  42976. })(BABYLON || (BABYLON = {}));
  42977. //# sourceMappingURL=babylon.analyser.js.map
  42978. var BABYLON;
  42979. (function (BABYLON) {
  42980. var CubeTexture = (function (_super) {
  42981. __extends(CubeTexture, _super);
  42982. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  42983. if (onLoad === void 0) { onLoad = null; }
  42984. if (onError === void 0) { onError = null; }
  42985. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  42986. var _this = _super.call(this, scene) || this;
  42987. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42988. _this.name = rootUrl;
  42989. _this.url = rootUrl;
  42990. _this._noMipmap = noMipmap;
  42991. _this.hasAlpha = false;
  42992. _this._format = format;
  42993. if (!rootUrl && !files) {
  42994. return _this;
  42995. }
  42996. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  42997. if (!files) {
  42998. if (!extensions) {
  42999. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  43000. }
  43001. files = [];
  43002. for (var index = 0; index < extensions.length; index++) {
  43003. files.push(rootUrl + extensions[index]);
  43004. }
  43005. _this._extensions = extensions;
  43006. }
  43007. _this._files = files;
  43008. if (!_this._texture) {
  43009. if (!scene.useDelayedTextureLoading) {
  43010. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  43011. }
  43012. else {
  43013. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43014. }
  43015. }
  43016. else if (onLoad) {
  43017. if (_this._texture.isReady) {
  43018. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  43019. }
  43020. else {
  43021. _this._texture.onLoadedCallbacks.push(onLoad);
  43022. }
  43023. }
  43024. _this.isCube = true;
  43025. _this._textureMatrix = BABYLON.Matrix.Identity();
  43026. return _this;
  43027. }
  43028. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  43029. return new CubeTexture("", scene, null, noMipmap, files);
  43030. };
  43031. // Methods
  43032. CubeTexture.prototype.delayLoad = function () {
  43033. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  43034. return;
  43035. }
  43036. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  43037. this._texture = this._getFromCache(this.url, this._noMipmap);
  43038. if (!this._texture) {
  43039. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  43040. }
  43041. };
  43042. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  43043. return this._textureMatrix;
  43044. };
  43045. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  43046. var texture = BABYLON.SerializationHelper.Parse(function () {
  43047. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  43048. }, parsedTexture, scene);
  43049. // Animations
  43050. if (parsedTexture.animations) {
  43051. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  43052. var parsedAnimation = parsedTexture.animations[animationIndex];
  43053. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  43054. }
  43055. }
  43056. return texture;
  43057. };
  43058. CubeTexture.prototype.clone = function () {
  43059. var _this = this;
  43060. return BABYLON.SerializationHelper.Clone(function () {
  43061. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  43062. }, this);
  43063. };
  43064. return CubeTexture;
  43065. }(BABYLON.BaseTexture));
  43066. BABYLON.CubeTexture = CubeTexture;
  43067. })(BABYLON || (BABYLON = {}));
  43068. //# sourceMappingURL=babylon.cubeTexture.js.map
  43069. var BABYLON;
  43070. (function (BABYLON) {
  43071. var RenderTargetTexture = (function (_super) {
  43072. __extends(RenderTargetTexture, _super);
  43073. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  43074. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  43075. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43076. if (isCube === void 0) { isCube = false; }
  43077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43078. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  43079. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  43080. if (isMulti === void 0) { isMulti = false; }
  43081. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  43082. _this.isCube = isCube;
  43083. /**
  43084. * Use this list to define the list of mesh you want to render.
  43085. */
  43086. _this.renderList = new Array();
  43087. _this.renderParticles = true;
  43088. _this.renderSprites = false;
  43089. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  43090. // Events
  43091. /**
  43092. * An event triggered when the texture is unbind.
  43093. * @type {BABYLON.Observable}
  43094. */
  43095. _this.onAfterUnbindObservable = new BABYLON.Observable();
  43096. /**
  43097. * An event triggered before rendering the texture
  43098. * @type {BABYLON.Observable}
  43099. */
  43100. _this.onBeforeRenderObservable = new BABYLON.Observable();
  43101. /**
  43102. * An event triggered after rendering the texture
  43103. * @type {BABYLON.Observable}
  43104. */
  43105. _this.onAfterRenderObservable = new BABYLON.Observable();
  43106. /**
  43107. * An event triggered after the texture clear
  43108. * @type {BABYLON.Observable}
  43109. */
  43110. _this.onClearObservable = new BABYLON.Observable();
  43111. _this._currentRefreshId = -1;
  43112. _this._refreshRate = 1;
  43113. _this._samples = 1;
  43114. scene = _this.getScene();
  43115. _this.name = name;
  43116. _this.isRenderTarget = true;
  43117. _this._size = size;
  43118. _this._generateMipMaps = generateMipMaps;
  43119. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  43120. // Rendering groups
  43121. _this._renderingManager = new BABYLON.RenderingManager(scene);
  43122. if (isMulti) {
  43123. return _this;
  43124. }
  43125. _this._renderTargetOptions = {
  43126. generateMipMaps: generateMipMaps,
  43127. type: type,
  43128. samplingMode: samplingMode,
  43129. generateDepthBuffer: generateDepthBuffer,
  43130. generateStencilBuffer: generateStencilBuffer
  43131. };
  43132. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  43133. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43134. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43135. }
  43136. if (isCube) {
  43137. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  43138. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  43139. _this._textureMatrix = BABYLON.Matrix.Identity();
  43140. }
  43141. else {
  43142. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  43143. }
  43144. return _this;
  43145. }
  43146. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  43147. get: function () {
  43148. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  43149. },
  43150. enumerable: true,
  43151. configurable: true
  43152. });
  43153. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  43154. get: function () {
  43155. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  43156. },
  43157. enumerable: true,
  43158. configurable: true
  43159. });
  43160. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  43161. get: function () {
  43162. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  43163. },
  43164. enumerable: true,
  43165. configurable: true
  43166. });
  43167. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  43168. set: function (callback) {
  43169. if (this._onAfterUnbindObserver) {
  43170. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  43171. }
  43172. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  43173. },
  43174. enumerable: true,
  43175. configurable: true
  43176. });
  43177. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  43178. set: function (callback) {
  43179. if (this._onBeforeRenderObserver) {
  43180. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  43181. }
  43182. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  43183. },
  43184. enumerable: true,
  43185. configurable: true
  43186. });
  43187. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  43188. set: function (callback) {
  43189. if (this._onAfterRenderObserver) {
  43190. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  43191. }
  43192. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  43193. },
  43194. enumerable: true,
  43195. configurable: true
  43196. });
  43197. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  43198. set: function (callback) {
  43199. if (this._onClearObserver) {
  43200. this.onClearObservable.remove(this._onClearObserver);
  43201. }
  43202. this._onClearObserver = this.onClearObservable.add(callback);
  43203. },
  43204. enumerable: true,
  43205. configurable: true
  43206. });
  43207. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  43208. get: function () {
  43209. return this._renderTargetOptions;
  43210. },
  43211. enumerable: true,
  43212. configurable: true
  43213. });
  43214. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  43215. get: function () {
  43216. return this._samples;
  43217. },
  43218. set: function (value) {
  43219. if (this._samples === value) {
  43220. return;
  43221. }
  43222. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  43223. },
  43224. enumerable: true,
  43225. configurable: true
  43226. });
  43227. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  43228. this._currentRefreshId = -1;
  43229. };
  43230. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  43231. get: function () {
  43232. return this._refreshRate;
  43233. },
  43234. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  43235. set: function (value) {
  43236. this._refreshRate = value;
  43237. this.resetRefreshCounter();
  43238. },
  43239. enumerable: true,
  43240. configurable: true
  43241. });
  43242. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  43243. if (!this._postProcessManager) {
  43244. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  43245. this._postProcesses = new Array();
  43246. }
  43247. this._postProcesses.push(postProcess);
  43248. this._postProcesses[0].autoClear = false;
  43249. };
  43250. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  43251. if (!this._postProcesses) {
  43252. return;
  43253. }
  43254. if (dispose) {
  43255. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  43256. var postProcess = _a[_i];
  43257. postProcess.dispose();
  43258. postProcess = null;
  43259. }
  43260. }
  43261. this._postProcesses = [];
  43262. };
  43263. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  43264. if (!this._postProcesses) {
  43265. return;
  43266. }
  43267. var index = this._postProcesses.indexOf(postProcess);
  43268. if (index === -1) {
  43269. return;
  43270. }
  43271. this._postProcesses.splice(index, 1);
  43272. if (this._postProcesses.length > 0) {
  43273. this._postProcesses[0].autoClear = false;
  43274. }
  43275. };
  43276. RenderTargetTexture.prototype._shouldRender = function () {
  43277. if (this._currentRefreshId === -1) {
  43278. this._currentRefreshId = 1;
  43279. return true;
  43280. }
  43281. if (this.refreshRate === this._currentRefreshId) {
  43282. this._currentRefreshId = 1;
  43283. return true;
  43284. }
  43285. this._currentRefreshId++;
  43286. return false;
  43287. };
  43288. RenderTargetTexture.prototype.isReady = function () {
  43289. if (!this.getScene().renderTargetsEnabled) {
  43290. return false;
  43291. }
  43292. return _super.prototype.isReady.call(this);
  43293. };
  43294. RenderTargetTexture.prototype.getRenderSize = function () {
  43295. return this._size;
  43296. };
  43297. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  43298. get: function () {
  43299. return true;
  43300. },
  43301. enumerable: true,
  43302. configurable: true
  43303. });
  43304. RenderTargetTexture.prototype.scale = function (ratio) {
  43305. var newSize = this._size * ratio;
  43306. this.resize(newSize);
  43307. };
  43308. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  43309. if (this.isCube) {
  43310. return this._textureMatrix;
  43311. }
  43312. return _super.prototype.getReflectionTextureMatrix.call(this);
  43313. };
  43314. RenderTargetTexture.prototype.resize = function (size) {
  43315. this.releaseInternalTexture();
  43316. if (this.isCube) {
  43317. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  43318. }
  43319. else {
  43320. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  43321. }
  43322. };
  43323. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  43324. var scene = this.getScene();
  43325. var engine = scene.getEngine();
  43326. if (this.useCameraPostProcesses !== undefined) {
  43327. useCameraPostProcess = this.useCameraPostProcesses;
  43328. }
  43329. if (this._waitingRenderList) {
  43330. this.renderList = [];
  43331. for (var index = 0; index < this._waitingRenderList.length; index++) {
  43332. var id = this._waitingRenderList[index];
  43333. this.renderList.push(scene.getMeshByID(id));
  43334. }
  43335. delete this._waitingRenderList;
  43336. }
  43337. // Is predicate defined?
  43338. if (this.renderListPredicate) {
  43339. this.renderList.splice(0); // Clear previous renderList
  43340. var sceneMeshes = this.getScene().meshes;
  43341. for (var index = 0; index < sceneMeshes.length; index++) {
  43342. var mesh = sceneMeshes[index];
  43343. if (this.renderListPredicate(mesh)) {
  43344. this.renderList.push(mesh);
  43345. }
  43346. }
  43347. }
  43348. if (this.renderList && this.renderList.length === 0) {
  43349. return;
  43350. }
  43351. // Set custom projection.
  43352. // Needs to be before binding to prevent changing the aspect ratio.
  43353. var camera;
  43354. if (this.activeCamera) {
  43355. camera = this.activeCamera;
  43356. engine.setViewport(this.activeCamera.viewport);
  43357. if (this.activeCamera !== scene.activeCamera) {
  43358. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  43359. }
  43360. }
  43361. else {
  43362. camera = scene.activeCamera;
  43363. engine.setViewport(scene.activeCamera.viewport);
  43364. }
  43365. // Prepare renderingManager
  43366. this._renderingManager.reset();
  43367. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  43368. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  43369. var sceneRenderId = scene.getRenderId();
  43370. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  43371. var mesh = currentRenderList[meshIndex];
  43372. if (mesh) {
  43373. if (!mesh.isReady()) {
  43374. // Reset _currentRefreshId
  43375. this.resetRefreshCounter();
  43376. continue;
  43377. }
  43378. mesh._preActivateForIntermediateRendering(sceneRenderId);
  43379. var isMasked = void 0;
  43380. if (!this.renderList) {
  43381. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  43382. }
  43383. else {
  43384. isMasked = false;
  43385. }
  43386. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  43387. mesh._activate(sceneRenderId);
  43388. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  43389. var subMesh = mesh.subMeshes[subIndex];
  43390. scene._activeIndices.addCount(subMesh.indexCount, false);
  43391. this._renderingManager.dispatch(subMesh);
  43392. }
  43393. }
  43394. }
  43395. }
  43396. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  43397. var particleSystem = scene.particleSystems[particleIndex];
  43398. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  43399. continue;
  43400. }
  43401. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  43402. this._renderingManager.dispatchParticles(particleSystem);
  43403. }
  43404. }
  43405. if (this.isCube) {
  43406. for (var face = 0; face < 6; face++) {
  43407. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  43408. scene.incrementRenderId();
  43409. scene.resetCachedMaterial();
  43410. }
  43411. }
  43412. else {
  43413. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  43414. }
  43415. this.onAfterUnbindObservable.notifyObservers(this);
  43416. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  43417. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  43418. }
  43419. engine.setViewport(scene.activeCamera.viewport);
  43420. scene.resetCachedMaterial();
  43421. };
  43422. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  43423. var _this = this;
  43424. var scene = this.getScene();
  43425. var engine = scene.getEngine();
  43426. // Bind
  43427. if (this._postProcessManager) {
  43428. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  43429. }
  43430. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  43431. if (this.isCube) {
  43432. engine.bindFramebuffer(this._texture, faceIndex);
  43433. }
  43434. else {
  43435. engine.bindFramebuffer(this._texture);
  43436. }
  43437. }
  43438. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  43439. // Clear
  43440. if (this.onClearObservable.hasObservers()) {
  43441. this.onClearObservable.notifyObservers(engine);
  43442. }
  43443. else {
  43444. engine.clear(scene.clearColor, true, true, true);
  43445. }
  43446. if (!this._doNotChangeAspectRatio) {
  43447. scene.updateTransformMatrix(true);
  43448. }
  43449. // Render
  43450. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  43451. if (this._postProcessManager) {
  43452. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  43453. }
  43454. else if (useCameraPostProcess) {
  43455. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  43456. }
  43457. if (!this._doNotChangeAspectRatio) {
  43458. scene.updateTransformMatrix(true);
  43459. }
  43460. // Dump ?
  43461. if (dumpForDebug) {
  43462. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  43463. }
  43464. // Unbind
  43465. if (!this.isCube || faceIndex === 5) {
  43466. if (this.isCube) {
  43467. if (faceIndex === 5) {
  43468. engine.generateMipMapsForCubemap(this._texture);
  43469. }
  43470. }
  43471. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  43472. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  43473. });
  43474. }
  43475. else {
  43476. this.onAfterRenderObservable.notifyObservers(faceIndex);
  43477. }
  43478. };
  43479. /**
  43480. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  43481. * This allowed control for front to back rendering or reversly depending of the special needs.
  43482. *
  43483. * @param renderingGroupId The rendering group id corresponding to its index
  43484. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  43485. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  43486. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  43487. */
  43488. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  43489. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  43490. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  43491. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  43492. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  43493. };
  43494. /**
  43495. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  43496. *
  43497. * @param renderingGroupId The rendering group id corresponding to its index
  43498. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  43499. */
  43500. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  43501. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  43502. };
  43503. RenderTargetTexture.prototype.clone = function () {
  43504. var textureSize = this.getSize();
  43505. 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);
  43506. // Base texture
  43507. newTexture.hasAlpha = this.hasAlpha;
  43508. newTexture.level = this.level;
  43509. // RenderTarget Texture
  43510. newTexture.coordinatesMode = this.coordinatesMode;
  43511. newTexture.renderList = this.renderList.slice(0);
  43512. return newTexture;
  43513. };
  43514. RenderTargetTexture.prototype.serialize = function () {
  43515. if (!this.name) {
  43516. return null;
  43517. }
  43518. var serializationObject = _super.prototype.serialize.call(this);
  43519. serializationObject.renderTargetSize = this.getRenderSize();
  43520. serializationObject.renderList = [];
  43521. for (var index = 0; index < this.renderList.length; index++) {
  43522. serializationObject.renderList.push(this.renderList[index].id);
  43523. }
  43524. return serializationObject;
  43525. };
  43526. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  43527. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  43528. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  43529. };
  43530. RenderTargetTexture.prototype.dispose = function () {
  43531. if (this._postProcessManager) {
  43532. this._postProcessManager.dispose();
  43533. this._postProcessManager = null;
  43534. }
  43535. this.clearPostProcesses(true);
  43536. // Remove from custom render targets
  43537. var scene = this.getScene();
  43538. var index = scene.customRenderTargets.indexOf(this);
  43539. if (index >= 0) {
  43540. scene.customRenderTargets.splice(index, 1);
  43541. }
  43542. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  43543. var camera = _a[_i];
  43544. index = camera.customRenderTargets.indexOf(this);
  43545. if (index >= 0) {
  43546. camera.customRenderTargets.splice(index, 1);
  43547. }
  43548. }
  43549. _super.prototype.dispose.call(this);
  43550. };
  43551. return RenderTargetTexture;
  43552. }(BABYLON.Texture));
  43553. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  43554. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  43555. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  43556. BABYLON.RenderTargetTexture = RenderTargetTexture;
  43557. })(BABYLON || (BABYLON = {}));
  43558. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  43559. var BABYLON;
  43560. (function (BABYLON) {
  43561. ;
  43562. var MultiRenderTarget = (function (_super) {
  43563. __extends(MultiRenderTarget, _super);
  43564. function MultiRenderTarget(name, size, count, scene, options) {
  43565. var _this = this;
  43566. options = options || {};
  43567. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  43568. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  43569. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  43570. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  43571. if (!_this.isSupported) {
  43572. _this.dispose();
  43573. return;
  43574. }
  43575. var types = [];
  43576. var samplingModes = [];
  43577. for (var i = 0; i < count; i++) {
  43578. if (options.types && options.types[i]) {
  43579. types.push(options.types[i]);
  43580. }
  43581. else {
  43582. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  43583. }
  43584. if (options.samplingModes && options.samplingModes[i]) {
  43585. samplingModes.push(options.samplingModes[i]);
  43586. }
  43587. else {
  43588. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43589. }
  43590. }
  43591. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  43592. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  43593. _this._count = count;
  43594. _this._size = size;
  43595. _this._multiRenderTargetOptions = {
  43596. samplingModes: samplingModes,
  43597. generateMipMaps: generateMipMaps,
  43598. generateDepthBuffer: generateDepthBuffer,
  43599. generateStencilBuffer: generateStencilBuffer,
  43600. generateDepthTexture: generateDepthTexture,
  43601. types: types,
  43602. textureCount: count
  43603. };
  43604. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  43605. _this._createInternalTextures();
  43606. return _this;
  43607. }
  43608. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  43609. get: function () {
  43610. var engine = this.getScene().getEngine();
  43611. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  43612. },
  43613. enumerable: true,
  43614. configurable: true
  43615. });
  43616. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  43617. get: function () {
  43618. return this._textures;
  43619. },
  43620. enumerable: true,
  43621. configurable: true
  43622. });
  43623. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  43624. get: function () {
  43625. return this._textures[this._textures.length - 1];
  43626. },
  43627. enumerable: true,
  43628. configurable: true
  43629. });
  43630. MultiRenderTarget.prototype._createInternalTextures = function () {
  43631. this._textures = [];
  43632. for (var i = 0; i < this._webGLTextures.length; i++) {
  43633. var texture = new BABYLON.Texture(null, this.getScene());
  43634. texture._texture = this._webGLTextures[i];
  43635. this._textures.push(texture);
  43636. }
  43637. // Keeps references to frame buffer and stencil/depth buffer
  43638. this._texture = this._webGLTextures[0];
  43639. };
  43640. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  43641. get: function () {
  43642. return this._samples;
  43643. },
  43644. set: function (value) {
  43645. if (this._samples === value) {
  43646. return;
  43647. }
  43648. for (var i = 0; i < this._webGLTextures.length; i++) {
  43649. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  43650. }
  43651. },
  43652. enumerable: true,
  43653. configurable: true
  43654. });
  43655. MultiRenderTarget.prototype.resize = function (size) {
  43656. this.releaseInternalTextures();
  43657. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  43658. this._createInternalTextures();
  43659. };
  43660. MultiRenderTarget.prototype.dispose = function () {
  43661. this.releaseInternalTextures();
  43662. _super.prototype.dispose.call(this);
  43663. };
  43664. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  43665. if (!this._webGLTextures) {
  43666. return;
  43667. }
  43668. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  43669. if (this._webGLTextures[i] !== undefined) {
  43670. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  43671. this._webGLTextures.splice(i, 1);
  43672. }
  43673. }
  43674. };
  43675. return MultiRenderTarget;
  43676. }(BABYLON.RenderTargetTexture));
  43677. BABYLON.MultiRenderTarget = MultiRenderTarget;
  43678. })(BABYLON || (BABYLON = {}));
  43679. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  43680. /// <reference path="babylon.renderTargetTexture.ts" />
  43681. var BABYLON;
  43682. (function (BABYLON) {
  43683. var MirrorTexture = (function (_super) {
  43684. __extends(MirrorTexture, _super);
  43685. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  43686. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43687. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43688. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  43689. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  43690. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  43691. _this._transformMatrix = BABYLON.Matrix.Zero();
  43692. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  43693. _this._blurKernelX = 0;
  43694. _this._blurKernelY = 0;
  43695. _this._blurRatio = 1.0;
  43696. _this.onBeforeRenderObservable.add(function () {
  43697. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  43698. _this._savedViewMatrix = scene.getViewMatrix();
  43699. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  43700. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  43701. scene.clipPlane = _this.mirrorPlane;
  43702. scene.getEngine().cullBackFaces = false;
  43703. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  43704. });
  43705. _this.onAfterRenderObservable.add(function () {
  43706. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  43707. scene.getEngine().cullBackFaces = true;
  43708. scene._mirroredCameraPosition = null;
  43709. delete scene.clipPlane;
  43710. });
  43711. return _this;
  43712. }
  43713. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  43714. get: function () {
  43715. return this._blurRatio;
  43716. },
  43717. set: function (value) {
  43718. if (this._blurRatio === value) {
  43719. return;
  43720. }
  43721. this._blurRatio = value;
  43722. this._preparePostProcesses();
  43723. },
  43724. enumerable: true,
  43725. configurable: true
  43726. });
  43727. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  43728. set: function (value) {
  43729. this.blurKernelX = value;
  43730. this.blurKernelY = value;
  43731. },
  43732. enumerable: true,
  43733. configurable: true
  43734. });
  43735. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  43736. get: function () {
  43737. return this._blurKernelX;
  43738. },
  43739. set: function (value) {
  43740. if (this._blurKernelX === value) {
  43741. return;
  43742. }
  43743. this._blurKernelX = value;
  43744. this._preparePostProcesses();
  43745. },
  43746. enumerable: true,
  43747. configurable: true
  43748. });
  43749. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  43750. get: function () {
  43751. return this._blurKernelY;
  43752. },
  43753. set: function (value) {
  43754. if (this._blurKernelY === value) {
  43755. return;
  43756. }
  43757. this._blurKernelY = value;
  43758. this._preparePostProcesses();
  43759. },
  43760. enumerable: true,
  43761. configurable: true
  43762. });
  43763. MirrorTexture.prototype._preparePostProcesses = function () {
  43764. this.clearPostProcesses(true);
  43765. if (this._blurKernelX && this._blurKernelY) {
  43766. var engine = this.getScene().getEngine();
  43767. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  43768. 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);
  43769. this._blurX.autoClear = false;
  43770. if (this._blurRatio === 1 && this.samples < 2) {
  43771. this._blurX.outputTexture = this._texture;
  43772. }
  43773. else {
  43774. this._blurX.alwaysForcePOT = true;
  43775. }
  43776. 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);
  43777. this._blurY.autoClear = false;
  43778. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  43779. this.addPostProcess(this._blurX);
  43780. this.addPostProcess(this._blurY);
  43781. }
  43782. };
  43783. MirrorTexture.prototype.clone = function () {
  43784. var textureSize = this.getSize();
  43785. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  43786. // Base texture
  43787. newTexture.hasAlpha = this.hasAlpha;
  43788. newTexture.level = this.level;
  43789. // Mirror Texture
  43790. newTexture.mirrorPlane = this.mirrorPlane.clone();
  43791. newTexture.renderList = this.renderList.slice(0);
  43792. return newTexture;
  43793. };
  43794. MirrorTexture.prototype.serialize = function () {
  43795. if (!this.name) {
  43796. return null;
  43797. }
  43798. var serializationObject = _super.prototype.serialize.call(this);
  43799. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  43800. return serializationObject;
  43801. };
  43802. return MirrorTexture;
  43803. }(BABYLON.RenderTargetTexture));
  43804. BABYLON.MirrorTexture = MirrorTexture;
  43805. })(BABYLON || (BABYLON = {}));
  43806. //# sourceMappingURL=babylon.mirrorTexture.js.map
  43807. /// <reference path="babylon.renderTargetTexture.ts" />
  43808. var BABYLON;
  43809. (function (BABYLON) {
  43810. /**
  43811. * Creates a refraction texture used by refraction channel of the standard material.
  43812. * @param name the texture name
  43813. * @param size size of the underlying texture
  43814. * @param scene root scene
  43815. */
  43816. var RefractionTexture = (function (_super) {
  43817. __extends(RefractionTexture, _super);
  43818. function RefractionTexture(name, size, scene, generateMipMaps) {
  43819. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  43820. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  43821. _this.depth = 2.0;
  43822. _this.onBeforeRenderObservable.add(function () {
  43823. scene.clipPlane = _this.refractionPlane;
  43824. });
  43825. _this.onAfterRenderObservable.add(function () {
  43826. delete scene.clipPlane;
  43827. });
  43828. return _this;
  43829. }
  43830. RefractionTexture.prototype.clone = function () {
  43831. var textureSize = this.getSize();
  43832. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  43833. // Base texture
  43834. newTexture.hasAlpha = this.hasAlpha;
  43835. newTexture.level = this.level;
  43836. // Refraction Texture
  43837. newTexture.refractionPlane = this.refractionPlane.clone();
  43838. newTexture.renderList = this.renderList.slice(0);
  43839. newTexture.depth = this.depth;
  43840. return newTexture;
  43841. };
  43842. RefractionTexture.prototype.serialize = function () {
  43843. if (!this.name) {
  43844. return null;
  43845. }
  43846. var serializationObject = _super.prototype.serialize.call(this);
  43847. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  43848. serializationObject.depth = this.depth;
  43849. return serializationObject;
  43850. };
  43851. return RefractionTexture;
  43852. }(BABYLON.RenderTargetTexture));
  43853. BABYLON.RefractionTexture = RefractionTexture;
  43854. })(BABYLON || (BABYLON = {}));
  43855. //# sourceMappingURL=babylon.refractionTexture.js.map
  43856. /// <reference path="babylon.texture.ts" />
  43857. var BABYLON;
  43858. (function (BABYLON) {
  43859. var DynamicTexture = (function (_super) {
  43860. __extends(DynamicTexture, _super);
  43861. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  43862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43863. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  43864. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  43865. _this.name = name;
  43866. var engine = _this.getScene().getEngine();
  43867. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43868. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43869. _this._generateMipMaps = generateMipMaps;
  43870. if (options.getContext) {
  43871. _this._canvas = options;
  43872. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43873. }
  43874. else {
  43875. _this._canvas = document.createElement("canvas");
  43876. if (options.width) {
  43877. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43878. }
  43879. else {
  43880. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  43881. }
  43882. }
  43883. var textureSize = _this.getSize();
  43884. _this._canvas.width = textureSize.width;
  43885. _this._canvas.height = textureSize.height;
  43886. _this._context = _this._canvas.getContext("2d");
  43887. return _this;
  43888. }
  43889. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  43890. get: function () {
  43891. return true;
  43892. },
  43893. enumerable: true,
  43894. configurable: true
  43895. });
  43896. DynamicTexture.prototype._recreate = function (textureSize) {
  43897. this._canvas.width = textureSize.width;
  43898. this._canvas.height = textureSize.height;
  43899. this.releaseInternalTexture();
  43900. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  43901. };
  43902. DynamicTexture.prototype.scale = function (ratio) {
  43903. var textureSize = this.getSize();
  43904. textureSize.width *= ratio;
  43905. textureSize.height *= ratio;
  43906. this._recreate(textureSize);
  43907. };
  43908. DynamicTexture.prototype.scaleTo = function (width, height) {
  43909. var textureSize = this.getSize();
  43910. textureSize.width = width;
  43911. textureSize.height = height;
  43912. this._recreate(textureSize);
  43913. };
  43914. DynamicTexture.prototype.getContext = function () {
  43915. return this._context;
  43916. };
  43917. DynamicTexture.prototype.clear = function () {
  43918. var size = this.getSize();
  43919. this._context.fillRect(0, 0, size.width, size.height);
  43920. };
  43921. DynamicTexture.prototype.update = function (invertY) {
  43922. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  43923. };
  43924. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  43925. if (update === void 0) { update = true; }
  43926. var size = this.getSize();
  43927. if (clearColor) {
  43928. this._context.fillStyle = clearColor;
  43929. this._context.fillRect(0, 0, size.width, size.height);
  43930. }
  43931. this._context.font = font;
  43932. if (x === null || x === undefined) {
  43933. var textSize = this._context.measureText(text);
  43934. x = (size.width - textSize.width) / 2;
  43935. }
  43936. if (y === null || y === undefined) {
  43937. var fontSize = parseInt((font.replace(/\D/g, '')));
  43938. ;
  43939. y = (size.height / 2) + (fontSize / 3.65);
  43940. }
  43941. this._context.fillStyle = color;
  43942. this._context.fillText(text, x, y);
  43943. if (update) {
  43944. this.update(invertY);
  43945. }
  43946. };
  43947. DynamicTexture.prototype.clone = function () {
  43948. var textureSize = this.getSize();
  43949. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  43950. // Base texture
  43951. newTexture.hasAlpha = this.hasAlpha;
  43952. newTexture.level = this.level;
  43953. // Dynamic Texture
  43954. newTexture.wrapU = this.wrapU;
  43955. newTexture.wrapV = this.wrapV;
  43956. return newTexture;
  43957. };
  43958. return DynamicTexture;
  43959. }(BABYLON.Texture));
  43960. BABYLON.DynamicTexture = DynamicTexture;
  43961. })(BABYLON || (BABYLON = {}));
  43962. //# sourceMappingURL=babylon.dynamicTexture.js.map
  43963. var BABYLON;
  43964. (function (BABYLON) {
  43965. var VideoTexture = (function (_super) {
  43966. __extends(VideoTexture, _super);
  43967. /**
  43968. * Creates a video texture.
  43969. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  43970. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  43971. * @param {BABYLON.Scene} scene is obviously the current scene.
  43972. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  43973. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  43974. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  43975. */
  43976. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  43977. if (generateMipMaps === void 0) { generateMipMaps = false; }
  43978. if (invertY === void 0) { invertY = false; }
  43979. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43980. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43981. _this._autoLaunch = true;
  43982. var urls;
  43983. _this.name = name;
  43984. if (urlsOrVideo instanceof HTMLVideoElement) {
  43985. _this.video = urlsOrVideo;
  43986. }
  43987. else {
  43988. urls = urlsOrVideo;
  43989. _this.video = document.createElement("video");
  43990. _this.video.autoplay = false;
  43991. _this.video.loop = true;
  43992. }
  43993. _this._generateMipMaps = generateMipMaps;
  43994. _this._samplingMode = samplingMode;
  43995. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  43996. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  43997. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  43998. }
  43999. else {
  44000. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44001. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44002. _this._generateMipMaps = false;
  44003. }
  44004. if (urls) {
  44005. _this.video.addEventListener("canplay", function () {
  44006. _this._createTexture();
  44007. });
  44008. urls.forEach(function (url) {
  44009. var source = document.createElement("source");
  44010. source.src = url;
  44011. _this.video.appendChild(source);
  44012. });
  44013. }
  44014. else {
  44015. _this._createTexture();
  44016. }
  44017. _this._lastUpdate = BABYLON.Tools.Now;
  44018. return _this;
  44019. }
  44020. VideoTexture.prototype.__setTextureReady = function () {
  44021. this._texture.isReady = true;
  44022. };
  44023. VideoTexture.prototype._createTexture = function () {
  44024. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  44025. if (this._autoLaunch) {
  44026. this._autoLaunch = false;
  44027. this.video.play();
  44028. }
  44029. this._setTextureReady = this.__setTextureReady.bind(this);
  44030. this.video.addEventListener("playing", this._setTextureReady);
  44031. };
  44032. VideoTexture.prototype.update = function () {
  44033. var now = BABYLON.Tools.Now;
  44034. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  44035. return false;
  44036. }
  44037. this._lastUpdate = now;
  44038. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  44039. return true;
  44040. };
  44041. VideoTexture.prototype.dispose = function () {
  44042. _super.prototype.dispose.call(this);
  44043. this.video.removeEventListener("playing", this._setTextureReady);
  44044. };
  44045. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  44046. var video = document.createElement("video");
  44047. var constraintsDeviceId;
  44048. if (constraints && constraints.deviceId) {
  44049. constraintsDeviceId = {
  44050. exact: constraints.deviceId
  44051. };
  44052. }
  44053. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  44054. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  44055. if (navigator.getUserMedia) {
  44056. navigator.getUserMedia({
  44057. video: {
  44058. deviceId: constraintsDeviceId,
  44059. width: {
  44060. min: (constraints && constraints.minWidth) || 256,
  44061. max: (constraints && constraints.maxWidth) || 640
  44062. },
  44063. height: {
  44064. min: (constraints && constraints.minHeight) || 256,
  44065. max: (constraints && constraints.maxHeight) || 480
  44066. }
  44067. }
  44068. }, function (stream) {
  44069. if (video.mozSrcObject !== undefined) {
  44070. video.mozSrcObject = stream;
  44071. }
  44072. else {
  44073. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  44074. }
  44075. video.play();
  44076. if (onReady) {
  44077. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  44078. }
  44079. }, function (e) {
  44080. BABYLON.Tools.Error(e.name);
  44081. });
  44082. }
  44083. };
  44084. return VideoTexture;
  44085. }(BABYLON.Texture));
  44086. BABYLON.VideoTexture = VideoTexture;
  44087. })(BABYLON || (BABYLON = {}));
  44088. //# sourceMappingURL=babylon.videoTexture.js.map
  44089. var BABYLON;
  44090. (function (BABYLON) {
  44091. var RawTexture = (function (_super) {
  44092. __extends(RawTexture, _super);
  44093. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  44094. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44095. if (invertY === void 0) { invertY = false; }
  44096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44097. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  44098. _this.format = format;
  44099. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  44100. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44101. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44102. return _this;
  44103. }
  44104. RawTexture.prototype.update = function (data) {
  44105. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  44106. };
  44107. // Statics
  44108. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44109. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44110. if (invertY === void 0) { invertY = false; }
  44111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44112. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  44113. };
  44114. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44115. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44116. if (invertY === void 0) { invertY = false; }
  44117. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44118. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44119. };
  44120. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44121. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44122. if (invertY === void 0) { invertY = false; }
  44123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44124. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44125. };
  44126. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44127. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44128. if (invertY === void 0) { invertY = false; }
  44129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44130. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  44131. };
  44132. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44133. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44134. if (invertY === void 0) { invertY = false; }
  44135. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44136. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  44137. };
  44138. return RawTexture;
  44139. }(BABYLON.Texture));
  44140. BABYLON.RawTexture = RawTexture;
  44141. })(BABYLON || (BABYLON = {}));
  44142. //# sourceMappingURL=babylon.rawTexture.js.map
  44143. var BABYLON;
  44144. (function (BABYLON) {
  44145. var PostProcess = (function () {
  44146. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  44147. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  44148. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44149. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  44150. if (blockCompilation === void 0) { blockCompilation = false; }
  44151. this.name = name;
  44152. this.width = -1;
  44153. this.height = -1;
  44154. this.autoClear = true;
  44155. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  44156. /*
  44157. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  44158. Can only be used on a single postprocess or on the last one of a chain.
  44159. */
  44160. this.enablePixelPerfectMode = false;
  44161. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  44162. this.alwaysForcePOT = false;
  44163. this.samples = 1;
  44164. this._reusable = false;
  44165. this._textures = new BABYLON.SmartArray(2);
  44166. this._currentRenderTextureInd = 0;
  44167. this._scaleRatio = new BABYLON.Vector2(1, 1);
  44168. this._texelSize = BABYLON.Vector2.Zero();
  44169. // Events
  44170. /**
  44171. * An event triggered when the postprocess is activated.
  44172. * @type {BABYLON.Observable}
  44173. */
  44174. this.onActivateObservable = new BABYLON.Observable();
  44175. /**
  44176. * An event triggered when the postprocess changes its size.
  44177. * @type {BABYLON.Observable}
  44178. */
  44179. this.onSizeChangedObservable = new BABYLON.Observable();
  44180. /**
  44181. * An event triggered when the postprocess applies its effect.
  44182. * @type {BABYLON.Observable}
  44183. */
  44184. this.onApplyObservable = new BABYLON.Observable();
  44185. /**
  44186. * An event triggered before rendering the postprocess
  44187. * @type {BABYLON.Observable}
  44188. */
  44189. this.onBeforeRenderObservable = new BABYLON.Observable();
  44190. /**
  44191. * An event triggered after rendering the postprocess
  44192. * @type {BABYLON.Observable}
  44193. */
  44194. this.onAfterRenderObservable = new BABYLON.Observable();
  44195. if (camera != null) {
  44196. this._camera = camera;
  44197. this._scene = camera.getScene();
  44198. camera.attachPostProcess(this);
  44199. this._engine = this._scene.getEngine();
  44200. }
  44201. else {
  44202. this._engine = engine;
  44203. }
  44204. this._options = options;
  44205. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  44206. this._reusable = reusable || false;
  44207. this._textureType = textureType;
  44208. this._samplers = samplers || [];
  44209. this._samplers.push("textureSampler");
  44210. this._fragmentUrl = fragmentUrl;
  44211. this._vertexUrl = vertexUrl;
  44212. this._parameters = parameters || [];
  44213. this._parameters.push("scale");
  44214. this._indexParameters = indexParameters;
  44215. if (!blockCompilation) {
  44216. this.updateEffect(defines);
  44217. }
  44218. }
  44219. Object.defineProperty(PostProcess.prototype, "onActivate", {
  44220. set: function (callback) {
  44221. if (this._onActivateObserver) {
  44222. this.onActivateObservable.remove(this._onActivateObserver);
  44223. }
  44224. this._onActivateObserver = this.onActivateObservable.add(callback);
  44225. },
  44226. enumerable: true,
  44227. configurable: true
  44228. });
  44229. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  44230. set: function (callback) {
  44231. if (this._onSizeChangedObserver) {
  44232. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  44233. }
  44234. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  44235. },
  44236. enumerable: true,
  44237. configurable: true
  44238. });
  44239. Object.defineProperty(PostProcess.prototype, "onApply", {
  44240. set: function (callback) {
  44241. if (this._onApplyObserver) {
  44242. this.onApplyObservable.remove(this._onApplyObserver);
  44243. }
  44244. this._onApplyObserver = this.onApplyObservable.add(callback);
  44245. },
  44246. enumerable: true,
  44247. configurable: true
  44248. });
  44249. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  44250. set: function (callback) {
  44251. if (this._onBeforeRenderObserver) {
  44252. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  44253. }
  44254. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  44255. },
  44256. enumerable: true,
  44257. configurable: true
  44258. });
  44259. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  44260. set: function (callback) {
  44261. if (this._onAfterRenderObserver) {
  44262. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  44263. }
  44264. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  44265. },
  44266. enumerable: true,
  44267. configurable: true
  44268. });
  44269. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  44270. get: function () {
  44271. return this._textures.data[this._currentRenderTextureInd];
  44272. },
  44273. set: function (value) {
  44274. this._forcedOutputTexture = value;
  44275. },
  44276. enumerable: true,
  44277. configurable: true
  44278. });
  44279. PostProcess.prototype.getCamera = function () {
  44280. return this._camera;
  44281. };
  44282. Object.defineProperty(PostProcess.prototype, "texelSize", {
  44283. get: function () {
  44284. if (this._shareOutputWithPostProcess) {
  44285. return this._shareOutputWithPostProcess.texelSize;
  44286. }
  44287. if (this._forcedOutputTexture) {
  44288. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  44289. }
  44290. return this._texelSize;
  44291. },
  44292. enumerable: true,
  44293. configurable: true
  44294. });
  44295. PostProcess.prototype.getEngine = function () {
  44296. return this._engine;
  44297. };
  44298. PostProcess.prototype.getEffect = function () {
  44299. return this._effect;
  44300. };
  44301. PostProcess.prototype.shareOutputWith = function (postProcess) {
  44302. this._disposeTextures();
  44303. this._shareOutputWithPostProcess = postProcess;
  44304. return this;
  44305. };
  44306. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  44307. 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);
  44308. };
  44309. PostProcess.prototype.isReusable = function () {
  44310. return this._reusable;
  44311. };
  44312. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  44313. PostProcess.prototype.markTextureDirty = function () {
  44314. this.width = -1;
  44315. };
  44316. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  44317. var _this = this;
  44318. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  44319. camera = camera || this._camera;
  44320. var scene = camera.getScene();
  44321. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  44322. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  44323. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  44324. var desiredWidth = this._options.width || requiredWidth;
  44325. var desiredHeight = this._options.height || requiredHeight;
  44326. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  44327. if (!this._options.width) {
  44328. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  44329. }
  44330. if (!this._options.height) {
  44331. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  44332. }
  44333. }
  44334. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  44335. if (this._textures.length > 0) {
  44336. for (var i = 0; i < this._textures.length; i++) {
  44337. this._engine._releaseTexture(this._textures.data[i]);
  44338. }
  44339. this._textures.reset();
  44340. }
  44341. this.width = desiredWidth;
  44342. this.height = desiredHeight;
  44343. var textureSize = { width: this.width, height: this.height };
  44344. var textureOptions = {
  44345. generateMipMaps: false,
  44346. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  44347. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  44348. samplingMode: this.renderTargetSamplingMode,
  44349. type: this._textureType
  44350. };
  44351. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  44352. if (this._reusable) {
  44353. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  44354. }
  44355. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  44356. this.onSizeChangedObservable.notifyObservers(this);
  44357. }
  44358. this._textures.forEach(function (texture) {
  44359. if (texture.samples !== _this.samples) {
  44360. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  44361. }
  44362. });
  44363. }
  44364. var target;
  44365. if (this._shareOutputWithPostProcess) {
  44366. target = this._shareOutputWithPostProcess.outputTexture;
  44367. }
  44368. else if (this._forcedOutputTexture) {
  44369. target = this._forcedOutputTexture;
  44370. this.width = this._forcedOutputTexture._width;
  44371. this.height = this._forcedOutputTexture._height;
  44372. }
  44373. else {
  44374. target = this.outputTexture;
  44375. }
  44376. if (this.enablePixelPerfectMode) {
  44377. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  44378. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  44379. }
  44380. else {
  44381. this._scaleRatio.copyFromFloats(1, 1);
  44382. this._engine.bindFramebuffer(target);
  44383. }
  44384. this.onActivateObservable.notifyObservers(camera);
  44385. // Clear
  44386. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  44387. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  44388. }
  44389. if (this._reusable) {
  44390. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  44391. }
  44392. };
  44393. Object.defineProperty(PostProcess.prototype, "isSupported", {
  44394. get: function () {
  44395. return this._effect.isSupported;
  44396. },
  44397. enumerable: true,
  44398. configurable: true
  44399. });
  44400. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  44401. get: function () {
  44402. if (this._shareOutputWithPostProcess) {
  44403. return this._shareOutputWithPostProcess.aspectRatio;
  44404. }
  44405. if (this._forcedOutputTexture) {
  44406. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  44407. }
  44408. return this.width / this.height;
  44409. },
  44410. enumerable: true,
  44411. configurable: true
  44412. });
  44413. PostProcess.prototype.apply = function () {
  44414. // Check
  44415. if (!this._effect || !this._effect.isReady())
  44416. return null;
  44417. // States
  44418. this._engine.enableEffect(this._effect);
  44419. this._engine.setState(false);
  44420. this._engine.setDepthBuffer(false);
  44421. this._engine.setDepthWrite(false);
  44422. // Alpha
  44423. this._engine.setAlphaMode(this.alphaMode);
  44424. if (this.alphaConstants) {
  44425. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  44426. }
  44427. // Texture
  44428. var source;
  44429. if (this._shareOutputWithPostProcess) {
  44430. source = this._shareOutputWithPostProcess.outputTexture;
  44431. }
  44432. else if (this._forcedOutputTexture) {
  44433. source = this._forcedOutputTexture;
  44434. }
  44435. else {
  44436. source = this.outputTexture;
  44437. }
  44438. this._effect._bindTexture("textureSampler", source);
  44439. // Parameters
  44440. this._effect.setVector2("scale", this._scaleRatio);
  44441. this.onApplyObservable.notifyObservers(this._effect);
  44442. return this._effect;
  44443. };
  44444. PostProcess.prototype._disposeTextures = function () {
  44445. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  44446. return;
  44447. }
  44448. if (this._textures.length > 0) {
  44449. for (var i = 0; i < this._textures.length; i++) {
  44450. this._engine._releaseTexture(this._textures.data[i]);
  44451. }
  44452. }
  44453. this._textures.dispose();
  44454. };
  44455. PostProcess.prototype.dispose = function (camera) {
  44456. camera = camera || this._camera;
  44457. this._disposeTextures();
  44458. if (!camera) {
  44459. return;
  44460. }
  44461. camera.detachPostProcess(this);
  44462. var index = camera._postProcesses.indexOf(this);
  44463. if (index === 0 && camera._postProcesses.length > 0) {
  44464. this._camera._postProcesses[0].markTextureDirty();
  44465. }
  44466. this.onActivateObservable.clear();
  44467. this.onAfterRenderObservable.clear();
  44468. this.onApplyObservable.clear();
  44469. this.onBeforeRenderObservable.clear();
  44470. this.onSizeChangedObservable.clear();
  44471. };
  44472. return PostProcess;
  44473. }());
  44474. BABYLON.PostProcess = PostProcess;
  44475. })(BABYLON || (BABYLON = {}));
  44476. //# sourceMappingURL=babylon.postProcess.js.map
  44477. var BABYLON;
  44478. (function (BABYLON) {
  44479. var PassPostProcess = (function (_super) {
  44480. __extends(PassPostProcess, _super);
  44481. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  44482. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44483. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  44484. }
  44485. return PassPostProcess;
  44486. }(BABYLON.PostProcess));
  44487. BABYLON.PassPostProcess = PassPostProcess;
  44488. })(BABYLON || (BABYLON = {}));
  44489. //# sourceMappingURL=babylon.passPostProcess.js.map
  44490. var BABYLON;
  44491. (function (BABYLON) {
  44492. var ShadowGenerator = (function () {
  44493. /**
  44494. * Creates a ShadowGenerator object.
  44495. * A ShadowGenerator is the required tool to use the shadows.
  44496. * Each light casting shadows needs to use its own ShadowGenerator.
  44497. * Required parameters :
  44498. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  44499. * - `light`: the light object generating the shadows.
  44500. * - `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.
  44501. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  44502. */
  44503. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  44504. // Members
  44505. this._bias = 0.00005;
  44506. this._blurBoxOffset = 1;
  44507. this._blurScale = 2;
  44508. this._blurKernel = 1;
  44509. this._useKernelBlur = false;
  44510. this._filter = ShadowGenerator.FILTER_NONE;
  44511. this._darkness = 0;
  44512. this._transparencyShadow = false;
  44513. this.forceBackFacesOnly = false;
  44514. this._lightDirection = BABYLON.Vector3.Zero();
  44515. this._viewMatrix = BABYLON.Matrix.Zero();
  44516. this._projectionMatrix = BABYLON.Matrix.Zero();
  44517. this._transformMatrix = BABYLON.Matrix.Zero();
  44518. this._worldViewProjection = BABYLON.Matrix.Zero();
  44519. this._currentFaceIndex = 0;
  44520. this._currentFaceIndexCache = 0;
  44521. this._isCube = false;
  44522. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  44523. this._mapSize = mapSize;
  44524. this._light = light;
  44525. this._scene = light.getScene();
  44526. light._shadowGenerator = this;
  44527. // Texture type fallback from float to int if not supported.
  44528. var caps = this._scene.getEngine().getCaps();
  44529. if (!useFullFloatFirst) {
  44530. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  44531. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  44532. }
  44533. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  44534. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44535. }
  44536. else {
  44537. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44538. }
  44539. }
  44540. else {
  44541. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  44542. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44543. }
  44544. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  44545. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  44546. }
  44547. else {
  44548. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44549. }
  44550. }
  44551. this._initializeGenerator();
  44552. }
  44553. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  44554. // Static
  44555. get: function () {
  44556. return ShadowGenerator._FILTER_NONE;
  44557. },
  44558. enumerable: true,
  44559. configurable: true
  44560. });
  44561. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  44562. get: function () {
  44563. return ShadowGenerator._FILTER_POISSONSAMPLING;
  44564. },
  44565. enumerable: true,
  44566. configurable: true
  44567. });
  44568. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  44569. get: function () {
  44570. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  44571. },
  44572. enumerable: true,
  44573. configurable: true
  44574. });
  44575. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  44576. get: function () {
  44577. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  44578. },
  44579. enumerable: true,
  44580. configurable: true
  44581. });
  44582. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  44583. get: function () {
  44584. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  44585. },
  44586. enumerable: true,
  44587. configurable: true
  44588. });
  44589. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  44590. get: function () {
  44591. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  44592. },
  44593. enumerable: true,
  44594. configurable: true
  44595. });
  44596. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  44597. get: function () {
  44598. return this._bias;
  44599. },
  44600. set: function (bias) {
  44601. this._bias = bias;
  44602. },
  44603. enumerable: true,
  44604. configurable: true
  44605. });
  44606. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  44607. get: function () {
  44608. return this._blurBoxOffset;
  44609. },
  44610. set: function (value) {
  44611. if (this._blurBoxOffset === value) {
  44612. return;
  44613. }
  44614. this._blurBoxOffset = value;
  44615. this._disposeBlurPostProcesses();
  44616. },
  44617. enumerable: true,
  44618. configurable: true
  44619. });
  44620. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  44621. get: function () {
  44622. return this._blurScale;
  44623. },
  44624. set: function (value) {
  44625. if (this._blurScale === value) {
  44626. return;
  44627. }
  44628. this._blurScale = value;
  44629. this._disposeBlurPostProcesses();
  44630. },
  44631. enumerable: true,
  44632. configurable: true
  44633. });
  44634. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  44635. get: function () {
  44636. return this._blurKernel;
  44637. },
  44638. set: function (value) {
  44639. if (this._blurKernel === value) {
  44640. return;
  44641. }
  44642. this._blurKernel = value;
  44643. this._disposeBlurPostProcesses();
  44644. },
  44645. enumerable: true,
  44646. configurable: true
  44647. });
  44648. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  44649. get: function () {
  44650. return this._useKernelBlur;
  44651. },
  44652. set: function (value) {
  44653. if (this._useKernelBlur === value) {
  44654. return;
  44655. }
  44656. this._useKernelBlur = value;
  44657. this._disposeBlurPostProcesses();
  44658. },
  44659. enumerable: true,
  44660. configurable: true
  44661. });
  44662. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  44663. get: function () {
  44664. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  44665. },
  44666. set: function (value) {
  44667. this._depthScale = value;
  44668. },
  44669. enumerable: true,
  44670. configurable: true
  44671. });
  44672. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  44673. get: function () {
  44674. return this._filter;
  44675. },
  44676. set: function (value) {
  44677. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  44678. if (this._light.needCube()) {
  44679. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  44680. this.useExponentialShadowMap = true;
  44681. return;
  44682. }
  44683. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  44684. this.useCloseExponentialShadowMap = true;
  44685. return;
  44686. }
  44687. }
  44688. if (this._filter === value) {
  44689. return;
  44690. }
  44691. this._filter = value;
  44692. this._disposeBlurPostProcesses();
  44693. this._applyFilterValues();
  44694. this._light._markMeshesAsLightDirty();
  44695. },
  44696. enumerable: true,
  44697. configurable: true
  44698. });
  44699. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  44700. get: function () {
  44701. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  44702. },
  44703. set: function (value) {
  44704. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  44705. },
  44706. enumerable: true,
  44707. configurable: true
  44708. });
  44709. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  44710. get: function () {
  44711. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  44712. return this.useExponentialShadowMap;
  44713. },
  44714. set: function (value) {
  44715. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  44716. this.useExponentialShadowMap = value;
  44717. },
  44718. enumerable: true,
  44719. configurable: true
  44720. });
  44721. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  44722. get: function () {
  44723. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  44724. return this.useBlurExponentialShadowMap;
  44725. },
  44726. set: function (value) {
  44727. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  44728. this.useBlurExponentialShadowMap = value;
  44729. },
  44730. enumerable: true,
  44731. configurable: true
  44732. });
  44733. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  44734. get: function () {
  44735. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  44736. },
  44737. set: function (value) {
  44738. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44739. },
  44740. enumerable: true,
  44741. configurable: true
  44742. });
  44743. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  44744. get: function () {
  44745. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  44746. },
  44747. set: function (value) {
  44748. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44749. },
  44750. enumerable: true,
  44751. configurable: true
  44752. });
  44753. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  44754. get: function () {
  44755. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  44756. },
  44757. set: function (value) {
  44758. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44759. },
  44760. enumerable: true,
  44761. configurable: true
  44762. });
  44763. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  44764. get: function () {
  44765. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  44766. },
  44767. set: function (value) {
  44768. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44769. },
  44770. enumerable: true,
  44771. configurable: true
  44772. });
  44773. /**
  44774. * Returns the darkness value (float).
  44775. */
  44776. ShadowGenerator.prototype.getDarkness = function () {
  44777. return this._darkness;
  44778. };
  44779. /**
  44780. * Sets the ShadowGenerator darkness value (float <= 1.0).
  44781. * Returns the ShadowGenerator.
  44782. */
  44783. ShadowGenerator.prototype.setDarkness = function (darkness) {
  44784. if (darkness >= 1.0)
  44785. this._darkness = 1.0;
  44786. else if (darkness <= 0.0)
  44787. this._darkness = 0.0;
  44788. else
  44789. this._darkness = darkness;
  44790. return this;
  44791. };
  44792. /**
  44793. * Sets the ability to have transparent shadow (boolean).
  44794. * Returns the ShadowGenerator.
  44795. */
  44796. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  44797. this._transparencyShadow = hasShadow;
  44798. return this;
  44799. };
  44800. /**
  44801. * Returns a RenderTargetTexture object : the shadow map texture.
  44802. */
  44803. ShadowGenerator.prototype.getShadowMap = function () {
  44804. return this._shadowMap;
  44805. };
  44806. /**
  44807. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  44808. */
  44809. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  44810. if (this._shadowMap2) {
  44811. return this._shadowMap2;
  44812. }
  44813. return this._shadowMap;
  44814. };
  44815. /**
  44816. * Returns the associated light object.
  44817. */
  44818. ShadowGenerator.prototype.getLight = function () {
  44819. return this._light;
  44820. };
  44821. ShadowGenerator.prototype._initializeGenerator = function () {
  44822. this._light._markMeshesAsLightDirty();
  44823. this._initializeShadowMap();
  44824. };
  44825. ShadowGenerator.prototype._initializeShadowMap = function () {
  44826. var _this = this;
  44827. // Render target
  44828. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  44829. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44830. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44831. this._shadowMap.anisotropicFilteringLevel = 1;
  44832. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44833. this._shadowMap.renderParticles = false;
  44834. // Record Face Index before render.
  44835. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  44836. _this._currentFaceIndex = faceIndex;
  44837. });
  44838. // Custom render function.
  44839. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  44840. // Blur if required afer render.
  44841. this._shadowMap.onAfterUnbindObservable.add(function () {
  44842. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  44843. return;
  44844. }
  44845. if (!_this._blurPostProcesses) {
  44846. _this._initializeBlurRTTAndPostProcesses();
  44847. }
  44848. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  44849. });
  44850. // Clear according to the chosen filter.
  44851. this._shadowMap.onClearObservable.add(function (engine) {
  44852. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  44853. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  44854. }
  44855. else {
  44856. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  44857. }
  44858. });
  44859. };
  44860. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  44861. var _this = this;
  44862. var engine = this._scene.getEngine();
  44863. var targetSize = this._mapSize / this.blurScale;
  44864. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  44865. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  44866. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44867. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44868. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44869. }
  44870. if (this.useKernelBlur) {
  44871. 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);
  44872. this._kernelBlurXPostprocess.width = targetSize;
  44873. this._kernelBlurXPostprocess.height = targetSize;
  44874. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  44875. effect.setTexture("textureSampler", _this._shadowMap);
  44876. });
  44877. 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);
  44878. this._kernelBlurXPostprocess.autoClear = false;
  44879. this._kernelBlurYPostprocess.autoClear = false;
  44880. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44881. this._kernelBlurXPostprocess.packedFloat = true;
  44882. this._kernelBlurYPostprocess.packedFloat = true;
  44883. }
  44884. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  44885. }
  44886. else {
  44887. 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);
  44888. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  44889. effect.setFloat2("screenSize", targetSize, targetSize);
  44890. effect.setTexture("textureSampler", _this._shadowMap);
  44891. });
  44892. this._boxBlurPostprocess.autoClear = false;
  44893. this._blurPostProcesses = [this._boxBlurPostprocess];
  44894. }
  44895. };
  44896. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  44897. var index;
  44898. for (index = 0; index < opaqueSubMeshes.length; index++) {
  44899. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  44900. }
  44901. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  44902. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  44903. }
  44904. if (this._transparencyShadow) {
  44905. for (index = 0; index < transparentSubMeshes.length; index++) {
  44906. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  44907. }
  44908. }
  44909. };
  44910. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  44911. var _this = this;
  44912. var mesh = subMesh.getRenderingMesh();
  44913. var scene = this._scene;
  44914. var engine = scene.getEngine();
  44915. // Culling
  44916. engine.setState(subMesh.getMaterial().backFaceCulling);
  44917. // Managing instances
  44918. var batch = mesh._getInstancesRenderList(subMesh._id);
  44919. if (batch.mustReturn) {
  44920. return;
  44921. }
  44922. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44923. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  44924. engine.enableEffect(this._effect);
  44925. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44926. var material = subMesh.getMaterial();
  44927. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  44928. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  44929. this._effect.setVector3("lightPosition", this.getLight().position);
  44930. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  44931. // Alpha test
  44932. if (material && material.needAlphaTesting()) {
  44933. var alphaTexture = material.getAlphaTestTexture();
  44934. if (alphaTexture) {
  44935. this._effect.setTexture("diffuseSampler", alphaTexture);
  44936. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  44937. }
  44938. }
  44939. // Bones
  44940. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44941. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44942. }
  44943. if (this.forceBackFacesOnly) {
  44944. engine.setState(true, 0, false, true);
  44945. }
  44946. // Draw
  44947. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  44948. if (this.forceBackFacesOnly) {
  44949. engine.setState(true, 0, false, false);
  44950. }
  44951. }
  44952. else {
  44953. // Need to reset refresh rate of the shadowMap
  44954. this._shadowMap.resetRefreshCounter();
  44955. }
  44956. };
  44957. ShadowGenerator.prototype._applyFilterValues = function () {
  44958. if (this.filter === ShadowGenerator.FILTER_NONE) {
  44959. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  44960. }
  44961. else {
  44962. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44963. }
  44964. };
  44965. /**
  44966. * Boolean : true when the ShadowGenerator is finally computed.
  44967. */
  44968. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  44969. var defines = [];
  44970. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44971. defines.push("#define FLOAT");
  44972. }
  44973. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44974. defines.push("#define ESM");
  44975. }
  44976. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44977. var mesh = subMesh.getMesh();
  44978. var material = subMesh.getMaterial();
  44979. // Alpha test
  44980. if (material && material.needAlphaTesting()) {
  44981. var alphaTexture = material.getAlphaTestTexture();
  44982. if (alphaTexture) {
  44983. defines.push("#define ALPHATEST");
  44984. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44985. attribs.push(BABYLON.VertexBuffer.UVKind);
  44986. defines.push("#define UV1");
  44987. }
  44988. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44989. if (alphaTexture.coordinatesIndex === 1) {
  44990. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44991. defines.push("#define UV2");
  44992. }
  44993. }
  44994. }
  44995. }
  44996. // Bones
  44997. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44998. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44999. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45000. if (mesh.numBoneInfluencers > 4) {
  45001. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45002. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45003. }
  45004. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45005. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45006. }
  45007. else {
  45008. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45009. }
  45010. // Instances
  45011. if (useInstances) {
  45012. defines.push("#define INSTANCES");
  45013. attribs.push("world0");
  45014. attribs.push("world1");
  45015. attribs.push("world2");
  45016. attribs.push("world3");
  45017. }
  45018. // Get correct effect
  45019. var join = defines.join("\n");
  45020. if (this._cachedDefines !== join) {
  45021. this._cachedDefines = join;
  45022. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  45023. }
  45024. return this._effect.isReady();
  45025. };
  45026. /**
  45027. * This creates the defines related to the standard BJS materials.
  45028. */
  45029. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  45030. var scene = this._scene;
  45031. var light = this._light;
  45032. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  45033. return;
  45034. }
  45035. defines["SHADOW" + lightIndex] = true;
  45036. if (this.usePoissonSampling) {
  45037. defines["SHADOWPCF" + lightIndex] = true;
  45038. }
  45039. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  45040. defines["SHADOWESM" + lightIndex] = true;
  45041. }
  45042. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  45043. defines["SHADOWCLOSEESM" + lightIndex] = true;
  45044. }
  45045. if (light.needCube()) {
  45046. defines["SHADOWCUBE" + lightIndex] = true;
  45047. }
  45048. };
  45049. /**
  45050. * This binds shadow lights related to the standard BJS materials.
  45051. * It implies the unifroms available on the materials are the standard BJS ones.
  45052. */
  45053. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  45054. var light = this._light;
  45055. var scene = this._scene;
  45056. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  45057. return;
  45058. }
  45059. if (!light.needCube()) {
  45060. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  45061. }
  45062. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  45063. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  45064. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  45065. };
  45066. // Methods
  45067. /**
  45068. * Returns a Matrix object : the updated transformation matrix.
  45069. */
  45070. ShadowGenerator.prototype.getTransformMatrix = function () {
  45071. var scene = this._scene;
  45072. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  45073. return this._transformMatrix;
  45074. }
  45075. this._currentRenderID = scene.getRenderId();
  45076. this._currentFaceIndexCache = this._currentFaceIndex;
  45077. var lightPosition = this._light.position;
  45078. if (this._light.computeTransformedInformation()) {
  45079. lightPosition = this._light.transformedPosition;
  45080. }
  45081. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  45082. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  45083. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  45084. }
  45085. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  45086. this._cachedPosition = lightPosition.clone();
  45087. this._cachedDirection = this._lightDirection.clone();
  45088. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  45089. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  45090. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  45091. }
  45092. return this._transformMatrix;
  45093. };
  45094. ShadowGenerator.prototype.recreateShadowMap = function () {
  45095. // Track render list.
  45096. var renderList = this._shadowMap.renderList;
  45097. // Clean up existing data.
  45098. this._disposeRTTandPostProcesses();
  45099. // Reinitializes.
  45100. this._initializeGenerator();
  45101. // Reaffect the filter to ensure a correct fallback if necessary.
  45102. this.filter = this.filter;
  45103. // Reaffect the filter.
  45104. this._applyFilterValues();
  45105. // Reaffect Render List.
  45106. this._shadowMap.renderList = renderList;
  45107. };
  45108. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  45109. if (this._shadowMap2) {
  45110. this._shadowMap2.dispose();
  45111. this._shadowMap2 = null;
  45112. }
  45113. if (this._downSamplePostprocess) {
  45114. this._downSamplePostprocess.dispose();
  45115. this._downSamplePostprocess = null;
  45116. }
  45117. if (this._boxBlurPostprocess) {
  45118. this._boxBlurPostprocess.dispose();
  45119. this._boxBlurPostprocess = null;
  45120. }
  45121. if (this._kernelBlurXPostprocess) {
  45122. this._kernelBlurXPostprocess.dispose();
  45123. this._kernelBlurXPostprocess = null;
  45124. }
  45125. if (this._kernelBlurYPostprocess) {
  45126. this._kernelBlurYPostprocess.dispose();
  45127. this._kernelBlurYPostprocess = null;
  45128. }
  45129. this._blurPostProcesses = null;
  45130. };
  45131. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  45132. if (this._shadowMap) {
  45133. this._shadowMap.dispose();
  45134. this._shadowMap = null;
  45135. }
  45136. this._disposeBlurPostProcesses();
  45137. };
  45138. /**
  45139. * Disposes the ShadowGenerator.
  45140. * Returns nothing.
  45141. */
  45142. ShadowGenerator.prototype.dispose = function () {
  45143. this._disposeRTTandPostProcesses();
  45144. this._light._shadowGenerator = null;
  45145. this._light._markMeshesAsLightDirty();
  45146. };
  45147. /**
  45148. * Serializes the ShadowGenerator and returns a serializationObject.
  45149. */
  45150. ShadowGenerator.prototype.serialize = function () {
  45151. var serializationObject = {};
  45152. var shadowMap = this.getShadowMap();
  45153. serializationObject.lightId = this._light.id;
  45154. serializationObject.mapSize = shadowMap.getRenderSize();
  45155. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  45156. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  45157. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  45158. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  45159. serializationObject.usePoissonSampling = this.usePoissonSampling;
  45160. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  45161. serializationObject.depthScale = this.depthScale;
  45162. serializationObject.darkness = this.getDarkness();
  45163. serializationObject.blurBoxOffset = this.blurBoxOffset;
  45164. serializationObject.blurKernel = this.blurKernel;
  45165. serializationObject.blurScale = this.blurScale;
  45166. serializationObject.useKernelBlur = this.useKernelBlur;
  45167. serializationObject.transparencyShadow = this._transparencyShadow;
  45168. serializationObject.renderList = [];
  45169. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  45170. var mesh = shadowMap.renderList[meshIndex];
  45171. serializationObject.renderList.push(mesh.id);
  45172. }
  45173. return serializationObject;
  45174. };
  45175. /**
  45176. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  45177. */
  45178. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  45179. //casting to point light, as light is missing the position attr and typescript complains.
  45180. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  45181. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  45182. var shadowMap = shadowGenerator.getShadowMap();
  45183. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  45184. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  45185. meshes.forEach(function (mesh) {
  45186. shadowMap.renderList.push(mesh);
  45187. });
  45188. }
  45189. if (parsedShadowGenerator.usePoissonSampling) {
  45190. shadowGenerator.usePoissonSampling = true;
  45191. }
  45192. else if (parsedShadowGenerator.useExponentialShadowMap) {
  45193. shadowGenerator.useExponentialShadowMap = true;
  45194. }
  45195. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  45196. shadowGenerator.useBlurExponentialShadowMap = true;
  45197. }
  45198. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  45199. shadowGenerator.useCloseExponentialShadowMap = true;
  45200. }
  45201. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  45202. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  45203. }
  45204. else if (parsedShadowGenerator.useVarianceShadowMap) {
  45205. shadowGenerator.useExponentialShadowMap = true;
  45206. }
  45207. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  45208. shadowGenerator.useBlurExponentialShadowMap = true;
  45209. }
  45210. if (parsedShadowGenerator.depthScale) {
  45211. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  45212. }
  45213. if (parsedShadowGenerator.blurScale) {
  45214. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  45215. }
  45216. if (parsedShadowGenerator.blurBoxOffset) {
  45217. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  45218. }
  45219. if (parsedShadowGenerator.useKernelBlur) {
  45220. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  45221. }
  45222. if (parsedShadowGenerator.blurKernel) {
  45223. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  45224. }
  45225. if (parsedShadowGenerator.bias !== undefined) {
  45226. shadowGenerator.bias = parsedShadowGenerator.bias;
  45227. }
  45228. if (parsedShadowGenerator.darkness) {
  45229. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  45230. }
  45231. if (parsedShadowGenerator.transparencyShadow) {
  45232. shadowGenerator.setTransparencyShadow(true);
  45233. }
  45234. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  45235. return shadowGenerator;
  45236. };
  45237. return ShadowGenerator;
  45238. }());
  45239. ShadowGenerator._FILTER_NONE = 0;
  45240. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  45241. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  45242. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  45243. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  45244. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  45245. BABYLON.ShadowGenerator = ShadowGenerator;
  45246. })(BABYLON || (BABYLON = {}));
  45247. //# sourceMappingURL=babylon.shadowGenerator.js.map
  45248. var BABYLON;
  45249. (function (BABYLON) {
  45250. var DefaultLoadingScreen = (function () {
  45251. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  45252. if (_loadingText === void 0) { _loadingText = ""; }
  45253. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  45254. var _this = this;
  45255. this._renderingCanvas = _renderingCanvas;
  45256. this._loadingText = _loadingText;
  45257. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  45258. // Resize
  45259. this._resizeLoadingUI = function () {
  45260. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  45261. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  45262. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  45263. _this._loadingDiv.style.left = canvasRect.left + "px";
  45264. _this._loadingDiv.style.top = canvasRect.top + "px";
  45265. _this._loadingDiv.style.width = canvasRect.width + "px";
  45266. _this._loadingDiv.style.height = canvasRect.height + "px";
  45267. };
  45268. }
  45269. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  45270. if (this._loadingDiv) {
  45271. // Do not add a loading screen if there is already one
  45272. return;
  45273. }
  45274. this._loadingDiv = document.createElement("div");
  45275. this._loadingDiv.id = "babylonjsLoadingDiv";
  45276. this._loadingDiv.style.opacity = "0";
  45277. this._loadingDiv.style.transition = "opacity 1.5s ease";
  45278. // Loading text
  45279. this._loadingTextDiv = document.createElement("div");
  45280. this._loadingTextDiv.style.position = "absolute";
  45281. this._loadingTextDiv.style.left = "0";
  45282. this._loadingTextDiv.style.top = "50%";
  45283. this._loadingTextDiv.style.marginTop = "80px";
  45284. this._loadingTextDiv.style.width = "100%";
  45285. this._loadingTextDiv.style.height = "20px";
  45286. this._loadingTextDiv.style.fontFamily = "Arial";
  45287. this._loadingTextDiv.style.fontSize = "14px";
  45288. this._loadingTextDiv.style.color = "white";
  45289. this._loadingTextDiv.style.textAlign = "center";
  45290. this._loadingTextDiv.innerHTML = "Loading";
  45291. this._loadingDiv.appendChild(this._loadingTextDiv);
  45292. //set the predefined text
  45293. this._loadingTextDiv.innerHTML = this._loadingText;
  45294. // Generating keyframes
  45295. var style = document.createElement('style');
  45296. style.type = 'text/css';
  45297. 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 }";
  45298. style.innerHTML = keyFrames;
  45299. document.getElementsByTagName('head')[0].appendChild(style);
  45300. // Loading img
  45301. var imgBack = new Image();
  45302. 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";
  45303. imgBack.style.position = "absolute";
  45304. imgBack.style.left = "50%";
  45305. imgBack.style.top = "50%";
  45306. imgBack.style.marginLeft = "-60px";
  45307. imgBack.style.marginTop = "-60px";
  45308. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  45309. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  45310. imgBack.style.transformOrigin = "50% 50%";
  45311. imgBack.style.webkitTransformOrigin = "50% 50%";
  45312. this._loadingDiv.appendChild(imgBack);
  45313. this._resizeLoadingUI();
  45314. window.addEventListener("resize", this._resizeLoadingUI);
  45315. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  45316. document.body.appendChild(this._loadingDiv);
  45317. this._loadingDiv.style.opacity = "1";
  45318. };
  45319. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  45320. var _this = this;
  45321. if (!this._loadingDiv) {
  45322. return;
  45323. }
  45324. var onTransitionEnd = function () {
  45325. if (!_this._loadingDiv) {
  45326. return;
  45327. }
  45328. document.body.removeChild(_this._loadingDiv);
  45329. window.removeEventListener("resize", _this._resizeLoadingUI);
  45330. _this._loadingDiv = null;
  45331. };
  45332. this._loadingDiv.style.opacity = "0";
  45333. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  45334. };
  45335. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  45336. set: function (text) {
  45337. this._loadingText = text;
  45338. if (this._loadingTextDiv) {
  45339. this._loadingTextDiv.innerHTML = this._loadingText;
  45340. }
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  45346. get: function () {
  45347. return this._loadingDivBackgroundColor;
  45348. },
  45349. set: function (color) {
  45350. this._loadingDivBackgroundColor = color;
  45351. if (!this._loadingDiv) {
  45352. return;
  45353. }
  45354. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  45355. },
  45356. enumerable: true,
  45357. configurable: true
  45358. });
  45359. return DefaultLoadingScreen;
  45360. }());
  45361. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  45362. })(BABYLON || (BABYLON = {}));
  45363. //# sourceMappingURL=babylon.loadingScreen.js.map
  45364. var BABYLON;
  45365. (function (BABYLON) {
  45366. var SceneLoader = (function () {
  45367. function SceneLoader() {
  45368. }
  45369. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  45370. get: function () {
  45371. return 0;
  45372. },
  45373. enumerable: true,
  45374. configurable: true
  45375. });
  45376. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  45377. get: function () {
  45378. return 1;
  45379. },
  45380. enumerable: true,
  45381. configurable: true
  45382. });
  45383. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  45384. get: function () {
  45385. return 2;
  45386. },
  45387. enumerable: true,
  45388. configurable: true
  45389. });
  45390. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  45391. get: function () {
  45392. return 3;
  45393. },
  45394. enumerable: true,
  45395. configurable: true
  45396. });
  45397. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  45398. get: function () {
  45399. return SceneLoader._ForceFullSceneLoadingForIncremental;
  45400. },
  45401. set: function (value) {
  45402. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  45403. },
  45404. enumerable: true,
  45405. configurable: true
  45406. });
  45407. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  45408. get: function () {
  45409. return SceneLoader._ShowLoadingScreen;
  45410. },
  45411. set: function (value) {
  45412. SceneLoader._ShowLoadingScreen = value;
  45413. },
  45414. enumerable: true,
  45415. configurable: true
  45416. });
  45417. Object.defineProperty(SceneLoader, "loggingLevel", {
  45418. get: function () {
  45419. return SceneLoader._loggingLevel;
  45420. },
  45421. set: function (value) {
  45422. SceneLoader._loggingLevel = value;
  45423. },
  45424. enumerable: true,
  45425. configurable: true
  45426. });
  45427. SceneLoader._getDefaultPlugin = function () {
  45428. return SceneLoader._registeredPlugins[".babylon"];
  45429. };
  45430. SceneLoader._getPluginForExtension = function (extension) {
  45431. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  45432. if (registeredPlugin) {
  45433. return registeredPlugin;
  45434. }
  45435. return SceneLoader._getDefaultPlugin();
  45436. };
  45437. SceneLoader._getPluginForDirectLoad = function (data) {
  45438. for (var extension in SceneLoader._registeredPlugins) {
  45439. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  45440. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  45441. return SceneLoader._registeredPlugins[extension];
  45442. }
  45443. }
  45444. return SceneLoader._getDefaultPlugin();
  45445. };
  45446. SceneLoader._getPluginForFilename = function (sceneFilename) {
  45447. if (sceneFilename.name) {
  45448. sceneFilename = sceneFilename.name;
  45449. }
  45450. var dotPosition = sceneFilename.lastIndexOf(".");
  45451. var queryStringPosition = sceneFilename.indexOf("?");
  45452. if (queryStringPosition === -1) {
  45453. queryStringPosition = sceneFilename.length;
  45454. }
  45455. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  45456. return SceneLoader._getPluginForExtension(extension);
  45457. };
  45458. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  45459. SceneLoader._getDirectLoad = function (sceneFilename) {
  45460. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  45461. return sceneFilename.substr(5);
  45462. }
  45463. return null;
  45464. };
  45465. // Public functions
  45466. SceneLoader.GetPluginForExtension = function (extension) {
  45467. return SceneLoader._getPluginForExtension(extension).plugin;
  45468. };
  45469. SceneLoader.RegisterPlugin = function (plugin) {
  45470. if (typeof plugin.extensions === "string") {
  45471. var extension = plugin.extensions;
  45472. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  45473. plugin: plugin,
  45474. isBinary: false
  45475. };
  45476. }
  45477. else {
  45478. var extensions = plugin.extensions;
  45479. Object.keys(extensions).forEach(function (extension) {
  45480. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  45481. plugin: plugin,
  45482. isBinary: extensions[extension].isBinary
  45483. };
  45484. });
  45485. }
  45486. };
  45487. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  45488. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  45489. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  45490. return;
  45491. }
  45492. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  45493. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  45494. return;
  45495. }
  45496. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  45497. var loadingToken = {};
  45498. scene._addPendingData(loadingToken);
  45499. var manifestChecked = function (success) {
  45500. scene.database = database;
  45501. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  45502. var plugin = registeredPlugin.plugin;
  45503. var useArrayBuffer = registeredPlugin.isBinary;
  45504. var importMeshFromData = function (data) {
  45505. var meshes = [];
  45506. var particleSystems = [];
  45507. var skeletons = [];
  45508. if (scene.isDisposed) {
  45509. if (onerror) {
  45510. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  45511. }
  45512. return;
  45513. }
  45514. try {
  45515. if (plugin.importMesh) {
  45516. var syncedPlugin = plugin;
  45517. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  45518. if (onerror) {
  45519. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  45520. }
  45521. scene._removePendingData(loadingToken);
  45522. return;
  45523. }
  45524. if (onsuccess) {
  45525. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  45526. onsuccess(meshes, particleSystems, skeletons);
  45527. scene._removePendingData(loadingToken);
  45528. }
  45529. }
  45530. else {
  45531. var asyncedPlugin = plugin;
  45532. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  45533. if (onsuccess) {
  45534. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  45535. onsuccess(meshes, particleSystems, skeletons);
  45536. scene._removePendingData(loadingToken);
  45537. }
  45538. }, function () {
  45539. if (onerror) {
  45540. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  45541. }
  45542. scene._removePendingData(loadingToken);
  45543. });
  45544. }
  45545. }
  45546. catch (e) {
  45547. if (onerror) {
  45548. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  45549. }
  45550. scene._removePendingData(loadingToken);
  45551. }
  45552. };
  45553. if (directLoad) {
  45554. importMeshFromData(directLoad);
  45555. return;
  45556. }
  45557. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  45558. importMeshFromData(data);
  45559. }, progressCallBack, database, useArrayBuffer, function () {
  45560. if (onerror) {
  45561. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  45562. }
  45563. });
  45564. };
  45565. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  45566. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  45567. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  45568. }
  45569. else {
  45570. // If the scene is a data stream or offline support is not enabled, it's a direct load
  45571. manifestChecked(true);
  45572. }
  45573. };
  45574. /**
  45575. * Load a scene
  45576. * @param rootUrl a string that defines the root url for scene and resources
  45577. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  45578. * @param engine is the instance of BABYLON.Engine to use to create the scene
  45579. */
  45580. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  45581. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  45582. };
  45583. /**
  45584. * Append a scene
  45585. * @param rootUrl a string that defines the root url for scene and resources
  45586. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  45587. * @param scene is the instance of BABYLON.Scene to append to
  45588. */
  45589. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  45590. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  45591. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  45592. return;
  45593. }
  45594. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  45595. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  45596. var plugin = registeredPlugin.plugin;
  45597. var useArrayBuffer = registeredPlugin.isBinary;
  45598. var database;
  45599. var loadingToken = {};
  45600. scene._addPendingData(loadingToken);
  45601. if (SceneLoader.ShowLoadingScreen) {
  45602. scene.getEngine().displayLoadingUI();
  45603. }
  45604. var loadSceneFromData = function (data) {
  45605. scene.database = database;
  45606. if (plugin.load) {
  45607. var syncedPlugin = plugin;
  45608. if (!syncedPlugin.load(scene, data, rootUrl)) {
  45609. if (onerror) {
  45610. onerror(scene);
  45611. }
  45612. scene._removePendingData(loadingToken);
  45613. scene.getEngine().hideLoadingUI();
  45614. return;
  45615. }
  45616. if (onsuccess) {
  45617. onsuccess(scene);
  45618. }
  45619. scene._removePendingData(loadingToken);
  45620. }
  45621. else {
  45622. var asyncedPlugin = plugin;
  45623. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  45624. if (onsuccess) {
  45625. onsuccess(scene);
  45626. }
  45627. scene._removePendingData(loadingToken);
  45628. }, function () {
  45629. if (onerror) {
  45630. onerror(scene);
  45631. }
  45632. scene._removePendingData(loadingToken);
  45633. scene.getEngine().hideLoadingUI();
  45634. });
  45635. }
  45636. if (SceneLoader.ShowLoadingScreen) {
  45637. scene.executeWhenReady(function () {
  45638. scene.getEngine().hideLoadingUI();
  45639. });
  45640. }
  45641. };
  45642. var manifestChecked = function (success) {
  45643. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  45644. };
  45645. if (directLoad) {
  45646. loadSceneFromData(directLoad);
  45647. return;
  45648. }
  45649. if (rootUrl.indexOf("file:") === -1) {
  45650. if (scene.getEngine().enableOfflineSupport) {
  45651. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  45652. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  45653. }
  45654. else {
  45655. manifestChecked(true);
  45656. }
  45657. }
  45658. else {
  45659. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  45660. }
  45661. };
  45662. return SceneLoader;
  45663. }());
  45664. // Flags
  45665. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  45666. SceneLoader._ShowLoadingScreen = true;
  45667. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  45668. // Members
  45669. SceneLoader._registeredPlugins = {};
  45670. BABYLON.SceneLoader = SceneLoader;
  45671. ;
  45672. })(BABYLON || (BABYLON = {}));
  45673. //# sourceMappingURL=babylon.sceneLoader.js.map
  45674. var BABYLON;
  45675. (function (BABYLON) {
  45676. var Internals;
  45677. (function (Internals) {
  45678. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  45679. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  45680. var parsedMaterial = parsedData.materials[index];
  45681. if (parsedMaterial.id === id) {
  45682. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  45683. }
  45684. }
  45685. return null;
  45686. };
  45687. var isDescendantOf = function (mesh, names, hierarchyIds) {
  45688. names = (names instanceof Array) ? names : [names];
  45689. for (var i in names) {
  45690. if (mesh.name === names[i]) {
  45691. hierarchyIds.push(mesh.id);
  45692. return true;
  45693. }
  45694. }
  45695. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  45696. hierarchyIds.push(mesh.id);
  45697. return true;
  45698. }
  45699. return false;
  45700. };
  45701. var logOperation = function (operation, producer) {
  45702. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  45703. };
  45704. BABYLON.SceneLoader.RegisterPlugin({
  45705. extensions: ".babylon",
  45706. canDirectLoad: function (data) {
  45707. if (data.indexOf("babylon") !== -1) {
  45708. return true;
  45709. }
  45710. return false;
  45711. },
  45712. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  45713. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  45714. // when SceneLoader.debugLogging = true (default), or exception encountered.
  45715. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  45716. // and avoid problems with multiple concurrent .babylon loads.
  45717. var log = "importMesh has failed JSON parse";
  45718. try {
  45719. var parsedData = JSON.parse(data);
  45720. log = "";
  45721. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  45722. var loadedSkeletonsIds = [];
  45723. var loadedMaterialsIds = [];
  45724. var hierarchyIds = [];
  45725. var index;
  45726. var cache;
  45727. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  45728. var parsedMesh = parsedData.meshes[index];
  45729. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  45730. if (meshesNames instanceof Array) {
  45731. // Remove found mesh name from list.
  45732. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  45733. }
  45734. //Geometry?
  45735. if (parsedMesh.geometryId) {
  45736. //does the file contain geometries?
  45737. if (parsedData.geometries) {
  45738. //find the correct geometry and add it to the scene
  45739. var found = false;
  45740. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  45741. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  45742. return;
  45743. }
  45744. else {
  45745. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  45746. if (parsedGeometryData.id === parsedMesh.geometryId) {
  45747. switch (geometryType) {
  45748. case "boxes":
  45749. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  45750. break;
  45751. case "spheres":
  45752. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  45753. break;
  45754. case "cylinders":
  45755. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  45756. break;
  45757. case "toruses":
  45758. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  45759. break;
  45760. case "grounds":
  45761. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  45762. break;
  45763. case "planes":
  45764. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  45765. break;
  45766. case "torusKnots":
  45767. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  45768. break;
  45769. case "vertexData":
  45770. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  45771. break;
  45772. }
  45773. found = true;
  45774. }
  45775. });
  45776. }
  45777. });
  45778. if (!found) {
  45779. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  45780. }
  45781. }
  45782. }
  45783. // Material ?
  45784. if (parsedMesh.materialId) {
  45785. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  45786. if (!materialFound && parsedData.multiMaterials) {
  45787. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  45788. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  45789. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  45790. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  45791. var subMatId = parsedMultiMaterial.materials[matIndex];
  45792. loadedMaterialsIds.push(subMatId);
  45793. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  45794. log += "\n\tMaterial " + mat.toString(fullDetails);
  45795. }
  45796. loadedMaterialsIds.push(parsedMultiMaterial.id);
  45797. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45798. materialFound = true;
  45799. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  45800. break;
  45801. }
  45802. }
  45803. }
  45804. if (!materialFound) {
  45805. loadedMaterialsIds.push(parsedMesh.materialId);
  45806. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  45807. if (!mat) {
  45808. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  45809. }
  45810. else {
  45811. log += "\n\tMaterial " + mat.toString(fullDetails);
  45812. }
  45813. }
  45814. }
  45815. // Skeleton ?
  45816. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  45817. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  45818. if (!skeletonAlreadyLoaded) {
  45819. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  45820. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  45821. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  45822. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45823. skeletons.push(skeleton);
  45824. loadedSkeletonsIds.push(parsedSkeleton.id);
  45825. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  45826. }
  45827. }
  45828. }
  45829. }
  45830. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  45831. meshes.push(mesh);
  45832. log += "\n\tMesh " + mesh.toString(fullDetails);
  45833. }
  45834. }
  45835. // Connecting parents
  45836. var currentMesh;
  45837. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45838. currentMesh = scene.meshes[index];
  45839. if (currentMesh._waitingParentId) {
  45840. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  45841. currentMesh._waitingParentId = undefined;
  45842. }
  45843. }
  45844. // freeze and compute world matrix application
  45845. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45846. currentMesh = scene.meshes[index];
  45847. if (currentMesh._waitingFreezeWorldMatrix) {
  45848. currentMesh.freezeWorldMatrix();
  45849. currentMesh._waitingFreezeWorldMatrix = undefined;
  45850. }
  45851. else {
  45852. currentMesh.computeWorldMatrix(true);
  45853. }
  45854. }
  45855. // Particles
  45856. if (parsedData.particleSystems) {
  45857. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  45858. var parsedParticleSystem = parsedData.particleSystems[index];
  45859. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  45860. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  45861. }
  45862. }
  45863. }
  45864. return true;
  45865. }
  45866. catch (err) {
  45867. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  45868. log = null;
  45869. throw err;
  45870. }
  45871. finally {
  45872. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  45873. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  45874. }
  45875. }
  45876. },
  45877. load: function (scene, data, rootUrl) {
  45878. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  45879. // when SceneLoader.debugLogging = true (default), or exception encountered.
  45880. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  45881. // and avoid problems with multiple concurrent .babylon loads.
  45882. var log = "importScene has failed JSON parse";
  45883. try {
  45884. var parsedData = JSON.parse(data);
  45885. log = "";
  45886. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  45887. // Scene
  45888. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  45889. scene.autoClear = parsedData.autoClear;
  45890. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  45891. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  45892. if (parsedData.gravity) {
  45893. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  45894. }
  45895. // Fog
  45896. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  45897. scene.fogMode = parsedData.fogMode;
  45898. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  45899. scene.fogStart = parsedData.fogStart;
  45900. scene.fogEnd = parsedData.fogEnd;
  45901. scene.fogDensity = parsedData.fogDensity;
  45902. log += "\tFog mode for scene: ";
  45903. switch (scene.fogMode) {
  45904. // getters not compiling, so using hardcoded
  45905. case 1:
  45906. log += "exp\n";
  45907. break;
  45908. case 2:
  45909. log += "exp2\n";
  45910. break;
  45911. case 3:
  45912. log += "linear\n";
  45913. break;
  45914. }
  45915. }
  45916. //Physics
  45917. if (parsedData.physicsEnabled) {
  45918. var physicsPlugin;
  45919. if (parsedData.physicsEngine === "cannon") {
  45920. physicsPlugin = new BABYLON.CannonJSPlugin();
  45921. }
  45922. else if (parsedData.physicsEngine === "oimo") {
  45923. physicsPlugin = new BABYLON.OimoJSPlugin();
  45924. }
  45925. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  45926. //else - default engine, which is currently oimo
  45927. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  45928. scene.enablePhysics(physicsGravity, physicsPlugin);
  45929. }
  45930. // Metadata
  45931. if (parsedData.metadata !== undefined) {
  45932. scene.metadata = parsedData.metadata;
  45933. }
  45934. //collisions, if defined. otherwise, default is true
  45935. if (parsedData.collisionsEnabled != undefined) {
  45936. scene.collisionsEnabled = parsedData.collisionsEnabled;
  45937. }
  45938. scene.workerCollisions = !!parsedData.workerCollisions;
  45939. var index;
  45940. var cache;
  45941. // Lights
  45942. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  45943. var parsedLight = parsedData.lights[index];
  45944. var light = BABYLON.Light.Parse(parsedLight, scene);
  45945. log += (index === 0 ? "\n\tLights:" : "");
  45946. log += "\n\t\t" + light.toString(fullDetails);
  45947. }
  45948. // Animations
  45949. if (parsedData.animations) {
  45950. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  45951. var parsedAnimation = parsedData.animations[index];
  45952. var animation = BABYLON.Animation.Parse(parsedAnimation);
  45953. scene.animations.push(animation);
  45954. log += (index === 0 ? "\n\tAnimations:" : "");
  45955. log += "\n\t\t" + animation.toString(fullDetails);
  45956. }
  45957. }
  45958. if (parsedData.autoAnimate) {
  45959. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  45960. }
  45961. // Materials
  45962. if (parsedData.materials) {
  45963. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  45964. var parsedMaterial = parsedData.materials[index];
  45965. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  45966. log += (index === 0 ? "\n\tMaterials:" : "");
  45967. log += "\n\t\t" + mat.toString(fullDetails);
  45968. }
  45969. }
  45970. if (parsedData.multiMaterials) {
  45971. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  45972. var parsedMultiMaterial = parsedData.multiMaterials[index];
  45973. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45974. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  45975. log += "\n\t\t" + mmat.toString(fullDetails);
  45976. }
  45977. }
  45978. // Morph targets
  45979. if (parsedData.morphTargetManagers) {
  45980. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  45981. var managerData = _a[_i];
  45982. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  45983. }
  45984. }
  45985. // Skeletons
  45986. if (parsedData.skeletons) {
  45987. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  45988. var parsedSkeleton = parsedData.skeletons[index];
  45989. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45990. log += (index === 0 ? "\n\tSkeletons:" : "");
  45991. log += "\n\t\t" + skeleton.toString(fullDetails);
  45992. }
  45993. }
  45994. // Geometries
  45995. var geometries = parsedData.geometries;
  45996. if (geometries) {
  45997. // Boxes
  45998. var boxes = geometries.boxes;
  45999. if (boxes) {
  46000. for (index = 0, cache = boxes.length; index < cache; index++) {
  46001. var parsedBox = boxes[index];
  46002. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  46003. }
  46004. }
  46005. // Spheres
  46006. var spheres = geometries.spheres;
  46007. if (spheres) {
  46008. for (index = 0, cache = spheres.length; index < cache; index++) {
  46009. var parsedSphere = spheres[index];
  46010. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  46011. }
  46012. }
  46013. // Cylinders
  46014. var cylinders = geometries.cylinders;
  46015. if (cylinders) {
  46016. for (index = 0, cache = cylinders.length; index < cache; index++) {
  46017. var parsedCylinder = cylinders[index];
  46018. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  46019. }
  46020. }
  46021. // Toruses
  46022. var toruses = geometries.toruses;
  46023. if (toruses) {
  46024. for (index = 0, cache = toruses.length; index < cache; index++) {
  46025. var parsedTorus = toruses[index];
  46026. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  46027. }
  46028. }
  46029. // Grounds
  46030. var grounds = geometries.grounds;
  46031. if (grounds) {
  46032. for (index = 0, cache = grounds.length; index < cache; index++) {
  46033. var parsedGround = grounds[index];
  46034. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  46035. }
  46036. }
  46037. // Planes
  46038. var planes = geometries.planes;
  46039. if (planes) {
  46040. for (index = 0, cache = planes.length; index < cache; index++) {
  46041. var parsedPlane = planes[index];
  46042. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  46043. }
  46044. }
  46045. // TorusKnots
  46046. var torusKnots = geometries.torusKnots;
  46047. if (torusKnots) {
  46048. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  46049. var parsedTorusKnot = torusKnots[index];
  46050. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  46051. }
  46052. }
  46053. // VertexData
  46054. var vertexData = geometries.vertexData;
  46055. if (vertexData) {
  46056. for (index = 0, cache = vertexData.length; index < cache; index++) {
  46057. var parsedVertexData = vertexData[index];
  46058. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  46059. }
  46060. }
  46061. }
  46062. // Meshes
  46063. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  46064. var parsedMesh = parsedData.meshes[index];
  46065. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  46066. log += (index === 0 ? "\n\tMeshes:" : "");
  46067. log += "\n\t\t" + mesh.toString(fullDetails);
  46068. }
  46069. // Cameras
  46070. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  46071. var parsedCamera = parsedData.cameras[index];
  46072. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  46073. log += (index === 0 ? "\n\tCameras:" : "");
  46074. log += "\n\t\t" + camera.toString(fullDetails);
  46075. }
  46076. if (parsedData.activeCameraID) {
  46077. scene.setActiveCameraByID(parsedData.activeCameraID);
  46078. }
  46079. // Browsing all the graph to connect the dots
  46080. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  46081. var camera = scene.cameras[index];
  46082. if (camera._waitingParentId) {
  46083. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  46084. camera._waitingParentId = undefined;
  46085. }
  46086. }
  46087. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  46088. var light = scene.lights[index];
  46089. if (light._waitingParentId) {
  46090. light.parent = scene.getLastEntryByID(light._waitingParentId);
  46091. light._waitingParentId = undefined;
  46092. }
  46093. }
  46094. // Sounds
  46095. var loadedSounds = [];
  46096. var loadedSound;
  46097. if (BABYLON.AudioEngine && parsedData.sounds) {
  46098. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  46099. var parsedSound = parsedData.sounds[index];
  46100. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46101. if (!parsedSound.url)
  46102. parsedSound.url = parsedSound.name;
  46103. if (!loadedSounds[parsedSound.url]) {
  46104. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  46105. loadedSounds[parsedSound.url] = loadedSound;
  46106. }
  46107. else {
  46108. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  46109. }
  46110. }
  46111. else {
  46112. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  46113. }
  46114. }
  46115. }
  46116. loadedSounds = [];
  46117. // Connect parents & children and parse actions
  46118. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  46119. var mesh = scene.meshes[index];
  46120. if (mesh._waitingParentId) {
  46121. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  46122. mesh._waitingParentId = undefined;
  46123. }
  46124. if (mesh._waitingActions) {
  46125. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  46126. mesh._waitingActions = undefined;
  46127. }
  46128. }
  46129. // freeze world matrix application
  46130. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  46131. var currentMesh = scene.meshes[index];
  46132. if (currentMesh._waitingFreezeWorldMatrix) {
  46133. currentMesh.freezeWorldMatrix();
  46134. currentMesh._waitingFreezeWorldMatrix = undefined;
  46135. }
  46136. else {
  46137. currentMesh.computeWorldMatrix(true);
  46138. }
  46139. }
  46140. // Particles Systems
  46141. if (parsedData.particleSystems) {
  46142. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  46143. var parsedParticleSystem = parsedData.particleSystems[index];
  46144. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  46145. }
  46146. }
  46147. // Lens flares
  46148. if (parsedData.lensFlareSystems) {
  46149. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  46150. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  46151. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  46152. }
  46153. }
  46154. // Shadows
  46155. if (parsedData.shadowGenerators) {
  46156. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  46157. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  46158. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  46159. }
  46160. }
  46161. // Lights exclusions / inclusions
  46162. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  46163. var light = scene.lights[index];
  46164. // Excluded check
  46165. if (light._excludedMeshesIds.length > 0) {
  46166. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  46167. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  46168. if (excludedMesh) {
  46169. light.excludedMeshes.push(excludedMesh);
  46170. }
  46171. }
  46172. light._excludedMeshesIds = [];
  46173. }
  46174. // Included check
  46175. if (light._includedOnlyMeshesIds.length > 0) {
  46176. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  46177. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  46178. if (includedOnlyMesh) {
  46179. light.includedOnlyMeshes.push(includedOnlyMesh);
  46180. }
  46181. }
  46182. light._includedOnlyMeshesIds = [];
  46183. }
  46184. }
  46185. // Actions (scene)
  46186. if (parsedData.actions) {
  46187. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  46188. }
  46189. // Finish
  46190. return true;
  46191. }
  46192. catch (err) {
  46193. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  46194. log = null;
  46195. throw err;
  46196. }
  46197. finally {
  46198. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  46199. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  46200. }
  46201. }
  46202. }
  46203. });
  46204. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46205. })(BABYLON || (BABYLON = {}));
  46206. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  46207. var BABYLON;
  46208. (function (BABYLON) {
  46209. var FilesInput = (function () {
  46210. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  46211. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  46212. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  46213. this._engine = p_engine;
  46214. this._canvas = p_canvas;
  46215. this._currentScene = p_scene;
  46216. this._sceneLoadedCallback = p_sceneLoadedCallback;
  46217. this._progressCallback = p_progressCallback;
  46218. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  46219. this._textureLoadingCallback = p_textureLoadingCallback;
  46220. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  46221. }
  46222. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  46223. var _this = this;
  46224. if (p_elementToMonitor) {
  46225. this._elementToMonitor = p_elementToMonitor;
  46226. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  46227. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  46228. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  46229. }
  46230. };
  46231. FilesInput.prototype.renderFunction = function () {
  46232. if (this._additionnalRenderLoopLogicCallback) {
  46233. this._additionnalRenderLoopLogicCallback();
  46234. }
  46235. if (this._currentScene) {
  46236. if (this._textureLoadingCallback) {
  46237. var remaining = this._currentScene.getWaitingItemsCount();
  46238. if (remaining > 0) {
  46239. this._textureLoadingCallback(remaining);
  46240. }
  46241. }
  46242. this._currentScene.render();
  46243. }
  46244. };
  46245. FilesInput.prototype.drag = function (e) {
  46246. e.stopPropagation();
  46247. e.preventDefault();
  46248. };
  46249. FilesInput.prototype.drop = function (eventDrop) {
  46250. eventDrop.stopPropagation();
  46251. eventDrop.preventDefault();
  46252. this.loadFiles(eventDrop);
  46253. };
  46254. FilesInput.prototype.loadFiles = function (event) {
  46255. if (this._startingProcessingFilesCallback)
  46256. this._startingProcessingFilesCallback();
  46257. // Handling data transfer via drag'n'drop
  46258. if (event && event.dataTransfer && event.dataTransfer.files) {
  46259. this._filesToLoad = event.dataTransfer.files;
  46260. }
  46261. // Handling files from input files
  46262. if (event && event.target && event.target.files) {
  46263. this._filesToLoad = event.target.files;
  46264. }
  46265. if (this._filesToLoad && this._filesToLoad.length > 0) {
  46266. for (var i = 0; i < this._filesToLoad.length; i++) {
  46267. var name_1 = this._filesToLoad[i].name.toLowerCase();
  46268. var extension = name_1.split('.').pop();
  46269. var type = this._filesToLoad[i].type;
  46270. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  46271. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  46272. this._sceneFileToLoad = this._filesToLoad[i];
  46273. }
  46274. else {
  46275. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  46276. }
  46277. }
  46278. this.reload();
  46279. }
  46280. };
  46281. FilesInput.prototype.reload = function () {
  46282. var _this = this;
  46283. var that = this;
  46284. // If a ".babylon" file has been provided
  46285. if (this._sceneFileToLoad) {
  46286. if (this._currentScene) {
  46287. if (BABYLON.Tools.errorsCount > 0) {
  46288. BABYLON.Tools.ClearLogCache();
  46289. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  46290. }
  46291. this._engine.stopRenderLoop();
  46292. this._currentScene.dispose();
  46293. }
  46294. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  46295. that._currentScene = newScene;
  46296. // Wait for textures and shaders to be ready
  46297. that._currentScene.executeWhenReady(function () {
  46298. if (that._sceneLoadedCallback) {
  46299. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  46300. }
  46301. that._engine.runRenderLoop(function () { that.renderFunction(); });
  46302. });
  46303. }, function (progress) {
  46304. if (_this._progressCallback) {
  46305. _this._progressCallback(progress);
  46306. }
  46307. });
  46308. }
  46309. else {
  46310. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  46311. }
  46312. };
  46313. return FilesInput;
  46314. }());
  46315. FilesInput.FilesToLoad = new Array();
  46316. BABYLON.FilesInput = FilesInput;
  46317. })(BABYLON || (BABYLON = {}));
  46318. //# sourceMappingURL=babylon.filesInput.js.map
  46319. var BABYLON;
  46320. (function (BABYLON) {
  46321. /**
  46322. * This class implement a typical dictionary using a string as key and the generic type T as value.
  46323. * The underlying implementation relies on an associative array to ensure the best performances.
  46324. * The value can be anything including 'null' but except 'undefined'
  46325. */
  46326. var StringDictionary = (function () {
  46327. function StringDictionary() {
  46328. this._count = 0;
  46329. this._data = {};
  46330. }
  46331. /**
  46332. * This will clear this dictionary and copy the content from the 'source' one.
  46333. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  46334. * @param source the dictionary to take the content from and copy to this dictionary
  46335. */
  46336. StringDictionary.prototype.copyFrom = function (source) {
  46337. var _this = this;
  46338. this.clear();
  46339. source.forEach(function (t, v) { return _this.add(t, v); });
  46340. };
  46341. /**
  46342. * Get a value based from its key
  46343. * @param key the given key to get the matching value from
  46344. * @return the value if found, otherwise undefined is returned
  46345. */
  46346. StringDictionary.prototype.get = function (key) {
  46347. var val = this._data[key];
  46348. if (val !== undefined) {
  46349. return val;
  46350. }
  46351. return undefined;
  46352. };
  46353. /**
  46354. * Get a value from its key or add it if it doesn't exist.
  46355. * This method will ensure you that a given key/data will be present in the dictionary.
  46356. * @param key the given key to get the matching value from
  46357. * @param factory the factory that will create the value if the key is not present in the dictionary.
  46358. * The factory will only be invoked if there's no data for the given key.
  46359. * @return the value corresponding to the key.
  46360. */
  46361. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  46362. var val = this.get(key);
  46363. if (val !== undefined) {
  46364. return val;
  46365. }
  46366. val = factory(key);
  46367. if (val) {
  46368. this.add(key, val);
  46369. }
  46370. return val;
  46371. };
  46372. /**
  46373. * Get a value from its key if present in the dictionary otherwise add it
  46374. * @param key the key to get the value from
  46375. * @param val if there's no such key/value pair in the dictionary add it with this value
  46376. * @return the value corresponding to the key
  46377. */
  46378. StringDictionary.prototype.getOrAdd = function (key, val) {
  46379. var curVal = this.get(key);
  46380. if (curVal !== undefined) {
  46381. return curVal;
  46382. }
  46383. this.add(key, val);
  46384. return val;
  46385. };
  46386. /**
  46387. * Check if there's a given key in the dictionary
  46388. * @param key the key to check for
  46389. * @return true if the key is present, false otherwise
  46390. */
  46391. StringDictionary.prototype.contains = function (key) {
  46392. return this._data[key] !== undefined;
  46393. };
  46394. /**
  46395. * Add a new key and its corresponding value
  46396. * @param key the key to add
  46397. * @param value the value corresponding to the key
  46398. * @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
  46399. */
  46400. StringDictionary.prototype.add = function (key, value) {
  46401. if (this._data[key] !== undefined) {
  46402. return false;
  46403. }
  46404. this._data[key] = value;
  46405. ++this._count;
  46406. return true;
  46407. };
  46408. StringDictionary.prototype.set = function (key, value) {
  46409. if (this._data[key] === undefined) {
  46410. return false;
  46411. }
  46412. this._data[key] = value;
  46413. return true;
  46414. };
  46415. /**
  46416. * Get the element of the given key and remove it from the dictionary
  46417. * @param key
  46418. */
  46419. StringDictionary.prototype.getAndRemove = function (key) {
  46420. var val = this.get(key);
  46421. if (val !== undefined) {
  46422. delete this._data[key];
  46423. --this._count;
  46424. return val;
  46425. }
  46426. return null;
  46427. };
  46428. /**
  46429. * Remove a key/value from the dictionary.
  46430. * @param key the key to remove
  46431. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  46432. */
  46433. StringDictionary.prototype.remove = function (key) {
  46434. if (this.contains(key)) {
  46435. delete this._data[key];
  46436. --this._count;
  46437. return true;
  46438. }
  46439. return false;
  46440. };
  46441. /**
  46442. * Clear the whole content of the dictionary
  46443. */
  46444. StringDictionary.prototype.clear = function () {
  46445. this._data = {};
  46446. this._count = 0;
  46447. };
  46448. Object.defineProperty(StringDictionary.prototype, "count", {
  46449. get: function () {
  46450. return this._count;
  46451. },
  46452. enumerable: true,
  46453. configurable: true
  46454. });
  46455. /**
  46456. * Execute a callback on each key/val of the dictionary.
  46457. * Note that you can remove any element in this dictionary in the callback implementation
  46458. * @param callback the callback to execute on a given key/value pair
  46459. */
  46460. StringDictionary.prototype.forEach = function (callback) {
  46461. for (var cur in this._data) {
  46462. var val = this._data[cur];
  46463. callback(cur, val);
  46464. }
  46465. };
  46466. /**
  46467. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  46468. * If the callback returns null or undefined the method will iterate to the next key/value pair
  46469. * Note that you can remove any element in this dictionary in the callback implementation
  46470. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  46471. */
  46472. StringDictionary.prototype.first = function (callback) {
  46473. for (var cur in this._data) {
  46474. var val = this._data[cur];
  46475. var res = callback(cur, val);
  46476. if (res) {
  46477. return res;
  46478. }
  46479. }
  46480. return null;
  46481. };
  46482. return StringDictionary;
  46483. }());
  46484. BABYLON.StringDictionary = StringDictionary;
  46485. })(BABYLON || (BABYLON = {}));
  46486. //# sourceMappingURL=babylon.stringDictionary.js.map
  46487. var BABYLON;
  46488. (function (BABYLON) {
  46489. var Tags = (function () {
  46490. function Tags() {
  46491. }
  46492. Tags.EnableFor = function (obj) {
  46493. obj._tags = obj._tags || {};
  46494. obj.hasTags = function () {
  46495. return Tags.HasTags(obj);
  46496. };
  46497. obj.addTags = function (tagsString) {
  46498. return Tags.AddTagsTo(obj, tagsString);
  46499. };
  46500. obj.removeTags = function (tagsString) {
  46501. return Tags.RemoveTagsFrom(obj, tagsString);
  46502. };
  46503. obj.matchesTagsQuery = function (tagsQuery) {
  46504. return Tags.MatchesQuery(obj, tagsQuery);
  46505. };
  46506. };
  46507. Tags.DisableFor = function (obj) {
  46508. delete obj._tags;
  46509. delete obj.hasTags;
  46510. delete obj.addTags;
  46511. delete obj.removeTags;
  46512. delete obj.matchesTagsQuery;
  46513. };
  46514. Tags.HasTags = function (obj) {
  46515. if (!obj._tags) {
  46516. return false;
  46517. }
  46518. return !BABYLON.Tools.IsEmpty(obj._tags);
  46519. };
  46520. Tags.GetTags = function (obj, asString) {
  46521. if (asString === void 0) { asString = true; }
  46522. if (!obj._tags) {
  46523. return null;
  46524. }
  46525. if (asString) {
  46526. var tagsArray = [];
  46527. for (var tag in obj._tags) {
  46528. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  46529. tagsArray.push(tag);
  46530. }
  46531. }
  46532. return tagsArray.join(" ");
  46533. }
  46534. else {
  46535. return obj._tags;
  46536. }
  46537. };
  46538. // the tags 'true' and 'false' are reserved and cannot be used as tags
  46539. // a tag cannot start with '||', '&&', and '!'
  46540. // it cannot contain whitespaces
  46541. Tags.AddTagsTo = function (obj, tagsString) {
  46542. if (!tagsString) {
  46543. return;
  46544. }
  46545. if (typeof tagsString !== "string") {
  46546. return;
  46547. }
  46548. var tags = tagsString.split(" ");
  46549. tags.forEach(function (tag, index, array) {
  46550. Tags._AddTagTo(obj, tag);
  46551. });
  46552. };
  46553. Tags._AddTagTo = function (obj, tag) {
  46554. tag = tag.trim();
  46555. if (tag === "" || tag === "true" || tag === "false") {
  46556. return;
  46557. }
  46558. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  46559. return;
  46560. }
  46561. Tags.EnableFor(obj);
  46562. obj._tags[tag] = true;
  46563. };
  46564. Tags.RemoveTagsFrom = function (obj, tagsString) {
  46565. if (!Tags.HasTags(obj)) {
  46566. return;
  46567. }
  46568. var tags = tagsString.split(" ");
  46569. for (var t in tags) {
  46570. Tags._RemoveTagFrom(obj, tags[t]);
  46571. }
  46572. };
  46573. Tags._RemoveTagFrom = function (obj, tag) {
  46574. delete obj._tags[tag];
  46575. };
  46576. Tags.MatchesQuery = function (obj, tagsQuery) {
  46577. if (tagsQuery === undefined) {
  46578. return true;
  46579. }
  46580. if (tagsQuery === "") {
  46581. return Tags.HasTags(obj);
  46582. }
  46583. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  46584. };
  46585. return Tags;
  46586. }());
  46587. BABYLON.Tags = Tags;
  46588. })(BABYLON || (BABYLON = {}));
  46589. //# sourceMappingURL=babylon.tags.js.map
  46590. var BABYLON;
  46591. (function (BABYLON) {
  46592. var Internals;
  46593. (function (Internals) {
  46594. var AndOrNotEvaluator = (function () {
  46595. function AndOrNotEvaluator() {
  46596. }
  46597. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  46598. if (!query.match(/\([^\(\)]*\)/g)) {
  46599. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  46600. }
  46601. else {
  46602. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  46603. // remove parenthesis
  46604. r = r.slice(1, r.length - 1);
  46605. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  46606. });
  46607. }
  46608. if (query === "true") {
  46609. return true;
  46610. }
  46611. if (query === "false") {
  46612. return false;
  46613. }
  46614. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  46615. };
  46616. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  46617. evaluateCallback = evaluateCallback || (function (r) {
  46618. return r === "true" ? true : false;
  46619. });
  46620. var result;
  46621. var or = parenthesisContent.split("||");
  46622. for (var i in or) {
  46623. if (or.hasOwnProperty(i)) {
  46624. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  46625. var and = ori.split("&&");
  46626. if (and.length > 1) {
  46627. for (var j = 0; j < and.length; ++j) {
  46628. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  46629. if (andj !== "true" && andj !== "false") {
  46630. if (andj[0] === "!") {
  46631. result = !evaluateCallback(andj.substring(1));
  46632. }
  46633. else {
  46634. result = evaluateCallback(andj);
  46635. }
  46636. }
  46637. else {
  46638. result = andj === "true" ? true : false;
  46639. }
  46640. if (!result) {
  46641. ori = "false";
  46642. break;
  46643. }
  46644. }
  46645. }
  46646. if (result || ori === "true") {
  46647. result = true;
  46648. break;
  46649. }
  46650. // result equals false (or undefined)
  46651. if (ori !== "true" && ori !== "false") {
  46652. if (ori[0] === "!") {
  46653. result = !evaluateCallback(ori.substring(1));
  46654. }
  46655. else {
  46656. result = evaluateCallback(ori);
  46657. }
  46658. }
  46659. else {
  46660. result = ori === "true" ? true : false;
  46661. }
  46662. }
  46663. }
  46664. // the whole parenthesis scope is replaced by 'true' or 'false'
  46665. return result ? "true" : "false";
  46666. };
  46667. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  46668. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  46669. // remove whitespaces
  46670. r = r.replace(/[\s]/g, function () { return ""; });
  46671. return r.length % 2 ? "!" : "";
  46672. });
  46673. booleanString = booleanString.trim();
  46674. if (booleanString === "!true") {
  46675. booleanString = "false";
  46676. }
  46677. else if (booleanString === "!false") {
  46678. booleanString = "true";
  46679. }
  46680. return booleanString;
  46681. };
  46682. return AndOrNotEvaluator;
  46683. }());
  46684. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  46685. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46686. })(BABYLON || (BABYLON = {}));
  46687. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  46688. var BABYLON;
  46689. (function (BABYLON) {
  46690. var Database = (function () {
  46691. function Database(urlToScene, callbackManifestChecked) {
  46692. // Handling various flavors of prefixed version of IndexedDB
  46693. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  46694. this.callbackManifestChecked = callbackManifestChecked;
  46695. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  46696. this.db = null;
  46697. this.enableSceneOffline = false;
  46698. this.enableTexturesOffline = false;
  46699. this.manifestVersionFound = 0;
  46700. this.mustUpdateRessources = false;
  46701. this.hasReachedQuota = false;
  46702. if (!Database.IDBStorageEnabled) {
  46703. this.callbackManifestChecked(true);
  46704. }
  46705. else {
  46706. this.checkManifestFile();
  46707. }
  46708. }
  46709. Database.prototype.checkManifestFile = function () {
  46710. var _this = this;
  46711. function noManifestFile() {
  46712. that.enableSceneOffline = false;
  46713. that.enableTexturesOffline = false;
  46714. that.callbackManifestChecked(false);
  46715. }
  46716. var that = this;
  46717. var timeStampUsed = false;
  46718. var manifestURL = this.currentSceneUrl + ".manifest";
  46719. var xhr = new XMLHttpRequest();
  46720. if (navigator.onLine) {
  46721. // Adding a timestamp to by-pass browsers' cache
  46722. timeStampUsed = true;
  46723. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  46724. }
  46725. xhr.open("GET", manifestURL, true);
  46726. xhr.addEventListener("load", function () {
  46727. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  46728. try {
  46729. var manifestFile = JSON.parse(xhr.response);
  46730. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  46731. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  46732. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  46733. _this.manifestVersionFound = manifestFile.version;
  46734. }
  46735. if (_this.callbackManifestChecked) {
  46736. _this.callbackManifestChecked(true);
  46737. }
  46738. }
  46739. catch (ex) {
  46740. noManifestFile();
  46741. }
  46742. }
  46743. else {
  46744. noManifestFile();
  46745. }
  46746. }, false);
  46747. xhr.addEventListener("error", function (event) {
  46748. if (timeStampUsed) {
  46749. timeStampUsed = false;
  46750. // Let's retry without the timeStamp
  46751. // It could fail when coupled with HTML5 Offline API
  46752. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  46753. xhr.open("GET", retryManifestURL, true);
  46754. xhr.send();
  46755. }
  46756. else {
  46757. noManifestFile();
  46758. }
  46759. }, false);
  46760. try {
  46761. xhr.send();
  46762. }
  46763. catch (ex) {
  46764. BABYLON.Tools.Error("Error on XHR send request.");
  46765. that.callbackManifestChecked(false);
  46766. }
  46767. };
  46768. Database.prototype.openAsync = function (successCallback, errorCallback) {
  46769. var _this = this;
  46770. function handleError() {
  46771. that.isSupported = false;
  46772. if (errorCallback)
  46773. errorCallback();
  46774. }
  46775. var that = this;
  46776. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  46777. // Your browser doesn't support IndexedDB
  46778. this.isSupported = false;
  46779. if (errorCallback)
  46780. errorCallback();
  46781. }
  46782. else {
  46783. // If the DB hasn't been opened or created yet
  46784. if (!this.db) {
  46785. this.hasReachedQuota = false;
  46786. this.isSupported = true;
  46787. var request = this.idbFactory.open("babylonjs", 1);
  46788. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  46789. request.onerror = function (event) {
  46790. handleError();
  46791. };
  46792. // executes when a version change transaction cannot complete due to other active transactions
  46793. request.onblocked = function (event) {
  46794. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  46795. handleError();
  46796. };
  46797. // DB has been opened successfully
  46798. request.onsuccess = function (event) {
  46799. _this.db = request.result;
  46800. successCallback();
  46801. };
  46802. // Initialization of the DB. Creating Scenes & Textures stores
  46803. request.onupgradeneeded = function (event) {
  46804. _this.db = (event.target).result;
  46805. try {
  46806. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  46807. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  46808. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  46809. }
  46810. catch (ex) {
  46811. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  46812. handleError();
  46813. }
  46814. };
  46815. }
  46816. else {
  46817. if (successCallback)
  46818. successCallback();
  46819. }
  46820. }
  46821. };
  46822. Database.prototype.loadImageFromDB = function (url, image) {
  46823. var _this = this;
  46824. var completeURL = Database.ReturnFullUrlLocation(url);
  46825. var saveAndLoadImage = function () {
  46826. if (!_this.hasReachedQuota && _this.db !== null) {
  46827. // the texture is not yet in the DB, let's try to save it
  46828. _this._saveImageIntoDBAsync(completeURL, image);
  46829. }
  46830. else {
  46831. image.src = url;
  46832. }
  46833. };
  46834. if (!this.mustUpdateRessources) {
  46835. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  46836. }
  46837. else {
  46838. saveAndLoadImage();
  46839. }
  46840. };
  46841. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  46842. if (this.isSupported && this.db !== null) {
  46843. var texture;
  46844. var transaction = this.db.transaction(["textures"]);
  46845. transaction.onabort = function (event) {
  46846. image.src = url;
  46847. };
  46848. transaction.oncomplete = function (event) {
  46849. var blobTextureURL;
  46850. if (texture) {
  46851. var URL = window.URL || window.webkitURL;
  46852. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  46853. image.onerror = function () {
  46854. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  46855. image.src = url;
  46856. };
  46857. image.src = blobTextureURL;
  46858. }
  46859. else {
  46860. notInDBCallback();
  46861. }
  46862. };
  46863. var getRequest = transaction.objectStore("textures").get(url);
  46864. getRequest.onsuccess = function (event) {
  46865. texture = (event.target).result;
  46866. };
  46867. getRequest.onerror = function (event) {
  46868. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  46869. image.src = url;
  46870. };
  46871. }
  46872. else {
  46873. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46874. image.src = url;
  46875. }
  46876. };
  46877. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  46878. var _this = this;
  46879. if (this.isSupported) {
  46880. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  46881. var generateBlobUrl = function () {
  46882. var blobTextureURL;
  46883. if (blob) {
  46884. var URL = window.URL || window.webkitURL;
  46885. try {
  46886. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  46887. }
  46888. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  46889. catch (ex) {
  46890. blobTextureURL = URL.createObjectURL(blob);
  46891. }
  46892. }
  46893. image.src = blobTextureURL;
  46894. };
  46895. if (Database.IsUASupportingBlobStorage) {
  46896. var xhr = new XMLHttpRequest(), blob;
  46897. xhr.open("GET", url, true);
  46898. xhr.responseType = "blob";
  46899. xhr.addEventListener("load", function () {
  46900. if (xhr.status === 200) {
  46901. // Blob as response (XHR2)
  46902. blob = xhr.response;
  46903. var transaction = _this.db.transaction(["textures"], "readwrite");
  46904. // the transaction could abort because of a QuotaExceededError error
  46905. transaction.onabort = function (event) {
  46906. try {
  46907. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  46908. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46909. _this.hasReachedQuota = true;
  46910. }
  46911. }
  46912. catch (ex) { }
  46913. generateBlobUrl();
  46914. };
  46915. transaction.oncomplete = function (event) {
  46916. generateBlobUrl();
  46917. };
  46918. var newTexture = { textureUrl: url, data: blob };
  46919. try {
  46920. // Put the blob into the dabase
  46921. var addRequest = transaction.objectStore("textures").put(newTexture);
  46922. addRequest.onsuccess = function (event) {
  46923. };
  46924. addRequest.onerror = function (event) {
  46925. generateBlobUrl();
  46926. };
  46927. }
  46928. catch (ex) {
  46929. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  46930. if (ex.code === 25) {
  46931. Database.IsUASupportingBlobStorage = false;
  46932. }
  46933. image.src = url;
  46934. }
  46935. }
  46936. else {
  46937. image.src = url;
  46938. }
  46939. }, false);
  46940. xhr.addEventListener("error", function (event) {
  46941. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  46942. image.src = url;
  46943. }, false);
  46944. xhr.send();
  46945. }
  46946. else {
  46947. image.src = url;
  46948. }
  46949. }
  46950. else {
  46951. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46952. image.src = url;
  46953. }
  46954. };
  46955. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  46956. var _this = this;
  46957. var updateVersion = function (event) {
  46958. // the version is not yet in the DB or we need to update it
  46959. _this._saveVersionIntoDBAsync(url, versionLoaded);
  46960. };
  46961. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  46962. };
  46963. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  46964. var _this = this;
  46965. if (this.isSupported) {
  46966. var version;
  46967. try {
  46968. var transaction = this.db.transaction(["versions"]);
  46969. transaction.oncomplete = function (event) {
  46970. if (version) {
  46971. // If the version in the JSON file is > than the version in DB
  46972. if (_this.manifestVersionFound > version.data) {
  46973. _this.mustUpdateRessources = true;
  46974. updateInDBCallback();
  46975. }
  46976. else {
  46977. callback(version.data);
  46978. }
  46979. }
  46980. else {
  46981. _this.mustUpdateRessources = true;
  46982. updateInDBCallback();
  46983. }
  46984. };
  46985. transaction.onabort = function (event) {
  46986. callback(-1);
  46987. };
  46988. var getRequest = transaction.objectStore("versions").get(url);
  46989. getRequest.onsuccess = function (event) {
  46990. version = (event.target).result;
  46991. };
  46992. getRequest.onerror = function (event) {
  46993. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  46994. callback(-1);
  46995. };
  46996. }
  46997. catch (ex) {
  46998. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  46999. callback(-1);
  47000. }
  47001. }
  47002. else {
  47003. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47004. callback(-1);
  47005. }
  47006. };
  47007. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  47008. var _this = this;
  47009. if (this.isSupported && !this.hasReachedQuota) {
  47010. try {
  47011. // Open a transaction to the database
  47012. var transaction = this.db.transaction(["versions"], "readwrite");
  47013. // the transaction could abort because of a QuotaExceededError error
  47014. transaction.onabort = function (event) {
  47015. try {
  47016. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  47017. _this.hasReachedQuota = true;
  47018. }
  47019. }
  47020. catch (ex) { }
  47021. callback(-1);
  47022. };
  47023. transaction.oncomplete = function (event) {
  47024. callback(_this.manifestVersionFound);
  47025. };
  47026. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  47027. // Put the scene into the database
  47028. var addRequest = transaction.objectStore("versions").put(newVersion);
  47029. addRequest.onsuccess = function (event) {
  47030. };
  47031. addRequest.onerror = function (event) {
  47032. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  47033. };
  47034. }
  47035. catch (ex) {
  47036. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  47037. callback(-1);
  47038. }
  47039. }
  47040. else {
  47041. callback(-1);
  47042. }
  47043. };
  47044. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  47045. var _this = this;
  47046. var completeUrl = Database.ReturnFullUrlLocation(url);
  47047. var saveAndLoadFile = function (event) {
  47048. // the scene is not yet in the DB, let's try to save it
  47049. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  47050. };
  47051. this._checkVersionFromDB(completeUrl, function (version) {
  47052. if (version !== -1) {
  47053. if (!_this.mustUpdateRessources) {
  47054. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  47055. }
  47056. else {
  47057. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  47058. }
  47059. }
  47060. else {
  47061. errorCallback();
  47062. }
  47063. });
  47064. };
  47065. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  47066. if (this.isSupported) {
  47067. var targetStore;
  47068. if (url.indexOf(".babylon") !== -1) {
  47069. targetStore = "scenes";
  47070. }
  47071. else {
  47072. targetStore = "textures";
  47073. }
  47074. var file;
  47075. var transaction = this.db.transaction([targetStore]);
  47076. transaction.oncomplete = function (event) {
  47077. if (file) {
  47078. callback(file.data);
  47079. }
  47080. else {
  47081. notInDBCallback();
  47082. }
  47083. };
  47084. transaction.onabort = function (event) {
  47085. notInDBCallback();
  47086. };
  47087. var getRequest = transaction.objectStore(targetStore).get(url);
  47088. getRequest.onsuccess = function (event) {
  47089. file = (event.target).result;
  47090. };
  47091. getRequest.onerror = function (event) {
  47092. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  47093. notInDBCallback();
  47094. };
  47095. }
  47096. else {
  47097. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47098. callback();
  47099. }
  47100. };
  47101. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  47102. var _this = this;
  47103. if (this.isSupported) {
  47104. var targetStore;
  47105. if (url.indexOf(".babylon") !== -1) {
  47106. targetStore = "scenes";
  47107. }
  47108. else {
  47109. targetStore = "textures";
  47110. }
  47111. // Create XHR
  47112. var xhr = new XMLHttpRequest(), fileData;
  47113. xhr.open("GET", url, true);
  47114. if (useArrayBuffer) {
  47115. xhr.responseType = "arraybuffer";
  47116. }
  47117. xhr.onprogress = progressCallback;
  47118. xhr.addEventListener("load", function () {
  47119. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  47120. // Blob as response (XHR2)
  47121. //fileData = xhr.responseText;
  47122. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  47123. if (!_this.hasReachedQuota) {
  47124. // Open a transaction to the database
  47125. var transaction = _this.db.transaction([targetStore], "readwrite");
  47126. // the transaction could abort because of a QuotaExceededError error
  47127. transaction.onabort = function (event) {
  47128. try {
  47129. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  47130. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  47131. _this.hasReachedQuota = true;
  47132. }
  47133. }
  47134. catch (ex) { }
  47135. callback(fileData);
  47136. };
  47137. transaction.oncomplete = function (event) {
  47138. callback(fileData);
  47139. };
  47140. var newFile;
  47141. if (targetStore === "scenes") {
  47142. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  47143. }
  47144. else {
  47145. newFile = { textureUrl: url, data: fileData };
  47146. }
  47147. try {
  47148. // Put the scene into the database
  47149. var addRequest = transaction.objectStore(targetStore).put(newFile);
  47150. addRequest.onsuccess = function (event) {
  47151. };
  47152. addRequest.onerror = function (event) {
  47153. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  47154. };
  47155. }
  47156. catch (ex) {
  47157. callback(fileData);
  47158. }
  47159. }
  47160. else {
  47161. callback(fileData);
  47162. }
  47163. }
  47164. else {
  47165. callback();
  47166. }
  47167. }, false);
  47168. xhr.addEventListener("error", function (event) {
  47169. BABYLON.Tools.Error("error on XHR request.");
  47170. callback();
  47171. }, false);
  47172. xhr.send();
  47173. }
  47174. else {
  47175. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47176. callback();
  47177. }
  47178. };
  47179. return Database;
  47180. }());
  47181. Database.IsUASupportingBlobStorage = true;
  47182. Database.IDBStorageEnabled = true;
  47183. Database.parseURL = function (url) {
  47184. var a = document.createElement('a');
  47185. a.href = url;
  47186. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  47187. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  47188. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  47189. return absLocation;
  47190. };
  47191. Database.ReturnFullUrlLocation = function (url) {
  47192. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  47193. return (Database.parseURL(window.location.href) + url);
  47194. }
  47195. else {
  47196. return url;
  47197. }
  47198. };
  47199. BABYLON.Database = Database;
  47200. })(BABYLON || (BABYLON = {}));
  47201. //# sourceMappingURL=babylon.database.js.map
  47202. var BABYLON;
  47203. (function (BABYLON) {
  47204. var FresnelParameters = (function () {
  47205. function FresnelParameters() {
  47206. this._isEnabled = true;
  47207. this.leftColor = BABYLON.Color3.White();
  47208. this.rightColor = BABYLON.Color3.Black();
  47209. this.bias = 0;
  47210. this.power = 1;
  47211. }
  47212. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  47213. get: function () {
  47214. return this._isEnabled;
  47215. },
  47216. set: function (value) {
  47217. if (this._isEnabled === value) {
  47218. return;
  47219. }
  47220. this._isEnabled = value;
  47221. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  47222. },
  47223. enumerable: true,
  47224. configurable: true
  47225. });
  47226. FresnelParameters.prototype.clone = function () {
  47227. var newFresnelParameters = new FresnelParameters();
  47228. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  47229. return newFresnelParameters;
  47230. };
  47231. FresnelParameters.prototype.serialize = function () {
  47232. var serializationObject = {};
  47233. serializationObject.isEnabled = this.isEnabled;
  47234. serializationObject.leftColor = this.leftColor;
  47235. serializationObject.rightColor = this.rightColor;
  47236. serializationObject.bias = this.bias;
  47237. serializationObject.power = this.power;
  47238. return serializationObject;
  47239. };
  47240. FresnelParameters.Parse = function (parsedFresnelParameters) {
  47241. var fresnelParameters = new FresnelParameters();
  47242. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  47243. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  47244. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  47245. fresnelParameters.bias = parsedFresnelParameters.bias;
  47246. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  47247. return fresnelParameters;
  47248. };
  47249. return FresnelParameters;
  47250. }());
  47251. BABYLON.FresnelParameters = FresnelParameters;
  47252. })(BABYLON || (BABYLON = {}));
  47253. //# sourceMappingURL=babylon.fresnelParameters.js.map
  47254. var BABYLON;
  47255. (function (BABYLON) {
  47256. var MultiMaterial = (function (_super) {
  47257. __extends(MultiMaterial, _super);
  47258. function MultiMaterial(name, scene) {
  47259. var _this = _super.call(this, name, scene, true) || this;
  47260. scene.multiMaterials.push(_this);
  47261. _this.subMaterials = new Array();
  47262. return _this;
  47263. }
  47264. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  47265. get: function () {
  47266. return this._subMaterials;
  47267. },
  47268. set: function (value) {
  47269. this._subMaterials = value;
  47270. this._hookArray(value);
  47271. },
  47272. enumerable: true,
  47273. configurable: true
  47274. });
  47275. MultiMaterial.prototype._hookArray = function (array) {
  47276. var _this = this;
  47277. var oldPush = array.push;
  47278. array.push = function () {
  47279. var items = [];
  47280. for (var _i = 0; _i < arguments.length; _i++) {
  47281. items[_i] = arguments[_i];
  47282. }
  47283. var result = oldPush.apply(array, items);
  47284. _this._markAllSubMeshesAsTexturesDirty();
  47285. return result;
  47286. };
  47287. var oldSplice = array.splice;
  47288. array.splice = function (index, deleteCount) {
  47289. var deleted = oldSplice.apply(array, [index, deleteCount]);
  47290. _this._markAllSubMeshesAsTexturesDirty();
  47291. return deleted;
  47292. };
  47293. };
  47294. // Properties
  47295. MultiMaterial.prototype.getSubMaterial = function (index) {
  47296. if (index < 0 || index >= this.subMaterials.length) {
  47297. return this.getScene().defaultMaterial;
  47298. }
  47299. return this.subMaterials[index];
  47300. };
  47301. MultiMaterial.prototype.getActiveTextures = function () {
  47302. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  47303. var _a;
  47304. };
  47305. // Methods
  47306. MultiMaterial.prototype.getClassName = function () {
  47307. return "MultiMaterial";
  47308. };
  47309. MultiMaterial.prototype.isReady = function (mesh) {
  47310. for (var index = 0; index < this.subMaterials.length; index++) {
  47311. var subMaterial = this.subMaterials[index];
  47312. if (subMaterial) {
  47313. if (!this.subMaterials[index].isReady(mesh)) {
  47314. return false;
  47315. }
  47316. }
  47317. }
  47318. return true;
  47319. };
  47320. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  47321. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  47322. for (var index = 0; index < this.subMaterials.length; index++) {
  47323. var subMaterial = null;
  47324. if (cloneChildren) {
  47325. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  47326. }
  47327. else {
  47328. subMaterial = this.subMaterials[index];
  47329. }
  47330. newMultiMaterial.subMaterials.push(subMaterial);
  47331. }
  47332. return newMultiMaterial;
  47333. };
  47334. MultiMaterial.prototype.serialize = function () {
  47335. var serializationObject = {};
  47336. serializationObject.name = this.name;
  47337. serializationObject.id = this.id;
  47338. serializationObject.tags = BABYLON.Tags.GetTags(this);
  47339. serializationObject.materials = [];
  47340. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  47341. var subMat = this.subMaterials[matIndex];
  47342. if (subMat) {
  47343. serializationObject.materials.push(subMat.id);
  47344. }
  47345. else {
  47346. serializationObject.materials.push(null);
  47347. }
  47348. }
  47349. return serializationObject;
  47350. };
  47351. return MultiMaterial;
  47352. }(BABYLON.Material));
  47353. BABYLON.MultiMaterial = MultiMaterial;
  47354. })(BABYLON || (BABYLON = {}));
  47355. //# sourceMappingURL=babylon.multiMaterial.js.map
  47356. var BABYLON;
  47357. (function (BABYLON) {
  47358. var FreeCameraTouchInput = (function () {
  47359. function FreeCameraTouchInput() {
  47360. this._offsetX = null;
  47361. this._offsetY = null;
  47362. this._pointerCount = 0;
  47363. this._pointerPressed = [];
  47364. this.touchAngularSensibility = 200000.0;
  47365. this.touchMoveSensibility = 250.0;
  47366. }
  47367. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  47368. var _this = this;
  47369. var previousPosition;
  47370. if (this._pointerInput === undefined) {
  47371. this._onLostFocus = function (evt) {
  47372. _this._offsetX = null;
  47373. _this._offsetY = null;
  47374. };
  47375. this._pointerInput = function (p, s) {
  47376. var evt = p.event;
  47377. if (evt.pointerType === "mouse") {
  47378. return;
  47379. }
  47380. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  47381. if (!noPreventDefault) {
  47382. evt.preventDefault();
  47383. }
  47384. _this._pointerPressed.push(evt.pointerId);
  47385. if (_this._pointerPressed.length !== 1) {
  47386. return;
  47387. }
  47388. previousPosition = {
  47389. x: evt.clientX,
  47390. y: evt.clientY
  47391. };
  47392. }
  47393. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  47394. if (!noPreventDefault) {
  47395. evt.preventDefault();
  47396. }
  47397. var index = _this._pointerPressed.indexOf(evt.pointerId);
  47398. if (index === -1) {
  47399. return;
  47400. }
  47401. _this._pointerPressed.splice(index, 1);
  47402. if (index != 0) {
  47403. return;
  47404. }
  47405. previousPosition = null;
  47406. _this._offsetX = null;
  47407. _this._offsetY = null;
  47408. }
  47409. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47410. if (!noPreventDefault) {
  47411. evt.preventDefault();
  47412. }
  47413. if (!previousPosition) {
  47414. return;
  47415. }
  47416. var index = _this._pointerPressed.indexOf(evt.pointerId);
  47417. if (index != 0) {
  47418. return;
  47419. }
  47420. _this._offsetX = evt.clientX - previousPosition.x;
  47421. _this._offsetY = -(evt.clientY - previousPosition.y);
  47422. }
  47423. };
  47424. }
  47425. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47426. element.addEventListener("blur", this._onLostFocus);
  47427. };
  47428. FreeCameraTouchInput.prototype.detachControl = function (element) {
  47429. if (this._pointerInput && element) {
  47430. this.camera.getScene().onPointerObservable.remove(this._observer);
  47431. this._observer = null;
  47432. element.removeEventListener("blur", this._onLostFocus);
  47433. this._onLostFocus = null;
  47434. this._pointerPressed = [];
  47435. this._offsetX = null;
  47436. this._offsetY = null;
  47437. this._pointerCount = 0;
  47438. }
  47439. };
  47440. FreeCameraTouchInput.prototype.checkInputs = function () {
  47441. if (this._offsetX) {
  47442. var camera = this.camera;
  47443. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  47444. if (this._pointerPressed.length > 1) {
  47445. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  47446. }
  47447. else {
  47448. var speed = camera._computeLocalCameraSpeed();
  47449. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  47450. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  47451. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  47452. }
  47453. }
  47454. };
  47455. FreeCameraTouchInput.prototype.getTypeName = function () {
  47456. return "FreeCameraTouchInput";
  47457. };
  47458. FreeCameraTouchInput.prototype.getSimpleName = function () {
  47459. return "touch";
  47460. };
  47461. return FreeCameraTouchInput;
  47462. }());
  47463. __decorate([
  47464. BABYLON.serialize()
  47465. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  47466. __decorate([
  47467. BABYLON.serialize()
  47468. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  47469. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  47470. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  47471. })(BABYLON || (BABYLON = {}));
  47472. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  47473. /// <reference path="babylon.freeCamera.ts" />
  47474. var BABYLON;
  47475. (function (BABYLON) {
  47476. // We're mainly based on the logic defined into the FreeCamera code
  47477. var TouchCamera = (function (_super) {
  47478. __extends(TouchCamera, _super);
  47479. //-- end properties for backward compatibility for inputs
  47480. function TouchCamera(name, position, scene) {
  47481. var _this = _super.call(this, name, position, scene) || this;
  47482. _this.inputs.addTouch();
  47483. _this._setupInputs();
  47484. return _this;
  47485. }
  47486. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  47487. //-- Begin properties for backward compatibility for inputs
  47488. get: function () {
  47489. var touch = this.inputs.attached["touch"];
  47490. if (touch)
  47491. return touch.touchAngularSensibility;
  47492. },
  47493. set: function (value) {
  47494. var touch = this.inputs.attached["touch"];
  47495. if (touch)
  47496. touch.touchAngularSensibility = value;
  47497. },
  47498. enumerable: true,
  47499. configurable: true
  47500. });
  47501. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  47502. get: function () {
  47503. var touch = this.inputs.attached["touch"];
  47504. if (touch)
  47505. return touch.touchMoveSensibility;
  47506. },
  47507. set: function (value) {
  47508. var touch = this.inputs.attached["touch"];
  47509. if (touch)
  47510. touch.touchMoveSensibility = value;
  47511. },
  47512. enumerable: true,
  47513. configurable: true
  47514. });
  47515. TouchCamera.prototype.getClassName = function () {
  47516. return "TouchCamera";
  47517. };
  47518. TouchCamera.prototype._setupInputs = function () {
  47519. var mouse = this.inputs.attached["mouse"];
  47520. if (mouse) {
  47521. mouse.touchEnabled = false;
  47522. }
  47523. };
  47524. return TouchCamera;
  47525. }(BABYLON.FreeCamera));
  47526. BABYLON.TouchCamera = TouchCamera;
  47527. })(BABYLON || (BABYLON = {}));
  47528. //# sourceMappingURL=babylon.touchCamera.js.map
  47529. var BABYLON;
  47530. (function (BABYLON) {
  47531. var ProceduralTexture = (function (_super) {
  47532. __extends(ProceduralTexture, _super);
  47533. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  47534. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47535. if (isCube === void 0) { isCube = false; }
  47536. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  47537. _this.isCube = isCube;
  47538. _this.isEnabled = true;
  47539. _this._currentRefreshId = -1;
  47540. _this._refreshRate = 1;
  47541. _this._vertexBuffers = {};
  47542. _this._uniforms = new Array();
  47543. _this._samplers = new Array();
  47544. _this._textures = new Array();
  47545. _this._floats = new Array();
  47546. _this._floatsArrays = {};
  47547. _this._colors3 = new Array();
  47548. _this._colors4 = new Array();
  47549. _this._vectors2 = new Array();
  47550. _this._vectors3 = new Array();
  47551. _this._matrices = new Array();
  47552. _this._fallbackTextureUsed = false;
  47553. scene._proceduralTextures.push(_this);
  47554. _this.name = name;
  47555. _this.isRenderTarget = true;
  47556. _this._size = size;
  47557. _this._generateMipMaps = generateMipMaps;
  47558. _this.setFragment(fragment);
  47559. _this._fallbackTexture = fallbackTexture;
  47560. var engine = scene.getEngine();
  47561. if (isCube) {
  47562. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  47563. _this.setFloat("face", 0);
  47564. }
  47565. else {
  47566. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  47567. }
  47568. // VBO
  47569. var vertices = [];
  47570. vertices.push(1, 1);
  47571. vertices.push(-1, 1);
  47572. vertices.push(-1, -1);
  47573. vertices.push(1, -1);
  47574. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  47575. // Indices
  47576. var indices = [];
  47577. indices.push(0);
  47578. indices.push(1);
  47579. indices.push(2);
  47580. indices.push(0);
  47581. indices.push(2);
  47582. indices.push(3);
  47583. _this._indexBuffer = engine.createIndexBuffer(indices);
  47584. return _this;
  47585. }
  47586. ProceduralTexture.prototype.reset = function () {
  47587. if (this._effect === undefined) {
  47588. return;
  47589. }
  47590. var engine = this.getScene().getEngine();
  47591. engine._releaseEffect(this._effect);
  47592. };
  47593. ProceduralTexture.prototype.isReady = function () {
  47594. var _this = this;
  47595. var engine = this.getScene().getEngine();
  47596. var shaders;
  47597. if (!this._fragment) {
  47598. return false;
  47599. }
  47600. if (this._fallbackTextureUsed) {
  47601. return true;
  47602. }
  47603. if (this._fragment.fragmentElement !== undefined) {
  47604. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  47605. }
  47606. else {
  47607. shaders = { vertex: "procedural", fragment: this._fragment };
  47608. }
  47609. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  47610. _this.releaseInternalTexture();
  47611. if (_this._fallbackTexture) {
  47612. _this._texture = _this._fallbackTexture._texture;
  47613. _this._texture.references++;
  47614. }
  47615. _this._fallbackTextureUsed = true;
  47616. });
  47617. return this._effect.isReady();
  47618. };
  47619. ProceduralTexture.prototype.resetRefreshCounter = function () {
  47620. this._currentRefreshId = -1;
  47621. };
  47622. ProceduralTexture.prototype.setFragment = function (fragment) {
  47623. this._fragment = fragment;
  47624. };
  47625. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  47626. get: function () {
  47627. return this._refreshRate;
  47628. },
  47629. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  47630. set: function (value) {
  47631. this._refreshRate = value;
  47632. this.resetRefreshCounter();
  47633. },
  47634. enumerable: true,
  47635. configurable: true
  47636. });
  47637. ProceduralTexture.prototype._shouldRender = function () {
  47638. if (!this.isEnabled || !this.isReady() || !this._texture) {
  47639. return false;
  47640. }
  47641. if (this._fallbackTextureUsed) {
  47642. return false;
  47643. }
  47644. if (this._currentRefreshId === -1) {
  47645. this._currentRefreshId = 1;
  47646. return true;
  47647. }
  47648. if (this.refreshRate === this._currentRefreshId) {
  47649. this._currentRefreshId = 1;
  47650. return true;
  47651. }
  47652. this._currentRefreshId++;
  47653. return false;
  47654. };
  47655. ProceduralTexture.prototype.getRenderSize = function () {
  47656. return this._size;
  47657. };
  47658. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  47659. if (this._fallbackTextureUsed) {
  47660. return;
  47661. }
  47662. this.releaseInternalTexture();
  47663. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  47664. };
  47665. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  47666. if (this._uniforms.indexOf(uniformName) === -1) {
  47667. this._uniforms.push(uniformName);
  47668. }
  47669. };
  47670. ProceduralTexture.prototype.setTexture = function (name, texture) {
  47671. if (this._samplers.indexOf(name) === -1) {
  47672. this._samplers.push(name);
  47673. }
  47674. this._textures[name] = texture;
  47675. return this;
  47676. };
  47677. ProceduralTexture.prototype.setFloat = function (name, value) {
  47678. this._checkUniform(name);
  47679. this._floats[name] = value;
  47680. return this;
  47681. };
  47682. ProceduralTexture.prototype.setFloats = function (name, value) {
  47683. this._checkUniform(name);
  47684. this._floatsArrays[name] = value;
  47685. return this;
  47686. };
  47687. ProceduralTexture.prototype.setColor3 = function (name, value) {
  47688. this._checkUniform(name);
  47689. this._colors3[name] = value;
  47690. return this;
  47691. };
  47692. ProceduralTexture.prototype.setColor4 = function (name, value) {
  47693. this._checkUniform(name);
  47694. this._colors4[name] = value;
  47695. return this;
  47696. };
  47697. ProceduralTexture.prototype.setVector2 = function (name, value) {
  47698. this._checkUniform(name);
  47699. this._vectors2[name] = value;
  47700. return this;
  47701. };
  47702. ProceduralTexture.prototype.setVector3 = function (name, value) {
  47703. this._checkUniform(name);
  47704. this._vectors3[name] = value;
  47705. return this;
  47706. };
  47707. ProceduralTexture.prototype.setMatrix = function (name, value) {
  47708. this._checkUniform(name);
  47709. this._matrices[name] = value;
  47710. return this;
  47711. };
  47712. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  47713. var scene = this.getScene();
  47714. var engine = scene.getEngine();
  47715. // Render
  47716. engine.enableEffect(this._effect);
  47717. engine.setState(false);
  47718. // Texture
  47719. for (var name in this._textures) {
  47720. this._effect.setTexture(name, this._textures[name]);
  47721. }
  47722. // Float
  47723. for (name in this._floats) {
  47724. this._effect.setFloat(name, this._floats[name]);
  47725. }
  47726. // Floats
  47727. for (name in this._floatsArrays) {
  47728. this._effect.setArray(name, this._floatsArrays[name]);
  47729. }
  47730. // Color3
  47731. for (name in this._colors3) {
  47732. this._effect.setColor3(name, this._colors3[name]);
  47733. }
  47734. // Color4
  47735. for (name in this._colors4) {
  47736. var color = this._colors4[name];
  47737. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47738. }
  47739. // Vector2
  47740. for (name in this._vectors2) {
  47741. this._effect.setVector2(name, this._vectors2[name]);
  47742. }
  47743. // Vector3
  47744. for (name in this._vectors3) {
  47745. this._effect.setVector3(name, this._vectors3[name]);
  47746. }
  47747. // Matrix
  47748. for (name in this._matrices) {
  47749. this._effect.setMatrix(name, this._matrices[name]);
  47750. }
  47751. if (this.isCube) {
  47752. for (var face = 0; face < 6; face++) {
  47753. engine.bindFramebuffer(this._texture, face);
  47754. // VBOs
  47755. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  47756. this._effect.setFloat("face", face);
  47757. // Clear
  47758. engine.clear(scene.clearColor, true, true, true);
  47759. // Draw order
  47760. engine.draw(true, 0, 6);
  47761. // Mipmaps
  47762. if (face === 5) {
  47763. engine.generateMipMapsForCubemap(this._texture);
  47764. }
  47765. }
  47766. }
  47767. else {
  47768. engine.bindFramebuffer(this._texture);
  47769. // VBOs
  47770. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  47771. // Clear
  47772. engine.clear(scene.clearColor, true, true, true);
  47773. // Draw order
  47774. engine.draw(true, 0, 6);
  47775. }
  47776. // Unbind
  47777. engine.unBindFramebuffer(this._texture, this.isCube);
  47778. if (this.onGenerated) {
  47779. this.onGenerated();
  47780. }
  47781. };
  47782. ProceduralTexture.prototype.clone = function () {
  47783. var textureSize = this.getSize();
  47784. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  47785. // Base texture
  47786. newTexture.hasAlpha = this.hasAlpha;
  47787. newTexture.level = this.level;
  47788. // RenderTarget Texture
  47789. newTexture.coordinatesMode = this.coordinatesMode;
  47790. return newTexture;
  47791. };
  47792. ProceduralTexture.prototype.dispose = function () {
  47793. var index = this.getScene()._proceduralTextures.indexOf(this);
  47794. if (index >= 0) {
  47795. this.getScene()._proceduralTextures.splice(index, 1);
  47796. }
  47797. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47798. if (vertexBuffer) {
  47799. vertexBuffer.dispose();
  47800. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47801. }
  47802. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  47803. this._indexBuffer = null;
  47804. }
  47805. _super.prototype.dispose.call(this);
  47806. };
  47807. return ProceduralTexture;
  47808. }(BABYLON.Texture));
  47809. BABYLON.ProceduralTexture = ProceduralTexture;
  47810. })(BABYLON || (BABYLON = {}));
  47811. //# sourceMappingURL=babylon.proceduralTexture.js.map
  47812. /// <reference path="babylon.proceduralTexture.ts" />
  47813. var BABYLON;
  47814. (function (BABYLON) {
  47815. var CustomProceduralTexture = (function (_super) {
  47816. __extends(CustomProceduralTexture, _super);
  47817. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  47818. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  47819. _this._animate = true;
  47820. _this._time = 0;
  47821. _this._texturePath = texturePath;
  47822. //Try to load json
  47823. _this.loadJson(texturePath);
  47824. _this.refreshRate = 1;
  47825. return _this;
  47826. }
  47827. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  47828. var _this = this;
  47829. var that = this;
  47830. function noConfigFile() {
  47831. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  47832. try {
  47833. that.setFragment(that._texturePath);
  47834. }
  47835. catch (ex) {
  47836. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  47837. }
  47838. }
  47839. var configFileUrl = jsonUrl + "/config.json";
  47840. var xhr = new XMLHttpRequest();
  47841. xhr.open("GET", configFileUrl, true);
  47842. xhr.addEventListener("load", function () {
  47843. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  47844. try {
  47845. _this._config = JSON.parse(xhr.response);
  47846. _this.updateShaderUniforms();
  47847. _this.updateTextures();
  47848. _this.setFragment(_this._texturePath + "/custom");
  47849. _this._animate = _this._config.animate;
  47850. _this.refreshRate = _this._config.refreshrate;
  47851. }
  47852. catch (ex) {
  47853. noConfigFile();
  47854. }
  47855. }
  47856. else {
  47857. noConfigFile();
  47858. }
  47859. }, false);
  47860. xhr.addEventListener("error", function () {
  47861. noConfigFile();
  47862. }, false);
  47863. try {
  47864. xhr.send();
  47865. }
  47866. catch (ex) {
  47867. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  47868. }
  47869. };
  47870. CustomProceduralTexture.prototype.isReady = function () {
  47871. if (!_super.prototype.isReady.call(this)) {
  47872. return false;
  47873. }
  47874. for (var name in this._textures) {
  47875. var texture = this._textures[name];
  47876. if (!texture.isReady()) {
  47877. return false;
  47878. }
  47879. }
  47880. return true;
  47881. };
  47882. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  47883. if (this._animate) {
  47884. this._time += this.getScene().getAnimationRatio() * 0.03;
  47885. this.updateShaderUniforms();
  47886. }
  47887. _super.prototype.render.call(this, useCameraPostProcess);
  47888. };
  47889. CustomProceduralTexture.prototype.updateTextures = function () {
  47890. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  47891. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  47892. }
  47893. };
  47894. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  47895. if (this._config) {
  47896. for (var j = 0; j < this._config.uniforms.length; j++) {
  47897. var uniform = this._config.uniforms[j];
  47898. switch (uniform.type) {
  47899. case "float":
  47900. this.setFloat(uniform.name, uniform.value);
  47901. break;
  47902. case "color3":
  47903. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  47904. break;
  47905. case "color4":
  47906. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  47907. break;
  47908. case "vector2":
  47909. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  47910. break;
  47911. case "vector3":
  47912. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  47913. break;
  47914. }
  47915. }
  47916. }
  47917. this.setFloat("time", this._time);
  47918. };
  47919. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  47920. get: function () {
  47921. return this._animate;
  47922. },
  47923. set: function (value) {
  47924. this._animate = value;
  47925. },
  47926. enumerable: true,
  47927. configurable: true
  47928. });
  47929. return CustomProceduralTexture;
  47930. }(BABYLON.ProceduralTexture));
  47931. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  47932. })(BABYLON || (BABYLON = {}));
  47933. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  47934. var BABYLON;
  47935. (function (BABYLON) {
  47936. var FreeCameraGamepadInput = (function () {
  47937. function FreeCameraGamepadInput() {
  47938. this.gamepadAngularSensibility = 200;
  47939. this.gamepadMoveSensibility = 40;
  47940. // private members
  47941. this._cameraTransform = BABYLON.Matrix.Identity();
  47942. this._deltaTransform = BABYLON.Vector3.Zero();
  47943. this._vector3 = BABYLON.Vector3.Zero();
  47944. this._vector2 = BABYLON.Vector2.Zero();
  47945. }
  47946. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  47947. var _this = this;
  47948. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  47949. };
  47950. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  47951. if (this._gamepads) {
  47952. this._gamepads.dispose();
  47953. }
  47954. this.gamepad = null;
  47955. };
  47956. FreeCameraGamepadInput.prototype.checkInputs = function () {
  47957. if (this.gamepad && this.gamepad.leftStick) {
  47958. var camera = this.camera;
  47959. var LSValues = this.gamepad.leftStick;
  47960. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  47961. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  47962. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  47963. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  47964. var RSValues = this.gamepad.rightStick;
  47965. if (RSValues) {
  47966. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  47967. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  47968. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  47969. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  47970. }
  47971. else {
  47972. RSValues = { x: 0, y: 0 };
  47973. }
  47974. if (!camera.rotationQuaternion) {
  47975. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  47976. }
  47977. else {
  47978. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  47979. }
  47980. var speed = camera._computeLocalCameraSpeed() * 50.0;
  47981. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  47982. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  47983. camera.cameraDirection.addInPlace(this._deltaTransform);
  47984. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  47985. camera.cameraRotation.addInPlace(this._vector2);
  47986. }
  47987. };
  47988. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  47989. // Only the first gamepad found can control the camera
  47990. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  47991. // prioritize XBOX gamepads.
  47992. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  47993. this.gamepad = gamepad;
  47994. }
  47995. }
  47996. };
  47997. FreeCameraGamepadInput.prototype.getTypeName = function () {
  47998. return "FreeCameraGamepadInput";
  47999. };
  48000. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  48001. return "gamepad";
  48002. };
  48003. return FreeCameraGamepadInput;
  48004. }());
  48005. __decorate([
  48006. BABYLON.serialize()
  48007. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  48008. __decorate([
  48009. BABYLON.serialize()
  48010. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  48011. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  48012. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  48013. })(BABYLON || (BABYLON = {}));
  48014. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  48015. var BABYLON;
  48016. (function (BABYLON) {
  48017. var ArcRotateCameraGamepadInput = (function () {
  48018. function ArcRotateCameraGamepadInput() {
  48019. this.gamepadRotationSensibility = 80;
  48020. this.gamepadMoveSensibility = 40;
  48021. }
  48022. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  48023. var _this = this;
  48024. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  48025. };
  48026. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  48027. if (this._gamepads) {
  48028. this._gamepads.dispose();
  48029. }
  48030. this.gamepad = null;
  48031. };
  48032. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  48033. if (this.gamepad) {
  48034. var camera = this.camera;
  48035. var RSValues = this.gamepad.rightStick;
  48036. if (RSValues) {
  48037. if (RSValues.x != 0) {
  48038. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  48039. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  48040. camera.inertialAlphaOffset += normalizedRX;
  48041. }
  48042. }
  48043. if (RSValues.y != 0) {
  48044. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  48045. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  48046. camera.inertialBetaOffset += normalizedRY;
  48047. }
  48048. }
  48049. }
  48050. var LSValues = this.gamepad.leftStick;
  48051. if (LSValues && LSValues.y != 0) {
  48052. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  48053. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  48054. this.camera.inertialRadiusOffset -= normalizedLY;
  48055. }
  48056. }
  48057. }
  48058. };
  48059. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  48060. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  48061. // prioritize XBOX gamepads.
  48062. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  48063. this.gamepad = gamepad;
  48064. }
  48065. }
  48066. };
  48067. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  48068. return "ArcRotateCameraGamepadInput";
  48069. };
  48070. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  48071. return "gamepad";
  48072. };
  48073. return ArcRotateCameraGamepadInput;
  48074. }());
  48075. __decorate([
  48076. BABYLON.serialize()
  48077. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  48078. __decorate([
  48079. BABYLON.serialize()
  48080. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  48081. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  48082. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  48083. })(BABYLON || (BABYLON = {}));
  48084. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  48085. var BABYLON;
  48086. (function (BABYLON) {
  48087. var Gamepads = (function () {
  48088. function Gamepads(ongamedpadconnected, ongamedpaddisconnected) {
  48089. var _this = this;
  48090. this.babylonGamepads = [];
  48091. this.oneGamepadConnected = false;
  48092. this.isMonitoring = false;
  48093. this.gamepadEventSupported = 'GamepadEvent' in window;
  48094. this.gamepadSupport = (navigator.getGamepads ||
  48095. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  48096. this._callbackGamepadConnected = ongamedpadconnected;
  48097. this._callbackGamepadDisconnected = ongamedpaddisconnected;
  48098. if (this.gamepadSupport) {
  48099. //first add already-connected gamepads
  48100. this._updateGamepadObjects();
  48101. if (this.babylonGamepads.length) {
  48102. this._startMonitoringGamepads();
  48103. }
  48104. // Checking if the gamepad connected event is supported (like in Firefox)
  48105. if (this.gamepadEventSupported) {
  48106. this._onGamepadConnectedEvent = function (evt) {
  48107. _this._onGamepadConnected(evt.gamepad);
  48108. };
  48109. this._onGamepadDisonnectedEvent = function (evt) {
  48110. _this._onGamepadDisconnected(evt.gamepad);
  48111. };
  48112. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  48113. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  48114. }
  48115. else {
  48116. this._startMonitoringGamepads();
  48117. }
  48118. }
  48119. }
  48120. Gamepads.prototype.dispose = function () {
  48121. if (this._onGamepadConnectedEvent) {
  48122. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  48123. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  48124. this._onGamepadConnectedEvent = null;
  48125. this._onGamepadDisonnectedEvent = null;
  48126. }
  48127. this.oneGamepadConnected = false;
  48128. this._stopMonitoringGamepads();
  48129. this.babylonGamepads = [];
  48130. };
  48131. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  48132. // Protection code for Chrome which has a very buggy gamepad implementation...
  48133. // And raises a connected event on disconnection for instance
  48134. if (gamepad.index in this.babylonGamepads) {
  48135. return;
  48136. }
  48137. var newGamepad = this._addNewGamepad(gamepad);
  48138. if (this._callbackGamepadConnected)
  48139. this._callbackGamepadConnected(newGamepad);
  48140. this._startMonitoringGamepads();
  48141. };
  48142. Gamepads.prototype._addNewGamepad = function (gamepad) {
  48143. if (!this.oneGamepadConnected) {
  48144. this.oneGamepadConnected = true;
  48145. }
  48146. var newGamepad;
  48147. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  48148. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  48149. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  48150. }
  48151. else if (gamepad.pose) {
  48152. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  48153. }
  48154. else {
  48155. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  48156. }
  48157. this.babylonGamepads.push(newGamepad);
  48158. return newGamepad;
  48159. };
  48160. Gamepads.prototype._onGamepadDisconnected = function (gamepad) {
  48161. // Remove the gamepad from the list of gamepads to monitor.
  48162. for (var i in this.babylonGamepads) {
  48163. if (this.babylonGamepads[i].index == gamepad.index) {
  48164. this.babylonGamepads.splice(+i, 1);
  48165. break;
  48166. }
  48167. }
  48168. // If no gamepads are left, stop the polling loop.
  48169. if (this.babylonGamepads.length == 0) {
  48170. this._stopMonitoringGamepads();
  48171. this.oneGamepadConnected = false;
  48172. }
  48173. if (this._callbackGamepadDisconnected)
  48174. this._callbackGamepadDisconnected(gamepad);
  48175. };
  48176. Gamepads.prototype._startMonitoringGamepads = function () {
  48177. if (!this.isMonitoring) {
  48178. this.isMonitoring = true;
  48179. this._checkGamepadsStatus();
  48180. }
  48181. };
  48182. Gamepads.prototype._stopMonitoringGamepads = function () {
  48183. this.isMonitoring = false;
  48184. };
  48185. Gamepads.prototype._checkGamepadsStatus = function () {
  48186. var _this = this;
  48187. // Hack to be compatible Chrome
  48188. this._updateGamepadObjects();
  48189. for (var i in this.babylonGamepads) {
  48190. this.babylonGamepads[i].update();
  48191. }
  48192. if (this.isMonitoring) {
  48193. if (window.requestAnimationFrame) {
  48194. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48195. }
  48196. else if (window.mozRequestAnimationFrame) {
  48197. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48198. }
  48199. else if (window.webkitRequestAnimationFrame) {
  48200. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48201. }
  48202. }
  48203. };
  48204. // This function is called only on Chrome, which does not properly support
  48205. // connection/disconnection events and forces you to recopy again the gamepad object
  48206. Gamepads.prototype._updateGamepadObjects = function () {
  48207. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  48208. for (var i = 0; i < gamepads.length; i++) {
  48209. if (gamepads[i]) {
  48210. if (!(gamepads[i].index in this.babylonGamepads)) {
  48211. var newGamepad = this._addNewGamepad(gamepads[i]);
  48212. if (this._callbackGamepadConnected) {
  48213. this._callbackGamepadConnected(newGamepad);
  48214. }
  48215. }
  48216. else {
  48217. // Forced to copy again this object for Chrome for unknown reason
  48218. this.babylonGamepads[i].browserGamepad = gamepads[i];
  48219. }
  48220. }
  48221. }
  48222. };
  48223. return Gamepads;
  48224. }());
  48225. BABYLON.Gamepads = Gamepads;
  48226. var StickValues = (function () {
  48227. function StickValues(x, y) {
  48228. this.x = x;
  48229. this.y = y;
  48230. }
  48231. return StickValues;
  48232. }());
  48233. BABYLON.StickValues = StickValues;
  48234. var Gamepad = (function () {
  48235. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  48236. if (leftStickX === void 0) { leftStickX = 0; }
  48237. if (leftStickY === void 0) { leftStickY = 1; }
  48238. if (rightStickX === void 0) { rightStickX = 2; }
  48239. if (rightStickY === void 0) { rightStickY = 3; }
  48240. this.id = id;
  48241. this.index = index;
  48242. this.browserGamepad = browserGamepad;
  48243. this.type = Gamepad.GAMEPAD;
  48244. this._leftStickAxisX = leftStickX;
  48245. this._leftStickAxisY = leftStickY;
  48246. this._rightStickAxisX = rightStickX;
  48247. this._rightStickAxisY = rightStickY;
  48248. if (this.browserGamepad.axes.length >= 2) {
  48249. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  48250. }
  48251. if (this.browserGamepad.axes.length >= 4) {
  48252. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  48253. }
  48254. }
  48255. Gamepad.prototype.onleftstickchanged = function (callback) {
  48256. this._onleftstickchanged = callback;
  48257. };
  48258. Gamepad.prototype.onrightstickchanged = function (callback) {
  48259. this._onrightstickchanged = callback;
  48260. };
  48261. Object.defineProperty(Gamepad.prototype, "leftStick", {
  48262. get: function () {
  48263. return this._leftStick;
  48264. },
  48265. set: function (newValues) {
  48266. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  48267. this._onleftstickchanged(newValues);
  48268. }
  48269. this._leftStick = newValues;
  48270. },
  48271. enumerable: true,
  48272. configurable: true
  48273. });
  48274. Object.defineProperty(Gamepad.prototype, "rightStick", {
  48275. get: function () {
  48276. return this._rightStick;
  48277. },
  48278. set: function (newValues) {
  48279. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  48280. this._onrightstickchanged(newValues);
  48281. }
  48282. this._rightStick = newValues;
  48283. },
  48284. enumerable: true,
  48285. configurable: true
  48286. });
  48287. Gamepad.prototype.update = function () {
  48288. if (this._leftStick) {
  48289. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  48290. }
  48291. if (this._rightStick) {
  48292. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  48293. }
  48294. };
  48295. return Gamepad;
  48296. }());
  48297. Gamepad.GAMEPAD = 0;
  48298. Gamepad.GENERIC = 1;
  48299. Gamepad.XBOX = 2;
  48300. Gamepad.POSE_ENABLED = 3;
  48301. BABYLON.Gamepad = Gamepad;
  48302. var GenericPad = (function (_super) {
  48303. __extends(GenericPad, _super);
  48304. function GenericPad(id, index, browserGamepad) {
  48305. var _this = _super.call(this, id, index, browserGamepad) || this;
  48306. _this.type = Gamepad.GENERIC;
  48307. _this._buttons = new Array(browserGamepad.buttons.length);
  48308. return _this;
  48309. }
  48310. GenericPad.prototype.onbuttondown = function (callback) {
  48311. this._onbuttondown = callback;
  48312. };
  48313. GenericPad.prototype.onbuttonup = function (callback) {
  48314. this._onbuttonup = callback;
  48315. };
  48316. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  48317. if (newValue !== currentValue) {
  48318. if (this._onbuttondown && newValue === 1) {
  48319. this._onbuttondown(buttonIndex);
  48320. }
  48321. if (this._onbuttonup && newValue === 0) {
  48322. this._onbuttonup(buttonIndex);
  48323. }
  48324. }
  48325. return newValue;
  48326. };
  48327. GenericPad.prototype.update = function () {
  48328. _super.prototype.update.call(this);
  48329. for (var index = 0; index < this._buttons.length; index++) {
  48330. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  48331. }
  48332. };
  48333. return GenericPad;
  48334. }(Gamepad));
  48335. BABYLON.GenericPad = GenericPad;
  48336. var Xbox360Button;
  48337. (function (Xbox360Button) {
  48338. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  48339. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  48340. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  48341. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  48342. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  48343. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  48344. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  48345. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  48346. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  48347. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  48348. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  48349. var Xbox360Dpad;
  48350. (function (Xbox360Dpad) {
  48351. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  48352. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  48353. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  48354. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  48355. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  48356. var Xbox360Pad = (function (_super) {
  48357. __extends(Xbox360Pad, _super);
  48358. function Xbox360Pad(id, index, gamepad, xboxOne) {
  48359. if (xboxOne === void 0) { xboxOne = false; }
  48360. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  48361. _this._leftTrigger = 0;
  48362. _this._rightTrigger = 0;
  48363. _this._buttonA = 0;
  48364. _this._buttonB = 0;
  48365. _this._buttonX = 0;
  48366. _this._buttonY = 0;
  48367. _this._buttonBack = 0;
  48368. _this._buttonStart = 0;
  48369. _this._buttonLB = 0;
  48370. _this._buttonRB = 0;
  48371. _this._buttonLeftStick = 0;
  48372. _this._buttonRightStick = 0;
  48373. _this._dPadUp = 0;
  48374. _this._dPadDown = 0;
  48375. _this._dPadLeft = 0;
  48376. _this._dPadRight = 0;
  48377. _this._isXboxOnePad = false;
  48378. _this.type = Gamepad.XBOX;
  48379. _this._isXboxOnePad = xboxOne;
  48380. return _this;
  48381. }
  48382. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  48383. this._onlefttriggerchanged = callback;
  48384. };
  48385. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  48386. this._onrighttriggerchanged = callback;
  48387. };
  48388. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  48389. get: function () {
  48390. return this._leftTrigger;
  48391. },
  48392. set: function (newValue) {
  48393. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  48394. this._onlefttriggerchanged(newValue);
  48395. }
  48396. this._leftTrigger = newValue;
  48397. },
  48398. enumerable: true,
  48399. configurable: true
  48400. });
  48401. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  48402. get: function () {
  48403. return this._rightTrigger;
  48404. },
  48405. set: function (newValue) {
  48406. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  48407. this._onrighttriggerchanged(newValue);
  48408. }
  48409. this._rightTrigger = newValue;
  48410. },
  48411. enumerable: true,
  48412. configurable: true
  48413. });
  48414. Xbox360Pad.prototype.onbuttondown = function (callback) {
  48415. this._onbuttondown = callback;
  48416. };
  48417. Xbox360Pad.prototype.onbuttonup = function (callback) {
  48418. this._onbuttonup = callback;
  48419. };
  48420. Xbox360Pad.prototype.ondpaddown = function (callback) {
  48421. this._ondpaddown = callback;
  48422. };
  48423. Xbox360Pad.prototype.ondpadup = function (callback) {
  48424. this._ondpadup = callback;
  48425. };
  48426. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  48427. if (newValue !== currentValue) {
  48428. if (this._onbuttondown && newValue === 1) {
  48429. this._onbuttondown(buttonType);
  48430. }
  48431. if (this._onbuttonup && newValue === 0) {
  48432. this._onbuttonup(buttonType);
  48433. }
  48434. }
  48435. return newValue;
  48436. };
  48437. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  48438. if (newValue !== currentValue) {
  48439. if (this._ondpaddown && newValue === 1) {
  48440. this._ondpaddown(buttonType);
  48441. }
  48442. if (this._ondpadup && newValue === 0) {
  48443. this._ondpadup(buttonType);
  48444. }
  48445. }
  48446. return newValue;
  48447. };
  48448. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  48449. get: function () {
  48450. return this._buttonA;
  48451. },
  48452. set: function (value) {
  48453. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  48454. },
  48455. enumerable: true,
  48456. configurable: true
  48457. });
  48458. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  48459. get: function () {
  48460. return this._buttonB;
  48461. },
  48462. set: function (value) {
  48463. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  48464. },
  48465. enumerable: true,
  48466. configurable: true
  48467. });
  48468. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  48469. get: function () {
  48470. return this._buttonX;
  48471. },
  48472. set: function (value) {
  48473. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  48474. },
  48475. enumerable: true,
  48476. configurable: true
  48477. });
  48478. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  48479. get: function () {
  48480. return this._buttonY;
  48481. },
  48482. set: function (value) {
  48483. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  48484. },
  48485. enumerable: true,
  48486. configurable: true
  48487. });
  48488. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  48489. get: function () {
  48490. return this._buttonStart;
  48491. },
  48492. set: function (value) {
  48493. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  48494. },
  48495. enumerable: true,
  48496. configurable: true
  48497. });
  48498. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  48499. get: function () {
  48500. return this._buttonBack;
  48501. },
  48502. set: function (value) {
  48503. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  48504. },
  48505. enumerable: true,
  48506. configurable: true
  48507. });
  48508. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  48509. get: function () {
  48510. return this._buttonLB;
  48511. },
  48512. set: function (value) {
  48513. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  48514. },
  48515. enumerable: true,
  48516. configurable: true
  48517. });
  48518. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  48519. get: function () {
  48520. return this._buttonRB;
  48521. },
  48522. set: function (value) {
  48523. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  48524. },
  48525. enumerable: true,
  48526. configurable: true
  48527. });
  48528. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  48529. get: function () {
  48530. return this._buttonLeftStick;
  48531. },
  48532. set: function (value) {
  48533. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  48534. },
  48535. enumerable: true,
  48536. configurable: true
  48537. });
  48538. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  48539. get: function () {
  48540. return this._buttonRightStick;
  48541. },
  48542. set: function (value) {
  48543. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  48544. },
  48545. enumerable: true,
  48546. configurable: true
  48547. });
  48548. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  48549. get: function () {
  48550. return this._dPadUp;
  48551. },
  48552. set: function (value) {
  48553. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  48554. },
  48555. enumerable: true,
  48556. configurable: true
  48557. });
  48558. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  48559. get: function () {
  48560. return this._dPadDown;
  48561. },
  48562. set: function (value) {
  48563. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  48564. },
  48565. enumerable: true,
  48566. configurable: true
  48567. });
  48568. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  48569. get: function () {
  48570. return this._dPadLeft;
  48571. },
  48572. set: function (value) {
  48573. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  48574. },
  48575. enumerable: true,
  48576. configurable: true
  48577. });
  48578. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  48579. get: function () {
  48580. return this._dPadRight;
  48581. },
  48582. set: function (value) {
  48583. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  48584. },
  48585. enumerable: true,
  48586. configurable: true
  48587. });
  48588. Xbox360Pad.prototype.update = function () {
  48589. _super.prototype.update.call(this);
  48590. if (this._isXboxOnePad) {
  48591. this.buttonA = this.browserGamepad.buttons[0].value;
  48592. this.buttonB = this.browserGamepad.buttons[1].value;
  48593. this.buttonX = this.browserGamepad.buttons[2].value;
  48594. this.buttonY = this.browserGamepad.buttons[3].value;
  48595. this.buttonLB = this.browserGamepad.buttons[4].value;
  48596. this.buttonRB = this.browserGamepad.buttons[5].value;
  48597. this.leftTrigger = this.browserGamepad.axes[2];
  48598. this.rightTrigger = this.browserGamepad.axes[5];
  48599. this.buttonBack = this.browserGamepad.buttons[9].value;
  48600. this.buttonStart = this.browserGamepad.buttons[8].value;
  48601. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  48602. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  48603. this.dPadUp = this.browserGamepad.buttons[11].value;
  48604. this.dPadDown = this.browserGamepad.buttons[12].value;
  48605. this.dPadLeft = this.browserGamepad.buttons[13].value;
  48606. this.dPadRight = this.browserGamepad.buttons[14].value;
  48607. }
  48608. else {
  48609. this.buttonA = this.browserGamepad.buttons[0].value;
  48610. this.buttonB = this.browserGamepad.buttons[1].value;
  48611. this.buttonX = this.browserGamepad.buttons[2].value;
  48612. this.buttonY = this.browserGamepad.buttons[3].value;
  48613. this.buttonLB = this.browserGamepad.buttons[4].value;
  48614. this.buttonRB = this.browserGamepad.buttons[5].value;
  48615. this.leftTrigger = this.browserGamepad.buttons[6].value;
  48616. this.rightTrigger = this.browserGamepad.buttons[7].value;
  48617. this.buttonBack = this.browserGamepad.buttons[8].value;
  48618. this.buttonStart = this.browserGamepad.buttons[9].value;
  48619. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  48620. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  48621. this.dPadUp = this.browserGamepad.buttons[12].value;
  48622. this.dPadDown = this.browserGamepad.buttons[13].value;
  48623. this.dPadLeft = this.browserGamepad.buttons[14].value;
  48624. this.dPadRight = this.browserGamepad.buttons[15].value;
  48625. }
  48626. };
  48627. return Xbox360Pad;
  48628. }(Gamepad));
  48629. BABYLON.Xbox360Pad = Xbox360Pad;
  48630. })(BABYLON || (BABYLON = {}));
  48631. //# sourceMappingURL=babylon.gamepads.js.map
  48632. var BABYLON;
  48633. (function (BABYLON) {
  48634. var PoseEnabledControllerType;
  48635. (function (PoseEnabledControllerType) {
  48636. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  48637. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  48638. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  48639. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  48640. var PoseEnabledControllerHelper = (function () {
  48641. function PoseEnabledControllerHelper() {
  48642. }
  48643. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  48644. // for now, only Oculus and Vive are supported
  48645. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  48646. return new OculusTouchController(vrGamepad);
  48647. }
  48648. else {
  48649. return new ViveController(vrGamepad);
  48650. }
  48651. };
  48652. return PoseEnabledControllerHelper;
  48653. }());
  48654. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  48655. var PoseEnabledController = (function (_super) {
  48656. __extends(PoseEnabledController, _super);
  48657. function PoseEnabledController(vrGamepad) {
  48658. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  48659. _this.vrGamepad = vrGamepad;
  48660. _this.deviceScaleFactor = 1;
  48661. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  48662. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  48663. _this.controllerType = PoseEnabledControllerType.GENERIC;
  48664. _this.position = BABYLON.Vector3.Zero();
  48665. _this.rotationQuaternion = new BABYLON.Quaternion();
  48666. _this.devicePosition = BABYLON.Vector3.Zero();
  48667. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  48668. _this._calculatedPosition = BABYLON.Vector3.Zero();
  48669. _this._calculatedRotation = new BABYLON.Quaternion();
  48670. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  48671. return _this;
  48672. }
  48673. PoseEnabledController.prototype.update = function () {
  48674. _super.prototype.update.call(this);
  48675. var pose = this.vrGamepad.pose;
  48676. this.updateFromDevice(pose);
  48677. if (this._mesh) {
  48678. this._mesh.position.copyFrom(this._calculatedPosition);
  48679. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  48680. }
  48681. };
  48682. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  48683. if (poseData) {
  48684. this.rawPose = poseData;
  48685. if (poseData.position) {
  48686. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  48687. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  48688. this.devicePosition.z *= -1;
  48689. }
  48690. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  48691. this._calculatedPosition.addInPlace(this.position);
  48692. }
  48693. if (poseData.orientation) {
  48694. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  48695. if (this._mesh) {
  48696. if (this._mesh.getScene().useRightHandedSystem) {
  48697. this.deviceRotationQuaternion.z *= -1;
  48698. this.deviceRotationQuaternion.w *= -1;
  48699. }
  48700. else {
  48701. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  48702. }
  48703. }
  48704. // if the camera is set, rotate to the camera's rotation
  48705. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  48706. }
  48707. }
  48708. };
  48709. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  48710. if (this._mesh) {
  48711. this._mesh.parent = undefined;
  48712. }
  48713. this._mesh = mesh;
  48714. if (this._poseControlledCamera) {
  48715. this._mesh.parent = this._poseControlledCamera;
  48716. }
  48717. if (!this._mesh.rotationQuaternion) {
  48718. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  48719. }
  48720. };
  48721. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  48722. this._poseControlledCamera = camera;
  48723. if (this._mesh) {
  48724. this._mesh.parent = this._poseControlledCamera;
  48725. }
  48726. };
  48727. PoseEnabledController.prototype.detachMesh = function () {
  48728. this._mesh = undefined;
  48729. };
  48730. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  48731. get: function () {
  48732. return this._mesh;
  48733. },
  48734. enumerable: true,
  48735. configurable: true
  48736. });
  48737. PoseEnabledController.prototype.getForwardRay = function (length) {
  48738. if (length === void 0) { length = 100; }
  48739. if (!this.mesh) {
  48740. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  48741. }
  48742. var m = this.mesh.getWorldMatrix();
  48743. var origin = m.getTranslation();
  48744. var forward = new BABYLON.Vector3(0, 0, -1);
  48745. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  48746. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  48747. return new BABYLON.Ray(origin, direction, length);
  48748. };
  48749. return PoseEnabledController;
  48750. }(BABYLON.Gamepad));
  48751. BABYLON.PoseEnabledController = PoseEnabledController;
  48752. var WebVRController = (function (_super) {
  48753. __extends(WebVRController, _super);
  48754. function WebVRController(vrGamepad) {
  48755. var _this = _super.call(this, vrGamepad) || this;
  48756. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  48757. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  48758. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  48759. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  48760. _this.onPadStateChangedObservable = new BABYLON.Observable();
  48761. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  48762. _this.pad = { x: 0, y: 0 };
  48763. // avoid GC, store state in a tmp object
  48764. _this._changes = {
  48765. pressChanged: false,
  48766. touchChanged: false,
  48767. valueChanged: false,
  48768. changed: false
  48769. };
  48770. _this._buttons = new Array(vrGamepad.buttons.length);
  48771. _this.hand = vrGamepad.hand;
  48772. return _this;
  48773. }
  48774. WebVRController.prototype.onButtonStateChange = function (callback) {
  48775. this._onButtonStateChange = callback;
  48776. };
  48777. WebVRController.prototype.update = function () {
  48778. _super.prototype.update.call(this);
  48779. for (var index = 0; index < this._buttons.length; index++) {
  48780. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  48781. }
  48782. ;
  48783. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  48784. this.pad.x = this.leftStick.x;
  48785. this.pad.y = this.leftStick.y;
  48786. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  48787. }
  48788. };
  48789. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  48790. if (!currentState) {
  48791. this._buttons[buttonIndex] = {
  48792. pressed: newState.pressed,
  48793. touched: newState.touched,
  48794. value: newState.value
  48795. };
  48796. return;
  48797. }
  48798. this._checkChanges(newState, currentState);
  48799. if (this._changes.changed) {
  48800. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  48801. this.handleButtonChange(buttonIndex, newState, this._changes);
  48802. }
  48803. this._buttons[buttonIndex].pressed = newState.pressed;
  48804. this._buttons[buttonIndex].touched = newState.touched;
  48805. // oculus triggers are never 0, thou not touched.
  48806. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  48807. };
  48808. WebVRController.prototype._checkChanges = function (newState, currentState) {
  48809. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  48810. this._changes.touchChanged = newState.touched !== currentState.touched;
  48811. this._changes.valueChanged = newState.value !== currentState.value;
  48812. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  48813. return this._changes;
  48814. };
  48815. return WebVRController;
  48816. }(PoseEnabledController));
  48817. BABYLON.WebVRController = WebVRController;
  48818. var OculusTouchController = (function (_super) {
  48819. __extends(OculusTouchController, _super);
  48820. function OculusTouchController(vrGamepad) {
  48821. var _this = _super.call(this, vrGamepad) || this;
  48822. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  48823. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  48824. _this.controllerType = PoseEnabledControllerType.OCULUS;
  48825. return _this;
  48826. }
  48827. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  48828. var _this = this;
  48829. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  48830. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  48831. /*
  48832. Parent Mesh name: oculus_touch_left
  48833. - body
  48834. - trigger
  48835. - thumbstick
  48836. - grip
  48837. - button_y
  48838. - button_x
  48839. - button_enter
  48840. */
  48841. _this._defaultModel = newMeshes[1];
  48842. if (meshLoaded) {
  48843. meshLoaded(_this._defaultModel);
  48844. }
  48845. _this.attachToMesh(_this._defaultModel);
  48846. });
  48847. };
  48848. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  48849. // helper getters for left and right hand.
  48850. get: function () {
  48851. if (this.hand === 'right') {
  48852. return this.onMainButtonStateChangedObservable;
  48853. }
  48854. else {
  48855. throw new Error('No A button on left hand');
  48856. }
  48857. },
  48858. enumerable: true,
  48859. configurable: true
  48860. });
  48861. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  48862. get: function () {
  48863. if (this.hand === 'right') {
  48864. return this.onSecondaryButtonStateChangedObservable;
  48865. }
  48866. else {
  48867. throw new Error('No B button on left hand');
  48868. }
  48869. },
  48870. enumerable: true,
  48871. configurable: true
  48872. });
  48873. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  48874. get: function () {
  48875. if (this.hand === 'left') {
  48876. return this.onMainButtonStateChangedObservable;
  48877. }
  48878. else {
  48879. throw new Error('No X button on right hand');
  48880. }
  48881. },
  48882. enumerable: true,
  48883. configurable: true
  48884. });
  48885. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  48886. get: function () {
  48887. if (this.hand === 'left') {
  48888. return this.onSecondaryButtonStateChangedObservable;
  48889. }
  48890. else {
  48891. throw new Error('No Y button on right hand');
  48892. }
  48893. },
  48894. enumerable: true,
  48895. configurable: true
  48896. });
  48897. /*
  48898. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  48899. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  48900. 2) secondary trigger (same)
  48901. 3) A (right) X (left), touch, pressed = value
  48902. 4) B / Y
  48903. 5) thumb rest
  48904. */
  48905. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  48906. var notifyObject = state; //{ state: state, changes: changes };
  48907. var triggerDirection = this.hand === 'right' ? -1 : 1;
  48908. switch (buttonIdx) {
  48909. case 0:
  48910. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  48911. return;
  48912. case 1:
  48913. if (this._defaultModel) {
  48914. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  48915. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  48916. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  48917. }
  48918. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  48919. return;
  48920. case 2:
  48921. if (this._defaultModel) {
  48922. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  48923. }
  48924. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  48925. return;
  48926. case 3:
  48927. if (this._defaultModel) {
  48928. if (notifyObject.pressed) {
  48929. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  48930. }
  48931. else {
  48932. (this._defaultModel.getChildren()[1]).position.y = 0;
  48933. }
  48934. }
  48935. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  48936. return;
  48937. case 4:
  48938. if (this._defaultModel) {
  48939. if (notifyObject.pressed) {
  48940. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  48941. }
  48942. else {
  48943. (this._defaultModel.getChildren()[2]).position.y = 0;
  48944. }
  48945. }
  48946. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  48947. return;
  48948. case 5:
  48949. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  48950. return;
  48951. }
  48952. };
  48953. return OculusTouchController;
  48954. }(WebVRController));
  48955. BABYLON.OculusTouchController = OculusTouchController;
  48956. var ViveController = (function (_super) {
  48957. __extends(ViveController, _super);
  48958. function ViveController(vrGamepad) {
  48959. var _this = _super.call(this, vrGamepad) || this;
  48960. _this.controllerType = PoseEnabledControllerType.VIVE;
  48961. return _this;
  48962. }
  48963. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  48964. var _this = this;
  48965. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  48966. /*
  48967. Parent Mesh name: ViveWand
  48968. - body
  48969. - r_gripper
  48970. - l_gripper
  48971. - menu_button
  48972. - system_button
  48973. - trackpad
  48974. - trigger
  48975. - LED
  48976. */
  48977. _this._defaultModel = newMeshes[1];
  48978. if (meshLoaded) {
  48979. meshLoaded(_this._defaultModel);
  48980. }
  48981. _this.attachToMesh(_this._defaultModel);
  48982. });
  48983. };
  48984. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  48985. get: function () {
  48986. return this.onMainButtonStateChangedObservable;
  48987. },
  48988. enumerable: true,
  48989. configurable: true
  48990. });
  48991. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  48992. get: function () {
  48993. return this.onMainButtonStateChangedObservable;
  48994. },
  48995. enumerable: true,
  48996. configurable: true
  48997. });
  48998. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  48999. get: function () {
  49000. return this.onSecondaryButtonStateChangedObservable;
  49001. },
  49002. enumerable: true,
  49003. configurable: true
  49004. });
  49005. /**
  49006. * Vive mapping:
  49007. * 0: touchpad
  49008. * 1: trigger
  49009. * 2: left AND right buttons
  49010. * 3: menu button
  49011. */
  49012. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  49013. var notifyObject = state; //{ state: state, changes: changes };
  49014. switch (buttonIdx) {
  49015. case 0:
  49016. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  49017. return;
  49018. case 1:
  49019. if (this._defaultModel) {
  49020. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  49021. }
  49022. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  49023. return;
  49024. case 2:
  49025. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  49026. return;
  49027. case 3:
  49028. if (this._defaultModel) {
  49029. if (notifyObject.pressed) {
  49030. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  49031. }
  49032. else {
  49033. (this._defaultModel.getChildren()[2]).position.y = 0;
  49034. }
  49035. }
  49036. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  49037. return;
  49038. }
  49039. };
  49040. return ViveController;
  49041. }(WebVRController));
  49042. BABYLON.ViveController = ViveController;
  49043. })(BABYLON || (BABYLON = {}));
  49044. //# sourceMappingURL=babylon.extendedGamepad.js.map
  49045. /// <reference path="babylon.targetCamera.ts" />
  49046. var BABYLON;
  49047. (function (BABYLON) {
  49048. var FollowCamera = (function (_super) {
  49049. __extends(FollowCamera, _super);
  49050. function FollowCamera(name, position, scene, lockedTarget) {
  49051. var _this = _super.call(this, name, position, scene) || this;
  49052. _this.radius = 12;
  49053. _this.rotationOffset = 0;
  49054. _this.heightOffset = 4;
  49055. _this.cameraAcceleration = 0.05;
  49056. _this.maxCameraSpeed = 20;
  49057. _this.lockedTarget = lockedTarget;
  49058. return _this;
  49059. }
  49060. FollowCamera.prototype.getRadians = function (degrees) {
  49061. return degrees * Math.PI / 180;
  49062. };
  49063. FollowCamera.prototype.follow = function (cameraTarget) {
  49064. if (!cameraTarget)
  49065. return;
  49066. var yRotation;
  49067. if (cameraTarget.rotationQuaternion) {
  49068. var rotMatrix = new BABYLON.Matrix();
  49069. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  49070. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  49071. }
  49072. else {
  49073. yRotation = cameraTarget.rotation.y;
  49074. }
  49075. var radians = this.getRadians(this.rotationOffset) + yRotation;
  49076. var targetPosition = cameraTarget.getAbsolutePosition();
  49077. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  49078. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  49079. var dx = targetX - this.position.x;
  49080. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  49081. var dz = (targetZ) - this.position.z;
  49082. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  49083. var vy = dy * this.cameraAcceleration;
  49084. var vz = dz * this.cameraAcceleration * 2;
  49085. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  49086. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49087. }
  49088. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  49089. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49090. }
  49091. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  49092. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49093. }
  49094. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  49095. this.setTarget(targetPosition);
  49096. };
  49097. FollowCamera.prototype._checkInputs = function () {
  49098. _super.prototype._checkInputs.call(this);
  49099. this.follow(this.lockedTarget);
  49100. };
  49101. FollowCamera.prototype.getClassName = function () {
  49102. return "FollowCamera";
  49103. };
  49104. return FollowCamera;
  49105. }(BABYLON.TargetCamera));
  49106. __decorate([
  49107. BABYLON.serialize()
  49108. ], FollowCamera.prototype, "radius", void 0);
  49109. __decorate([
  49110. BABYLON.serialize()
  49111. ], FollowCamera.prototype, "rotationOffset", void 0);
  49112. __decorate([
  49113. BABYLON.serialize()
  49114. ], FollowCamera.prototype, "heightOffset", void 0);
  49115. __decorate([
  49116. BABYLON.serialize()
  49117. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  49118. __decorate([
  49119. BABYLON.serialize()
  49120. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  49121. __decorate([
  49122. BABYLON.serializeAsMeshReference("lockedTargetId")
  49123. ], FollowCamera.prototype, "lockedTarget", void 0);
  49124. BABYLON.FollowCamera = FollowCamera;
  49125. var ArcFollowCamera = (function (_super) {
  49126. __extends(ArcFollowCamera, _super);
  49127. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  49128. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  49129. _this.alpha = alpha;
  49130. _this.beta = beta;
  49131. _this.radius = radius;
  49132. _this.target = target;
  49133. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  49134. _this.follow();
  49135. return _this;
  49136. }
  49137. ArcFollowCamera.prototype.follow = function () {
  49138. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  49139. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  49140. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  49141. var targetPosition = this.target.getAbsolutePosition();
  49142. this.position = targetPosition.add(this._cartesianCoordinates);
  49143. this.setTarget(targetPosition);
  49144. };
  49145. ArcFollowCamera.prototype._checkInputs = function () {
  49146. _super.prototype._checkInputs.call(this);
  49147. this.follow();
  49148. };
  49149. ArcFollowCamera.prototype.getClassName = function () {
  49150. return "ArcFollowCamera";
  49151. };
  49152. return ArcFollowCamera;
  49153. }(BABYLON.TargetCamera));
  49154. BABYLON.ArcFollowCamera = ArcFollowCamera;
  49155. })(BABYLON || (BABYLON = {}));
  49156. //# sourceMappingURL=babylon.followCamera.js.map
  49157. /// <reference path="babylon.touchCamera.ts" />
  49158. var BABYLON;
  49159. (function (BABYLON) {
  49160. // We're mainly based on the logic defined into the FreeCamera code
  49161. var UniversalCamera = (function (_super) {
  49162. __extends(UniversalCamera, _super);
  49163. //-- end properties for backward compatibility for inputs
  49164. function UniversalCamera(name, position, scene) {
  49165. var _this = _super.call(this, name, position, scene) || this;
  49166. _this.inputs.addGamepad();
  49167. return _this;
  49168. }
  49169. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  49170. //-- Begin properties for backward compatibility for inputs
  49171. get: function () {
  49172. var gamepad = this.inputs.attached["gamepad"];
  49173. if (gamepad)
  49174. return gamepad.gamepadAngularSensibility;
  49175. },
  49176. set: function (value) {
  49177. var gamepad = this.inputs.attached["gamepad"];
  49178. if (gamepad)
  49179. gamepad.gamepadAngularSensibility = value;
  49180. },
  49181. enumerable: true,
  49182. configurable: true
  49183. });
  49184. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  49185. get: function () {
  49186. var gamepad = this.inputs.attached["gamepad"];
  49187. if (gamepad)
  49188. return gamepad.gamepadMoveSensibility;
  49189. },
  49190. set: function (value) {
  49191. var gamepad = this.inputs.attached["gamepad"];
  49192. if (gamepad)
  49193. gamepad.gamepadMoveSensibility = value;
  49194. },
  49195. enumerable: true,
  49196. configurable: true
  49197. });
  49198. UniversalCamera.prototype.getClassName = function () {
  49199. return "UniversalCamera";
  49200. };
  49201. return UniversalCamera;
  49202. }(BABYLON.TouchCamera));
  49203. BABYLON.UniversalCamera = UniversalCamera;
  49204. })(BABYLON || (BABYLON = {}));
  49205. //# sourceMappingURL=babylon.universalCamera.js.map
  49206. /// <reference path="babylon.universalCamera.ts" />
  49207. var BABYLON;
  49208. (function (BABYLON) {
  49209. // We're mainly based on the logic defined into the FreeCamera code
  49210. var GamepadCamera = (function (_super) {
  49211. __extends(GamepadCamera, _super);
  49212. //-- end properties for backward compatibility for inputs
  49213. function GamepadCamera(name, position, scene) {
  49214. return _super.call(this, name, position, scene) || this;
  49215. }
  49216. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  49217. //-- Begin properties for backward compatibility for inputs
  49218. get: function () {
  49219. var gamepad = this.inputs.attached["gamepad"];
  49220. if (gamepad)
  49221. return gamepad.gamepadAngularSensibility;
  49222. },
  49223. set: function (value) {
  49224. var gamepad = this.inputs.attached["gamepad"];
  49225. if (gamepad)
  49226. gamepad.gamepadAngularSensibility = value;
  49227. },
  49228. enumerable: true,
  49229. configurable: true
  49230. });
  49231. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  49232. get: function () {
  49233. var gamepad = this.inputs.attached["gamepad"];
  49234. if (gamepad)
  49235. return gamepad.gamepadMoveSensibility;
  49236. },
  49237. set: function (value) {
  49238. var gamepad = this.inputs.attached["gamepad"];
  49239. if (gamepad)
  49240. gamepad.gamepadMoveSensibility = value;
  49241. },
  49242. enumerable: true,
  49243. configurable: true
  49244. });
  49245. GamepadCamera.prototype.getClassName = function () {
  49246. return "GamepadCamera";
  49247. };
  49248. return GamepadCamera;
  49249. }(BABYLON.UniversalCamera));
  49250. BABYLON.GamepadCamera = GamepadCamera;
  49251. })(BABYLON || (BABYLON = {}));
  49252. //# sourceMappingURL=babylon.gamepadCamera.js.map
  49253. var BABYLON;
  49254. (function (BABYLON) {
  49255. var PostProcessRenderPipelineManager = (function () {
  49256. function PostProcessRenderPipelineManager() {
  49257. this._renderPipelines = {};
  49258. }
  49259. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  49260. this._renderPipelines[renderPipeline._name] = renderPipeline;
  49261. };
  49262. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  49263. var renderPipeline = this._renderPipelines[renderPipelineName];
  49264. if (!renderPipeline) {
  49265. return;
  49266. }
  49267. renderPipeline._attachCameras(cameras, unique);
  49268. };
  49269. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  49270. var renderPipeline = this._renderPipelines[renderPipelineName];
  49271. if (!renderPipeline) {
  49272. return;
  49273. }
  49274. renderPipeline._detachCameras(cameras);
  49275. };
  49276. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  49277. var renderPipeline = this._renderPipelines[renderPipelineName];
  49278. if (!renderPipeline) {
  49279. return;
  49280. }
  49281. renderPipeline._enableEffect(renderEffectName, cameras);
  49282. };
  49283. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  49284. var renderPipeline = this._renderPipelines[renderPipelineName];
  49285. if (!renderPipeline) {
  49286. return;
  49287. }
  49288. renderPipeline._disableEffect(renderEffectName, cameras);
  49289. };
  49290. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  49291. var renderPipeline = this._renderPipelines[renderPipelineName];
  49292. if (!renderPipeline) {
  49293. return;
  49294. }
  49295. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  49296. };
  49297. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  49298. var renderPipeline = this._renderPipelines[renderPipelineName];
  49299. if (!renderPipeline) {
  49300. return;
  49301. }
  49302. renderPipeline._disableDisplayOnlyPass(cameras);
  49303. };
  49304. PostProcessRenderPipelineManager.prototype.update = function () {
  49305. for (var renderPipelineName in this._renderPipelines) {
  49306. var pipeline = this._renderPipelines[renderPipelineName];
  49307. if (!pipeline.isSupported) {
  49308. pipeline.dispose();
  49309. delete this._renderPipelines[renderPipelineName];
  49310. }
  49311. else {
  49312. pipeline._update();
  49313. }
  49314. }
  49315. };
  49316. return PostProcessRenderPipelineManager;
  49317. }());
  49318. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  49319. })(BABYLON || (BABYLON = {}));
  49320. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  49321. var BABYLON;
  49322. (function (BABYLON) {
  49323. var PostProcessRenderPass = (function () {
  49324. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  49325. this._enabled = true;
  49326. this._refCount = 0;
  49327. this._name = name;
  49328. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  49329. this.setRenderList(renderList);
  49330. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  49331. this._renderTexture.onAfterRenderObservable.add(afterRender);
  49332. this._scene = scene;
  49333. this._renderList = renderList;
  49334. }
  49335. // private
  49336. PostProcessRenderPass.prototype._incRefCount = function () {
  49337. if (this._refCount === 0) {
  49338. this._scene.customRenderTargets.push(this._renderTexture);
  49339. }
  49340. return ++this._refCount;
  49341. };
  49342. PostProcessRenderPass.prototype._decRefCount = function () {
  49343. this._refCount--;
  49344. if (this._refCount <= 0) {
  49345. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  49346. }
  49347. return this._refCount;
  49348. };
  49349. PostProcessRenderPass.prototype._update = function () {
  49350. this.setRenderList(this._renderList);
  49351. };
  49352. // public
  49353. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  49354. this._renderTexture.renderList = renderList;
  49355. };
  49356. PostProcessRenderPass.prototype.getRenderTexture = function () {
  49357. return this._renderTexture;
  49358. };
  49359. return PostProcessRenderPass;
  49360. }());
  49361. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  49362. })(BABYLON || (BABYLON = {}));
  49363. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  49364. var BABYLON;
  49365. (function (BABYLON) {
  49366. var PostProcessRenderEffect = (function () {
  49367. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  49368. this._engine = engine;
  49369. this._name = name;
  49370. this._singleInstance = singleInstance || true;
  49371. this._getPostProcess = getPostProcess;
  49372. this._cameras = [];
  49373. this._indicesForCamera = [];
  49374. this._postProcesses = {};
  49375. this._renderPasses = {};
  49376. this._renderEffectAsPasses = {};
  49377. }
  49378. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  49379. get: function () {
  49380. for (var index in this._postProcesses) {
  49381. if (!this._postProcesses[index].isSupported) {
  49382. return false;
  49383. }
  49384. }
  49385. return true;
  49386. },
  49387. enumerable: true,
  49388. configurable: true
  49389. });
  49390. PostProcessRenderEffect.prototype._update = function () {
  49391. for (var renderPassName in this._renderPasses) {
  49392. this._renderPasses[renderPassName]._update();
  49393. }
  49394. };
  49395. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  49396. this._renderPasses[renderPass._name] = renderPass;
  49397. this._linkParameters();
  49398. };
  49399. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  49400. delete this._renderPasses[renderPass._name];
  49401. this._linkParameters();
  49402. };
  49403. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  49404. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  49405. this._linkParameters();
  49406. };
  49407. PostProcessRenderEffect.prototype.getPass = function (passName) {
  49408. for (var renderPassName in this._renderPasses) {
  49409. if (renderPassName === passName) {
  49410. return this._renderPasses[passName];
  49411. }
  49412. }
  49413. };
  49414. PostProcessRenderEffect.prototype.emptyPasses = function () {
  49415. this._renderPasses = {};
  49416. this._linkParameters();
  49417. };
  49418. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  49419. var cameraKey;
  49420. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49421. for (var i = 0; i < _cam.length; i++) {
  49422. var camera = _cam[i];
  49423. var cameraName = camera.name;
  49424. if (this._singleInstance) {
  49425. cameraKey = 0;
  49426. }
  49427. else {
  49428. cameraKey = cameraName;
  49429. }
  49430. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  49431. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  49432. if (!this._indicesForCamera[cameraName]) {
  49433. this._indicesForCamera[cameraName] = [];
  49434. }
  49435. this._indicesForCamera[cameraName].push(index);
  49436. if (this._cameras.indexOf(camera) === -1) {
  49437. this._cameras[cameraName] = camera;
  49438. }
  49439. for (var passName in this._renderPasses) {
  49440. this._renderPasses[passName]._incRefCount();
  49441. }
  49442. }
  49443. this._linkParameters();
  49444. };
  49445. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  49446. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49447. for (var i = 0; i < _cam.length; i++) {
  49448. var camera = _cam[i];
  49449. var cameraName = camera.name;
  49450. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  49451. var index = this._cameras.indexOf(cameraName);
  49452. this._indicesForCamera.splice(index, 1);
  49453. this._cameras.splice(index, 1);
  49454. for (var passName in this._renderPasses) {
  49455. this._renderPasses[passName]._decRefCount();
  49456. }
  49457. }
  49458. };
  49459. PostProcessRenderEffect.prototype._enable = function (cameras) {
  49460. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49461. for (var i = 0; i < _cam.length; i++) {
  49462. var camera = _cam[i];
  49463. var cameraName = camera.name;
  49464. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  49465. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  49466. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  49467. }
  49468. }
  49469. for (var passName in this._renderPasses) {
  49470. this._renderPasses[passName]._incRefCount();
  49471. }
  49472. }
  49473. };
  49474. PostProcessRenderEffect.prototype._disable = function (cameras) {
  49475. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49476. for (var i = 0; i < _cam.length; i++) {
  49477. var camera = _cam[i];
  49478. var cameraName = camera.Name;
  49479. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  49480. for (var passName in this._renderPasses) {
  49481. this._renderPasses[passName]._decRefCount();
  49482. }
  49483. }
  49484. };
  49485. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  49486. if (this._singleInstance) {
  49487. return this._postProcesses[0];
  49488. }
  49489. else {
  49490. return this._postProcesses[camera.name];
  49491. }
  49492. };
  49493. PostProcessRenderEffect.prototype._linkParameters = function () {
  49494. var _this = this;
  49495. for (var index in this._postProcesses) {
  49496. if (this.applyParameters) {
  49497. this.applyParameters(this._postProcesses[index]);
  49498. }
  49499. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  49500. _this._linkTextures(effect);
  49501. });
  49502. }
  49503. };
  49504. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  49505. for (var renderPassName in this._renderPasses) {
  49506. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  49507. }
  49508. for (var renderEffectName in this._renderEffectAsPasses) {
  49509. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  49510. }
  49511. };
  49512. return PostProcessRenderEffect;
  49513. }());
  49514. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  49515. })(BABYLON || (BABYLON = {}));
  49516. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  49517. var BABYLON;
  49518. (function (BABYLON) {
  49519. var PostProcessRenderPipeline = (function () {
  49520. function PostProcessRenderPipeline(engine, name) {
  49521. this._engine = engine;
  49522. this._name = name;
  49523. this._renderEffects = new Array();
  49524. this._renderEffectsForIsolatedPass = new Array();
  49525. this._cameras = [];
  49526. }
  49527. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  49528. get: function () {
  49529. for (var renderEffectName in this._renderEffects) {
  49530. if (!this._renderEffects[renderEffectName].isSupported) {
  49531. return false;
  49532. }
  49533. }
  49534. return true;
  49535. },
  49536. enumerable: true,
  49537. configurable: true
  49538. });
  49539. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  49540. this._renderEffects[renderEffect._name] = renderEffect;
  49541. };
  49542. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  49543. var renderEffects = this._renderEffects[renderEffectName];
  49544. if (!renderEffects) {
  49545. return;
  49546. }
  49547. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  49548. };
  49549. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  49550. var renderEffects = this._renderEffects[renderEffectName];
  49551. if (!renderEffects) {
  49552. return;
  49553. }
  49554. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  49555. };
  49556. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  49557. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49558. var indicesToDelete = [];
  49559. var i;
  49560. for (i = 0; i < _cam.length; i++) {
  49561. var camera = _cam[i];
  49562. var cameraName = camera.name;
  49563. if (this._cameras.indexOf(camera) === -1) {
  49564. this._cameras[cameraName] = camera;
  49565. }
  49566. else if (unique) {
  49567. indicesToDelete.push(i);
  49568. }
  49569. }
  49570. for (i = 0; i < indicesToDelete.length; i++) {
  49571. cameras.splice(indicesToDelete[i], 1);
  49572. }
  49573. for (var renderEffectName in this._renderEffects) {
  49574. this._renderEffects[renderEffectName]._attachCameras(_cam);
  49575. }
  49576. };
  49577. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  49578. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49579. for (var renderEffectName in this._renderEffects) {
  49580. this._renderEffects[renderEffectName]._detachCameras(_cam);
  49581. }
  49582. for (var i = 0; i < _cam.length; i++) {
  49583. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  49584. }
  49585. };
  49586. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  49587. var _this = this;
  49588. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49589. var pass = null;
  49590. var renderEffectName;
  49591. for (renderEffectName in this._renderEffects) {
  49592. pass = this._renderEffects[renderEffectName].getPass(passName);
  49593. if (pass != null) {
  49594. break;
  49595. }
  49596. }
  49597. if (pass === null) {
  49598. return;
  49599. }
  49600. for (renderEffectName in this._renderEffects) {
  49601. this._renderEffects[renderEffectName]._disable(_cam);
  49602. }
  49603. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  49604. for (var i = 0; i < _cam.length; i++) {
  49605. var camera = _cam[i];
  49606. var cameraName = camera.name;
  49607. 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); });
  49608. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  49609. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  49610. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  49611. }
  49612. };
  49613. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  49614. var _this = this;
  49615. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49616. for (var i = 0; i < _cam.length; i++) {
  49617. var camera = _cam[i];
  49618. var cameraName = camera.name;
  49619. 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); });
  49620. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  49621. }
  49622. for (var renderEffectName in this._renderEffects) {
  49623. this._renderEffects[renderEffectName]._enable(_cam);
  49624. }
  49625. };
  49626. PostProcessRenderPipeline.prototype._update = function () {
  49627. for (var renderEffectName in this._renderEffects) {
  49628. this._renderEffects[renderEffectName]._update();
  49629. }
  49630. for (var i = 0; i < this._cameras.length; i++) {
  49631. var cameraName = this._cameras[i].name;
  49632. if (this._renderEffectsForIsolatedPass[cameraName]) {
  49633. this._renderEffectsForIsolatedPass[cameraName]._update();
  49634. }
  49635. }
  49636. };
  49637. PostProcessRenderPipeline.prototype._reset = function () {
  49638. this._renderEffects = new Array();
  49639. this._renderEffectsForIsolatedPass = new Array();
  49640. };
  49641. PostProcessRenderPipeline.prototype.dispose = function () {
  49642. // Must be implemented by children
  49643. };
  49644. return PostProcessRenderPipeline;
  49645. }());
  49646. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  49647. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  49648. __decorate([
  49649. BABYLON.serialize()
  49650. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  49651. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  49652. })(BABYLON || (BABYLON = {}));
  49653. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  49654. var BABYLON;
  49655. (function (BABYLON) {
  49656. var DepthRenderer = (function () {
  49657. function DepthRenderer(scene, type) {
  49658. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  49659. var _this = this;
  49660. this._viewMatrix = BABYLON.Matrix.Zero();
  49661. this._projectionMatrix = BABYLON.Matrix.Zero();
  49662. this._transformMatrix = BABYLON.Matrix.Zero();
  49663. this._worldViewProjection = BABYLON.Matrix.Zero();
  49664. this._scene = scene;
  49665. var engine = scene.getEngine();
  49666. // Render target
  49667. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  49668. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49669. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49670. this._depthMap.refreshRate = 1;
  49671. this._depthMap.renderParticles = false;
  49672. this._depthMap.renderList = null;
  49673. // set default depth value to 1.0 (far away)
  49674. this._depthMap.onClearObservable.add(function (engine) {
  49675. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  49676. });
  49677. // Custom render function
  49678. var renderSubMesh = function (subMesh) {
  49679. var mesh = subMesh.getRenderingMesh();
  49680. var scene = _this._scene;
  49681. var engine = scene.getEngine();
  49682. // Culling
  49683. engine.setState(subMesh.getMaterial().backFaceCulling);
  49684. // Managing instances
  49685. var batch = mesh._getInstancesRenderList(subMesh._id);
  49686. if (batch.mustReturn) {
  49687. return;
  49688. }
  49689. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  49690. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  49691. engine.enableEffect(_this._effect);
  49692. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  49693. var material = subMesh.getMaterial();
  49694. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  49695. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  49696. // Alpha test
  49697. if (material && material.needAlphaTesting()) {
  49698. var alphaTexture = material.getAlphaTestTexture();
  49699. _this._effect.setTexture("diffuseSampler", alphaTexture);
  49700. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  49701. }
  49702. // Bones
  49703. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49704. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49705. }
  49706. // Draw
  49707. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  49708. }
  49709. };
  49710. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  49711. var index;
  49712. for (index = 0; index < opaqueSubMeshes.length; index++) {
  49713. renderSubMesh(opaqueSubMeshes.data[index]);
  49714. }
  49715. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  49716. renderSubMesh(alphaTestSubMeshes.data[index]);
  49717. }
  49718. };
  49719. }
  49720. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  49721. var material = subMesh.getMaterial();
  49722. if (material.disableDepthWrite) {
  49723. return false;
  49724. }
  49725. var defines = [];
  49726. var attribs = [BABYLON.VertexBuffer.PositionKind];
  49727. var mesh = subMesh.getMesh();
  49728. var scene = mesh.getScene();
  49729. // Alpha test
  49730. if (material && material.needAlphaTesting()) {
  49731. defines.push("#define ALPHATEST");
  49732. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49733. attribs.push(BABYLON.VertexBuffer.UVKind);
  49734. defines.push("#define UV1");
  49735. }
  49736. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49737. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49738. defines.push("#define UV2");
  49739. }
  49740. }
  49741. // Bones
  49742. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49743. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49744. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49745. if (mesh.numBoneInfluencers > 4) {
  49746. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49747. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49748. }
  49749. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49750. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49751. }
  49752. else {
  49753. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49754. }
  49755. // Instances
  49756. if (useInstances) {
  49757. defines.push("#define INSTANCES");
  49758. attribs.push("world0");
  49759. attribs.push("world1");
  49760. attribs.push("world2");
  49761. attribs.push("world3");
  49762. }
  49763. // Get correct effect
  49764. var join = defines.join("\n");
  49765. if (this._cachedDefines !== join) {
  49766. this._cachedDefines = join;
  49767. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  49768. }
  49769. return this._effect.isReady();
  49770. };
  49771. DepthRenderer.prototype.getDepthMap = function () {
  49772. return this._depthMap;
  49773. };
  49774. // Methods
  49775. DepthRenderer.prototype.dispose = function () {
  49776. this._depthMap.dispose();
  49777. };
  49778. return DepthRenderer;
  49779. }());
  49780. BABYLON.DepthRenderer = DepthRenderer;
  49781. })(BABYLON || (BABYLON = {}));
  49782. //# sourceMappingURL=babylon.depthRenderer.js.map
  49783. var BABYLON;
  49784. (function (BABYLON) {
  49785. var SSAORenderingPipeline = (function (_super) {
  49786. __extends(SSAORenderingPipeline, _super);
  49787. /**
  49788. * @constructor
  49789. * @param {string} name - The rendering pipeline name
  49790. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49791. * @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 }
  49792. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49793. */
  49794. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  49795. var _this = _super.call(this, scene.getEngine(), name) || this;
  49796. // Members
  49797. /**
  49798. * The PassPostProcess id in the pipeline that contains the original scene color
  49799. * @type {string}
  49800. */
  49801. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  49802. /**
  49803. * The SSAO PostProcess id in the pipeline
  49804. * @type {string}
  49805. */
  49806. _this.SSAORenderEffect = "SSAORenderEffect";
  49807. /**
  49808. * The horizontal blur PostProcess id in the pipeline
  49809. * @type {string}
  49810. */
  49811. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  49812. /**
  49813. * The vertical blur PostProcess id in the pipeline
  49814. * @type {string}
  49815. */
  49816. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  49817. /**
  49818. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  49819. * @type {string}
  49820. */
  49821. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  49822. /**
  49823. * The output strength of the SSAO post-process. Default value is 1.0.
  49824. * @type {number}
  49825. */
  49826. _this.totalStrength = 1.0;
  49827. /**
  49828. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  49829. * @type {number}
  49830. */
  49831. _this.radius = 0.0001;
  49832. /**
  49833. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  49834. * Must not be equal to fallOff and superior to fallOff.
  49835. * Default value is 0.975
  49836. * @type {number}
  49837. */
  49838. _this.area = 0.0075;
  49839. /**
  49840. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  49841. * Must not be equal to area and inferior to area.
  49842. * Default value is 0.0
  49843. * @type {number}
  49844. */
  49845. _this.fallOff = 0.000001;
  49846. /**
  49847. * The base color of the SSAO post-process
  49848. * The final result is "base + ssao" between [0, 1]
  49849. * @type {number}
  49850. */
  49851. _this.base = 0.5;
  49852. _this._firstUpdate = true;
  49853. _this._scene = scene;
  49854. // Set up assets
  49855. _this._createRandomTexture();
  49856. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  49857. var ssaoRatio = ratio.ssaoRatio || ratio;
  49858. var combineRatio = ratio.combineRatio || ratio;
  49859. _this._ratio = {
  49860. ssaoRatio: ssaoRatio,
  49861. combineRatio: combineRatio
  49862. };
  49863. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49864. _this._createSSAOPostProcess(ssaoRatio);
  49865. _this._createBlurPostProcess(ssaoRatio);
  49866. _this._createSSAOCombinePostProcess(combineRatio);
  49867. // Set up pipeline
  49868. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  49869. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  49870. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  49871. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  49872. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  49873. // Finish
  49874. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49875. if (cameras)
  49876. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49877. return _this;
  49878. }
  49879. // Public Methods
  49880. /**
  49881. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  49882. */
  49883. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  49884. if (disableDepthRender === void 0) { disableDepthRender = false; }
  49885. for (var i = 0; i < this._scene.cameras.length; i++) {
  49886. var camera = this._scene.cameras[i];
  49887. this._originalColorPostProcess.dispose(camera);
  49888. this._ssaoPostProcess.dispose(camera);
  49889. this._blurHPostProcess.dispose(camera);
  49890. this._blurVPostProcess.dispose(camera);
  49891. this._ssaoCombinePostProcess.dispose(camera);
  49892. }
  49893. this._randomTexture.dispose();
  49894. if (disableDepthRender)
  49895. this._scene.disableDepthRenderer();
  49896. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49897. _super.prototype.dispose.call(this);
  49898. };
  49899. // Private Methods
  49900. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  49901. var _this = this;
  49902. /*
  49903. var samplerOffsets = [
  49904. -8.0, -6.0, -4.0, -2.0,
  49905. 0.0,
  49906. 2.0, 4.0, 6.0, 8.0
  49907. ];
  49908. */
  49909. var samples = 16;
  49910. var samplerOffsets = [];
  49911. for (var i = -8; i < 8; i++) {
  49912. samplerOffsets.push(i * 2);
  49913. }
  49914. 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");
  49915. this._blurHPostProcess.onApply = function (effect) {
  49916. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  49917. effect.setTexture("depthSampler", _this._depthTexture);
  49918. if (_this._firstUpdate) {
  49919. effect.setArray("samplerOffsets", samplerOffsets);
  49920. }
  49921. };
  49922. 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");
  49923. this._blurVPostProcess.onApply = function (effect) {
  49924. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  49925. effect.setTexture("depthSampler", _this._depthTexture);
  49926. if (_this._firstUpdate) {
  49927. effect.setArray("samplerOffsets", samplerOffsets);
  49928. _this._firstUpdate = false;
  49929. }
  49930. };
  49931. };
  49932. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  49933. var _this = this;
  49934. var numSamples = 16;
  49935. var sampleSphere = [
  49936. 0.5381, 0.1856, -0.4319,
  49937. 0.1379, 0.2486, 0.4430,
  49938. 0.3371, 0.5679, -0.0057,
  49939. -0.6999, -0.0451, -0.0019,
  49940. 0.0689, -0.1598, -0.8547,
  49941. 0.0560, 0.0069, -0.1843,
  49942. -0.0146, 0.1402, 0.0762,
  49943. 0.0100, -0.1924, -0.0344,
  49944. -0.3577, -0.5301, -0.4358,
  49945. -0.3169, 0.1063, 0.0158,
  49946. 0.0103, -0.5869, 0.0046,
  49947. -0.0897, -0.4940, 0.3287,
  49948. 0.7119, -0.0154, -0.0918,
  49949. -0.0533, 0.0596, -0.5411,
  49950. 0.0352, -0.0631, 0.5460,
  49951. -0.4776, 0.2847, -0.0271
  49952. ];
  49953. var samplesFactor = 1.0 / numSamples;
  49954. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  49955. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  49956. "area", "fallOff", "base", "range", "viewport"
  49957. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  49958. var viewport = new BABYLON.Vector2(0, 0);
  49959. this._ssaoPostProcess.onApply = function (effect) {
  49960. if (_this._firstUpdate) {
  49961. effect.setArray3("sampleSphere", sampleSphere);
  49962. effect.setFloat("samplesFactor", samplesFactor);
  49963. effect.setFloat("randTextureTiles", 4.0);
  49964. }
  49965. effect.setFloat("totalStrength", _this.totalStrength);
  49966. effect.setFloat("radius", _this.radius);
  49967. effect.setFloat("area", _this.area);
  49968. effect.setFloat("fallOff", _this.fallOff);
  49969. effect.setFloat("base", _this.base);
  49970. effect.setTexture("textureSampler", _this._depthTexture);
  49971. effect.setTexture("randomSampler", _this._randomTexture);
  49972. };
  49973. };
  49974. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  49975. var _this = this;
  49976. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49977. this._ssaoCombinePostProcess.onApply = function (effect) {
  49978. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49979. };
  49980. };
  49981. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  49982. var size = 512;
  49983. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49984. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49985. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49986. var context = this._randomTexture.getContext();
  49987. var rand = function (min, max) {
  49988. return Math.random() * (max - min) + min;
  49989. };
  49990. var randVector = BABYLON.Vector3.Zero();
  49991. for (var x = 0; x < size; x++) {
  49992. for (var y = 0; y < size; y++) {
  49993. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  49994. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  49995. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  49996. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49997. context.fillRect(x, y, 1, 1);
  49998. }
  49999. }
  50000. this._randomTexture.update(false);
  50001. };
  50002. return SSAORenderingPipeline;
  50003. }(BABYLON.PostProcessRenderPipeline));
  50004. __decorate([
  50005. BABYLON.serialize()
  50006. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  50007. __decorate([
  50008. BABYLON.serialize()
  50009. ], SSAORenderingPipeline.prototype, "radius", void 0);
  50010. __decorate([
  50011. BABYLON.serialize()
  50012. ], SSAORenderingPipeline.prototype, "area", void 0);
  50013. __decorate([
  50014. BABYLON.serialize()
  50015. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  50016. __decorate([
  50017. BABYLON.serialize()
  50018. ], SSAORenderingPipeline.prototype, "base", void 0);
  50019. __decorate([
  50020. BABYLON.serialize()
  50021. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  50022. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  50023. })(BABYLON || (BABYLON = {}));
  50024. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  50025. var BABYLON;
  50026. (function (BABYLON) {
  50027. var SSAO2RenderingPipeline = (function (_super) {
  50028. __extends(SSAO2RenderingPipeline, _super);
  50029. /**
  50030. * @constructor
  50031. * @param {string} name - The rendering pipeline name
  50032. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50033. * @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 }
  50034. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50035. */
  50036. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  50037. var _this = _super.call(this, scene.getEngine(), name) || this;
  50038. // Members
  50039. /**
  50040. * The PassPostProcess id in the pipeline that contains the original scene color
  50041. * @type {string}
  50042. */
  50043. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  50044. /**
  50045. * The SSAO PostProcess id in the pipeline
  50046. * @type {string}
  50047. */
  50048. _this.SSAORenderEffect = "SSAORenderEffect";
  50049. /**
  50050. * The horizontal blur PostProcess id in the pipeline
  50051. * @type {string}
  50052. */
  50053. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  50054. /**
  50055. * The vertical blur PostProcess id in the pipeline
  50056. * @type {string}
  50057. */
  50058. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  50059. /**
  50060. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  50061. * @type {string}
  50062. */
  50063. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  50064. /**
  50065. * The output strength of the SSAO post-process. Default value is 1.0.
  50066. * @type {number}
  50067. */
  50068. _this.totalStrength = 1.0;
  50069. /**
  50070. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  50071. * @type {number}
  50072. */
  50073. _this.maxZ = 100.0;
  50074. /**
  50075. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  50076. * @type {number}
  50077. */
  50078. _this.minZAspect = 0.2;
  50079. /**
  50080. * Number of samples used for the SSAO calculations. Default value is 8
  50081. * @type {number}
  50082. */
  50083. _this._samples = 8;
  50084. /**
  50085. * Are we using bilateral blur ?
  50086. * @type {boolean}
  50087. */
  50088. _this._expensiveBlur = true;
  50089. /**
  50090. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  50091. * @type {number}
  50092. */
  50093. _this.radius = 2.0;
  50094. /**
  50095. * The base color of the SSAO post-process
  50096. * The final result is "base + ssao" between [0, 1]
  50097. * @type {number}
  50098. */
  50099. _this.base = 0.1;
  50100. _this._firstUpdate = true;
  50101. _this._scene = scene;
  50102. if (!_this.isSupported) {
  50103. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  50104. return _this;
  50105. }
  50106. var ssaoRatio = ratio.ssaoRatio || ratio;
  50107. var blurRatio = ratio.blurRatio || ratio;
  50108. _this._ratio = {
  50109. ssaoRatio: ssaoRatio,
  50110. blurRatio: blurRatio
  50111. };
  50112. // Set up assets
  50113. _this._createRandomTexture();
  50114. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  50115. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  50116. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  50117. _this._createSSAOPostProcess(1.0);
  50118. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  50119. _this._createSSAOCombinePostProcess(blurRatio);
  50120. // Set up pipeline
  50121. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  50122. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  50123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  50124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  50125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  50126. // Finish
  50127. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50128. if (cameras)
  50129. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50130. return _this;
  50131. }
  50132. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  50133. get: function () {
  50134. return this._samples;
  50135. },
  50136. set: function (n) {
  50137. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  50138. this._samples = n;
  50139. this._sampleSphere = this._generateHemisphere();
  50140. this._firstUpdate = true;
  50141. },
  50142. enumerable: true,
  50143. configurable: true
  50144. });
  50145. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  50146. get: function () {
  50147. return this._expensiveBlur;
  50148. },
  50149. set: function (b) {
  50150. 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"]);
  50151. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  50152. this._expensiveBlur = b;
  50153. this._firstUpdate = true;
  50154. },
  50155. enumerable: true,
  50156. configurable: true
  50157. });
  50158. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  50159. /**
  50160. * Support test.
  50161. * @type {boolean}
  50162. */
  50163. get: function () {
  50164. var engine = BABYLON.Engine.LastCreatedEngine;
  50165. return engine.webGLVersion > 1;
  50166. },
  50167. enumerable: true,
  50168. configurable: true
  50169. });
  50170. // Public Methods
  50171. /**
  50172. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  50173. */
  50174. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  50175. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  50176. for (var i = 0; i < this._scene.cameras.length; i++) {
  50177. var camera = this._scene.cameras[i];
  50178. this._originalColorPostProcess.dispose(camera);
  50179. this._ssaoPostProcess.dispose(camera);
  50180. this._blurHPostProcess.dispose(camera);
  50181. this._blurVPostProcess.dispose(camera);
  50182. this._ssaoCombinePostProcess.dispose(camera);
  50183. }
  50184. this._randomTexture.dispose();
  50185. if (disableGeometryBufferRenderer)
  50186. this._scene.disableGeometryBufferRenderer();
  50187. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50188. _super.prototype.dispose.call(this);
  50189. };
  50190. // Private Methods
  50191. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  50192. var _this = this;
  50193. var samples = 16;
  50194. this._samplerOffsets = [];
  50195. var expensive = this.expensiveBlur;
  50196. for (var i = -8; i < 8; i++) {
  50197. this._samplerOffsets.push(i * 2 + 0.5);
  50198. }
  50199. 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");
  50200. this._blurHPostProcess.onApply = function (effect) {
  50201. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  50202. effect.setFloat("near", _this._scene.activeCamera.minZ);
  50203. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  50204. effect.setFloat("radius", _this.radius);
  50205. effect.setTexture("depthSampler", _this._depthTexture);
  50206. if (_this._firstUpdate) {
  50207. effect.setArray("samplerOffsets", _this._samplerOffsets);
  50208. }
  50209. };
  50210. 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");
  50211. this._blurVPostProcess.onApply = function (effect) {
  50212. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  50213. effect.setFloat("near", _this._scene.activeCamera.minZ);
  50214. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  50215. effect.setFloat("radius", _this.radius);
  50216. effect.setTexture("depthSampler", _this._depthTexture);
  50217. if (_this._firstUpdate) {
  50218. effect.setArray("samplerOffsets", _this._samplerOffsets);
  50219. _this._firstUpdate = false;
  50220. }
  50221. };
  50222. };
  50223. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  50224. var numSamples = this.samples;
  50225. var result = [];
  50226. var vector, scale;
  50227. var rand = function (min, max) {
  50228. return Math.random() * (max - min) + min;
  50229. };
  50230. var lerp = function (start, end, percent) {
  50231. return (start + percent * (end - start));
  50232. };
  50233. var i = 0;
  50234. var normal = new BABYLON.Vector3(0, 0, 1);
  50235. while (i < numSamples) {
  50236. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  50237. vector.normalize();
  50238. scale = i / numSamples;
  50239. scale = lerp(0.1, 1.0, scale * scale);
  50240. vector.scaleInPlace(scale);
  50241. result.push(vector.x, vector.y, vector.z);
  50242. i++;
  50243. }
  50244. return result;
  50245. };
  50246. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  50247. var _this = this;
  50248. var numSamples = this.samples;
  50249. this._sampleSphere = this._generateHemisphere();
  50250. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  50251. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  50252. "base", "range", "projection", "near", "far", "texelSize",
  50253. "xViewport", "yViewport", "maxZ", "minZAspect"
  50254. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  50255. this._ssaoPostProcess.onApply = function (effect) {
  50256. if (_this._firstUpdate) {
  50257. effect.setArray3("sampleSphere", _this._sampleSphere);
  50258. effect.setFloat("randTextureTiles", 4.0);
  50259. }
  50260. effect.setFloat("samplesFactor", 1 / _this.samples);
  50261. effect.setFloat("totalStrength", _this.totalStrength);
  50262. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  50263. effect.setFloat("radius", _this.radius);
  50264. effect.setFloat("maxZ", _this.maxZ);
  50265. effect.setFloat("minZAspect", _this.minZAspect);
  50266. effect.setFloat("base", _this.base);
  50267. effect.setFloat("near", _this._scene.activeCamera.minZ);
  50268. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  50269. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  50270. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  50271. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  50272. effect.setTexture("textureSampler", _this._depthTexture);
  50273. effect.setTexture("normalSampler", _this._normalTexture);
  50274. effect.setTexture("randomSampler", _this._randomTexture);
  50275. };
  50276. };
  50277. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  50278. var _this = this;
  50279. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50280. this._ssaoCombinePostProcess.onApply = function (effect) {
  50281. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  50282. };
  50283. };
  50284. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  50285. var size = 512;
  50286. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  50287. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50288. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50289. var context = this._randomTexture.getContext();
  50290. var rand = function (min, max) {
  50291. return Math.random() * (max - min) + min;
  50292. };
  50293. var randVector = BABYLON.Vector3.Zero();
  50294. for (var x = 0; x < size; x++) {
  50295. for (var y = 0; y < size; y++) {
  50296. randVector.x = rand(0.0, 1.0);
  50297. randVector.y = rand(0.0, 1.0);
  50298. randVector.z = 0.0;
  50299. randVector.normalize();
  50300. randVector.scaleInPlace(255);
  50301. randVector.x = Math.floor(randVector.x);
  50302. randVector.y = Math.floor(randVector.y);
  50303. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  50304. context.fillRect(x, y, 1, 1);
  50305. }
  50306. }
  50307. this._randomTexture.update(false);
  50308. };
  50309. return SSAO2RenderingPipeline;
  50310. }(BABYLON.PostProcessRenderPipeline));
  50311. __decorate([
  50312. BABYLON.serialize()
  50313. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  50314. __decorate([
  50315. BABYLON.serialize()
  50316. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  50317. __decorate([
  50318. BABYLON.serialize()
  50319. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  50320. __decorate([
  50321. BABYLON.serialize("samples")
  50322. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  50323. __decorate([
  50324. BABYLON.serialize("expensiveBlur")
  50325. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  50326. __decorate([
  50327. BABYLON.serialize()
  50328. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  50329. __decorate([
  50330. BABYLON.serialize()
  50331. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  50332. __decorate([
  50333. BABYLON.serialize()
  50334. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  50335. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  50336. })(BABYLON || (BABYLON = {}));
  50337. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  50338. // BABYLON.JS Chromatic Aberration GLSL Shader
  50339. // Author: Olivier Guyot
  50340. // Separates very slightly R, G and B colors on the edges of the screen
  50341. // Inspired by Francois Tarlier & Martins Upitis
  50342. var BABYLON;
  50343. (function (BABYLON) {
  50344. var LensRenderingPipeline = (function (_super) {
  50345. __extends(LensRenderingPipeline, _super);
  50346. /**
  50347. * @constructor
  50348. *
  50349. * Effect parameters are as follow:
  50350. * {
  50351. * chromatic_aberration: number; // from 0 to x (1 for realism)
  50352. * edge_blur: number; // from 0 to x (1 for realism)
  50353. * distortion: number; // from 0 to x (1 for realism)
  50354. * grain_amount: number; // from 0 to 1
  50355. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  50356. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  50357. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  50358. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  50359. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  50360. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  50361. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  50362. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  50363. * }
  50364. * Note: if an effect parameter is unset, effect is disabled
  50365. *
  50366. * @param {string} name - The rendering pipeline name
  50367. * @param {object} parameters - An object containing all parameters (see above)
  50368. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50369. * @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)
  50370. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50371. */
  50372. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  50373. if (ratio === void 0) { ratio = 1.0; }
  50374. var _this = _super.call(this, scene.getEngine(), name) || this;
  50375. // Lens effects can be of the following:
  50376. // - chromatic aberration (slight shift of RGB colors)
  50377. // - blur on the edge of the lens
  50378. // - lens distortion
  50379. // - depth-of-field blur & highlights enhancing
  50380. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  50381. // - grain effect (noise or custom texture)
  50382. // Two additional texture samplers are needed:
  50383. // - depth map (for depth-of-field)
  50384. // - grain texture
  50385. /**
  50386. * The chromatic aberration PostProcess id in the pipeline
  50387. * @type {string}
  50388. */
  50389. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  50390. /**
  50391. * The highlights enhancing PostProcess id in the pipeline
  50392. * @type {string}
  50393. */
  50394. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  50395. /**
  50396. * The depth-of-field PostProcess id in the pipeline
  50397. * @type {string}
  50398. */
  50399. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  50400. _this._scene = scene;
  50401. // Fetch texture samplers
  50402. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  50403. if (parameters.grain_texture) {
  50404. _this._grainTexture = parameters.grain_texture;
  50405. }
  50406. else {
  50407. _this._createGrainTexture();
  50408. }
  50409. // save parameters
  50410. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  50411. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  50412. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  50413. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  50414. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  50415. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  50416. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  50417. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  50418. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  50419. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  50420. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  50421. // Create effects
  50422. _this._createChromaticAberrationPostProcess(ratio);
  50423. _this._createHighlightsPostProcess(ratio);
  50424. _this._createDepthOfFieldPostProcess(ratio / 4);
  50425. // Set up pipeline
  50426. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  50427. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  50428. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  50429. if (_this._highlightsGain === -1) {
  50430. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  50431. }
  50432. // Finish
  50433. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50434. if (cameras) {
  50435. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50436. }
  50437. return _this;
  50438. }
  50439. // public methods (self explanatory)
  50440. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  50441. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  50442. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  50443. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  50444. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  50445. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  50446. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  50447. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  50448. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  50449. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  50450. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  50451. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  50452. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  50453. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  50454. };
  50455. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  50456. this._highlightsPostProcess.updateEffect();
  50457. };
  50458. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  50459. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  50460. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  50461. this._highlightsGain = amount;
  50462. };
  50463. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  50464. if (this._highlightsGain === -1) {
  50465. this._highlightsGain = 1.0;
  50466. }
  50467. this._highlightsThreshold = amount;
  50468. };
  50469. LensRenderingPipeline.prototype.disableHighlights = function () {
  50470. this._highlightsGain = -1;
  50471. };
  50472. /**
  50473. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  50474. */
  50475. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  50476. if (disableDepthRender === void 0) { disableDepthRender = false; }
  50477. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50478. this._chromaticAberrationPostProcess = undefined;
  50479. this._highlightsPostProcess = undefined;
  50480. this._depthOfFieldPostProcess = undefined;
  50481. this._grainTexture.dispose();
  50482. if (disableDepthRender)
  50483. this._scene.disableDepthRenderer();
  50484. };
  50485. // colors shifting and distortion
  50486. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  50487. var _this = this;
  50488. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  50489. [], // samplers
  50490. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50491. this._chromaticAberrationPostProcess.onApply = function (effect) {
  50492. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  50493. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50494. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50495. };
  50496. };
  50497. // highlights enhancing
  50498. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  50499. var _this = this;
  50500. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  50501. [], // samplers
  50502. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  50503. this._highlightsPostProcess.onApply = function (effect) {
  50504. effect.setFloat('gain', _this._highlightsGain);
  50505. effect.setFloat('threshold', _this._highlightsThreshold);
  50506. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  50507. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50508. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50509. };
  50510. };
  50511. // colors shifting and distortion
  50512. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  50513. var _this = this;
  50514. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  50515. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  50516. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  50517. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50518. this._depthOfFieldPostProcess.onApply = function (effect) {
  50519. effect.setTexture("depthSampler", _this._depthTexture);
  50520. effect.setTexture("grainSampler", _this._grainTexture);
  50521. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  50522. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  50523. effect.setFloat('grain_amount', _this._grainAmount);
  50524. effect.setBool('blur_noise', _this._blurNoise);
  50525. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50526. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50527. effect.setFloat('distortion', _this._distortion);
  50528. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  50529. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  50530. effect.setFloat('aperture', _this._dofAperture);
  50531. effect.setFloat('darken', _this._dofDarken);
  50532. effect.setFloat('edge_blur', _this._edgeBlur);
  50533. effect.setBool('highlights', (_this._highlightsGain !== -1));
  50534. effect.setFloat('near', _this._scene.activeCamera.minZ);
  50535. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  50536. };
  50537. };
  50538. // creates a black and white random noise texture, 512x512
  50539. LensRenderingPipeline.prototype._createGrainTexture = function () {
  50540. var size = 512;
  50541. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50542. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50543. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50544. var context = this._grainTexture.getContext();
  50545. var rand = function (min, max) {
  50546. return Math.random() * (max - min) + min;
  50547. };
  50548. var value;
  50549. for (var x = 0; x < size; x++) {
  50550. for (var y = 0; y < size; y++) {
  50551. value = Math.floor(rand(0.42, 0.58) * 255);
  50552. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  50553. context.fillRect(x, y, 1, 1);
  50554. }
  50555. }
  50556. this._grainTexture.update(false);
  50557. };
  50558. return LensRenderingPipeline;
  50559. }(BABYLON.PostProcessRenderPipeline));
  50560. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  50561. })(BABYLON || (BABYLON = {}));
  50562. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  50563. var BABYLON;
  50564. (function (BABYLON) {
  50565. var StandardRenderingPipeline = (function (_super) {
  50566. __extends(StandardRenderingPipeline, _super);
  50567. /**
  50568. * @constructor
  50569. * @param {string} name - The rendering pipeline name
  50570. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50571. * @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)
  50572. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  50573. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50574. */
  50575. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  50576. if (originalPostProcess === void 0) { originalPostProcess = null; }
  50577. var _this = _super.call(this, scene.getEngine(), name) || this;
  50578. _this.downSampleX4PostProcess = null;
  50579. _this.brightPassPostProcess = null;
  50580. _this.blurHPostProcesses = [];
  50581. _this.blurVPostProcesses = [];
  50582. _this.textureAdderPostProcess = null;
  50583. _this.volumetricLightPostProcess = null;
  50584. _this.volumetricLightSmoothXPostProcess = null;
  50585. _this.volumetricLightSmoothYPostProcess = null;
  50586. _this.volumetricLightMergePostProces = null;
  50587. _this.volumetricLightFinalPostProcess = null;
  50588. _this.luminancePostProcess = null;
  50589. _this.luminanceDownSamplePostProcesses = [];
  50590. _this.hdrPostProcess = null;
  50591. _this.textureAdderFinalPostProcess = null;
  50592. _this.lensFlareFinalPostProcess = null;
  50593. _this.hdrFinalPostProcess = null;
  50594. _this.lensFlarePostProcess = null;
  50595. _this.lensFlareComposePostProcess = null;
  50596. _this.motionBlurPostProcess = null;
  50597. _this.depthOfFieldPostProcess = null;
  50598. // Values
  50599. _this.brightThreshold = 1.0;
  50600. _this.blurWidth = 512.0;
  50601. _this.horizontalBlur = false;
  50602. _this.exposure = 1.0;
  50603. _this.lensTexture = null;
  50604. _this.volumetricLightCoefficient = 0.2;
  50605. _this.volumetricLightPower = 4.0;
  50606. _this.volumetricLightBlurScale = 64.0;
  50607. _this.sourceLight = null;
  50608. _this.hdrMinimumLuminance = 1.0;
  50609. _this.hdrDecreaseRate = 0.5;
  50610. _this.hdrIncreaseRate = 0.5;
  50611. _this.lensColorTexture = null;
  50612. _this.lensFlareStrength = 20.0;
  50613. _this.lensFlareGhostDispersal = 1.4;
  50614. _this.lensFlareHaloWidth = 0.7;
  50615. _this.lensFlareDistortionStrength = 16.0;
  50616. _this.lensStarTexture = null;
  50617. _this.lensFlareDirtTexture = null;
  50618. _this.depthOfFieldDistance = 10.0;
  50619. _this.depthOfFieldBlurWidth = 64.0;
  50620. _this.motionStrength = 1.0;
  50621. // IAnimatable
  50622. _this.animations = [];
  50623. _this._currentDepthOfFieldSource = null;
  50624. _this._hdrCurrentLuminance = 1.0;
  50625. // Getters and setters
  50626. _this._bloomEnabled = true;
  50627. _this._depthOfFieldEnabled = false;
  50628. _this._vlsEnabled = false;
  50629. _this._lensFlareEnabled = false;
  50630. _this._hdrEnabled = false;
  50631. _this._motionBlurEnabled = false;
  50632. _this._motionBlurSamples = 64.0;
  50633. _this._volumetricLightStepsCount = 50.0;
  50634. _this._cameras = cameras || [];
  50635. // Initialize
  50636. _this._scene = scene;
  50637. _this._basePostProcess = originalPostProcess;
  50638. _this._ratio = ratio;
  50639. // Misc
  50640. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50641. // Finish
  50642. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50643. _this._buildPipeline();
  50644. return _this;
  50645. }
  50646. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  50647. get: function () {
  50648. return this._bloomEnabled;
  50649. },
  50650. set: function (enabled) {
  50651. if (this._bloomEnabled === enabled) {
  50652. return;
  50653. }
  50654. this._bloomEnabled = enabled;
  50655. this._buildPipeline();
  50656. },
  50657. enumerable: true,
  50658. configurable: true
  50659. });
  50660. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  50661. get: function () {
  50662. return this._depthOfFieldEnabled;
  50663. },
  50664. set: function (enabled) {
  50665. if (this._depthOfFieldEnabled === enabled) {
  50666. return;
  50667. }
  50668. this._depthOfFieldEnabled = enabled;
  50669. this._buildPipeline();
  50670. },
  50671. enumerable: true,
  50672. configurable: true
  50673. });
  50674. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  50675. get: function () {
  50676. return this._lensFlareEnabled;
  50677. },
  50678. set: function (enabled) {
  50679. if (this._lensFlareEnabled === enabled) {
  50680. return;
  50681. }
  50682. this._lensFlareEnabled = enabled;
  50683. this._buildPipeline();
  50684. },
  50685. enumerable: true,
  50686. configurable: true
  50687. });
  50688. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  50689. get: function () {
  50690. return this._hdrEnabled;
  50691. },
  50692. set: function (enabled) {
  50693. if (this._hdrEnabled === enabled) {
  50694. return;
  50695. }
  50696. this._hdrEnabled = enabled;
  50697. this._buildPipeline();
  50698. },
  50699. enumerable: true,
  50700. configurable: true
  50701. });
  50702. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  50703. get: function () {
  50704. return this._vlsEnabled;
  50705. },
  50706. set: function (enabled) {
  50707. if (this._vlsEnabled === enabled) {
  50708. return;
  50709. }
  50710. if (enabled) {
  50711. var geometry = this._scene.enableGeometryBufferRenderer();
  50712. if (!geometry) {
  50713. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  50714. return;
  50715. }
  50716. }
  50717. this._vlsEnabled = enabled;
  50718. this._buildPipeline();
  50719. },
  50720. enumerable: true,
  50721. configurable: true
  50722. });
  50723. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  50724. get: function () {
  50725. return this._motionBlurEnabled;
  50726. },
  50727. set: function (enabled) {
  50728. if (this._motionBlurEnabled === enabled) {
  50729. return;
  50730. }
  50731. this._motionBlurEnabled = enabled;
  50732. this._buildPipeline();
  50733. },
  50734. enumerable: true,
  50735. configurable: true
  50736. });
  50737. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  50738. get: function () {
  50739. return this._volumetricLightStepsCount;
  50740. },
  50741. set: function (count) {
  50742. if (this.volumetricLightPostProcess) {
  50743. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  50744. }
  50745. this._volumetricLightStepsCount = count;
  50746. },
  50747. enumerable: true,
  50748. configurable: true
  50749. });
  50750. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  50751. get: function () {
  50752. return this._motionBlurSamples;
  50753. },
  50754. set: function (samples) {
  50755. if (this.motionBlurPostProcess) {
  50756. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  50757. }
  50758. this._motionBlurSamples = samples;
  50759. },
  50760. enumerable: true,
  50761. configurable: true
  50762. });
  50763. StandardRenderingPipeline.prototype._buildPipeline = function () {
  50764. var _this = this;
  50765. var ratio = this._ratio;
  50766. var scene = this._scene;
  50767. this._disposePostProcesses();
  50768. this._reset();
  50769. // Create pass post-process
  50770. if (!this._basePostProcess) {
  50771. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  50772. this.originalPostProcess.onApply = function (effect) {
  50773. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  50774. };
  50775. }
  50776. else {
  50777. this.originalPostProcess = this._basePostProcess;
  50778. }
  50779. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  50780. this._currentDepthOfFieldSource = this.originalPostProcess;
  50781. if (this._vlsEnabled) {
  50782. // Create volumetric light
  50783. this._createVolumetricLightPostProcess(scene, ratio);
  50784. // Create volumetric light final post-process
  50785. 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);
  50786. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  50787. }
  50788. if (this._bloomEnabled) {
  50789. // Create down sample X4 post-process
  50790. this._createDownSampleX4PostProcess(scene, ratio / 2);
  50791. // Create bright pass post-process
  50792. this._createBrightPassPostProcess(scene, ratio / 2);
  50793. // Create gaussian blur post-processes (down sampling blurs)
  50794. this._createBlurPostProcesses(scene, ratio / 4, 1);
  50795. // Create texture adder post-process
  50796. this._createTextureAdderPostProcess(scene, ratio);
  50797. // Create depth-of-field source post-process
  50798. 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);
  50799. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  50800. }
  50801. if (this._lensFlareEnabled) {
  50802. // Create lens flare post-process
  50803. this._createLensFlarePostProcess(scene, ratio);
  50804. // Create depth-of-field source post-process post lens-flare and disable it now
  50805. 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);
  50806. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  50807. }
  50808. if (this._hdrEnabled) {
  50809. // Create luminance
  50810. this._createLuminancePostProcesses(scene, this._floatTextureType);
  50811. // Create HDR
  50812. this._createHdrPostProcess(scene, ratio);
  50813. // Create depth-of-field source post-process post hdr and disable it now
  50814. 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);
  50815. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  50816. }
  50817. if (this._depthOfFieldEnabled) {
  50818. // Create gaussian blur used by depth-of-field
  50819. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  50820. // Create depth-of-field post-process
  50821. this._createDepthOfFieldPostProcess(scene, ratio);
  50822. }
  50823. if (this._motionBlurEnabled) {
  50824. // Create motion blur post-process
  50825. this._createMotionBlurPostProcess(scene, ratio);
  50826. }
  50827. if (this._cameras !== null) {
  50828. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  50829. }
  50830. };
  50831. // Down Sample X4 Post-Processs
  50832. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  50833. var _this = this;
  50834. var downSampleX4Offsets = new Array(32);
  50835. 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);
  50836. this.downSampleX4PostProcess.onApply = function (effect) {
  50837. var id = 0;
  50838. for (var i = -2; i < 2; i++) {
  50839. for (var j = -2; j < 2; j++) {
  50840. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  50841. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  50842. id += 2;
  50843. }
  50844. }
  50845. effect.setArray2("dsOffsets", downSampleX4Offsets);
  50846. };
  50847. // Add to pipeline
  50848. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  50849. };
  50850. // Brightpass Post-Process
  50851. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  50852. var _this = this;
  50853. var brightOffsets = new Array(8);
  50854. 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);
  50855. this.brightPassPostProcess.onApply = function (effect) {
  50856. var sU = (1.0 / _this.brightPassPostProcess.width);
  50857. var sV = (1.0 / _this.brightPassPostProcess.height);
  50858. brightOffsets[0] = -0.5 * sU;
  50859. brightOffsets[1] = 0.5 * sV;
  50860. brightOffsets[2] = 0.5 * sU;
  50861. brightOffsets[3] = 0.5 * sV;
  50862. brightOffsets[4] = -0.5 * sU;
  50863. brightOffsets[5] = -0.5 * sV;
  50864. brightOffsets[6] = 0.5 * sU;
  50865. brightOffsets[7] = -0.5 * sV;
  50866. effect.setArray2("dsOffsets", brightOffsets);
  50867. effect.setFloat("brightThreshold", _this.brightThreshold);
  50868. };
  50869. // Add to pipeline
  50870. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  50871. };
  50872. // Create blur H&V post-processes
  50873. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  50874. var _this = this;
  50875. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  50876. var engine = scene.getEngine();
  50877. 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);
  50878. 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);
  50879. blurX.onActivateObservable.add(function () {
  50880. var dw = blurX.width / engine.getRenderingCanvas().width;
  50881. blurX.kernel = _this[blurWidthKey] * dw;
  50882. });
  50883. blurY.onActivateObservable.add(function () {
  50884. var dw = blurY.height / engine.getRenderingCanvas().height;
  50885. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  50886. });
  50887. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  50888. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  50889. this.blurHPostProcesses.push(blurX);
  50890. this.blurVPostProcesses.push(blurY);
  50891. };
  50892. // Create texture adder post-process
  50893. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  50894. var _this = this;
  50895. 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);
  50896. this.textureAdderPostProcess.onApply = function (effect) {
  50897. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  50898. effect.setTexture("lensSampler", _this.lensTexture);
  50899. effect.setFloat("exposure", _this.exposure);
  50900. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  50901. };
  50902. // Add to pipeline
  50903. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  50904. };
  50905. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  50906. var _this = this;
  50907. var geometryRenderer = scene.enableGeometryBufferRenderer();
  50908. geometryRenderer.enablePosition = true;
  50909. var geometry = geometryRenderer.getGBuffer();
  50910. // Base post-process
  50911. 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));
  50912. var depthValues = BABYLON.Vector2.Zero();
  50913. this.volumetricLightPostProcess.onApply = function (effect) {
  50914. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  50915. var generator = _this.sourceLight.getShadowGenerator();
  50916. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  50917. effect.setTexture("positionSampler", geometry.textures[2]);
  50918. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  50919. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  50920. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  50921. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  50922. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  50923. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  50924. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  50925. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  50926. effect.setVector2("depthValues", depthValues);
  50927. }
  50928. };
  50929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  50930. // Smooth
  50931. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  50932. // Merge
  50933. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  50934. this.volumetricLightMergePostProces.onApply = function (effect) {
  50935. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  50936. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  50937. };
  50938. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  50939. };
  50940. // Create luminance
  50941. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  50942. var _this = this;
  50943. // Create luminance
  50944. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  50945. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  50946. var offsets = [];
  50947. this.luminancePostProcess.onApply = function (effect) {
  50948. var sU = (1.0 / _this.luminancePostProcess.width);
  50949. var sV = (1.0 / _this.luminancePostProcess.height);
  50950. offsets[0] = -0.5 * sU;
  50951. offsets[1] = 0.5 * sV;
  50952. offsets[2] = 0.5 * sU;
  50953. offsets[3] = 0.5 * sV;
  50954. offsets[4] = -0.5 * sU;
  50955. offsets[5] = -0.5 * sV;
  50956. offsets[6] = 0.5 * sU;
  50957. offsets[7] = -0.5 * sV;
  50958. effect.setArray2("lumOffsets", offsets);
  50959. };
  50960. // Add to pipeline
  50961. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  50962. // Create down sample luminance
  50963. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  50964. var size = Math.pow(3, i);
  50965. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  50966. if (i === 0) {
  50967. defines += "#define FINAL_DOWN_SAMPLER";
  50968. }
  50969. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  50970. this.luminanceDownSamplePostProcesses.push(postProcess);
  50971. }
  50972. // Create callbacks and add effects
  50973. var lastLuminance = this.luminancePostProcess;
  50974. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  50975. var downSampleOffsets = new Array(18);
  50976. pp.onApply = function (effect) {
  50977. var id = 0;
  50978. for (var x = -1; x < 2; x++) {
  50979. for (var y = -1; y < 2; y++) {
  50980. downSampleOffsets[id] = x / lastLuminance.width;
  50981. downSampleOffsets[id + 1] = y / lastLuminance.height;
  50982. id += 2;
  50983. }
  50984. }
  50985. effect.setArray2("dsOffsets", downSampleOffsets);
  50986. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  50987. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  50988. lastLuminance = _this.luminancePostProcess;
  50989. }
  50990. else {
  50991. lastLuminance = pp;
  50992. }
  50993. };
  50994. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  50995. pp.onAfterRender = function (effect) {
  50996. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  50997. 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);
  50998. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  50999. };
  51000. }
  51001. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  51002. });
  51003. };
  51004. // Create HDR post-process
  51005. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  51006. var _this = this;
  51007. 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);
  51008. var outputLiminance = 1;
  51009. var time = 0;
  51010. var lastTime = 0;
  51011. this.hdrPostProcess.onApply = function (effect) {
  51012. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  51013. time += scene.getEngine().getDeltaTime();
  51014. if (outputLiminance < 0) {
  51015. outputLiminance = _this._hdrCurrentLuminance;
  51016. }
  51017. else {
  51018. var dt = (lastTime - time) / 1000.0;
  51019. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  51020. outputLiminance += _this.hdrDecreaseRate * dt;
  51021. }
  51022. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  51023. outputLiminance -= _this.hdrIncreaseRate * dt;
  51024. }
  51025. else {
  51026. outputLiminance = _this._hdrCurrentLuminance;
  51027. }
  51028. }
  51029. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  51030. effect.setFloat("averageLuminance", outputLiminance);
  51031. lastTime = time;
  51032. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  51033. };
  51034. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  51035. };
  51036. // Create lens flare post-process
  51037. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  51038. var _this = this;
  51039. 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);
  51040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  51041. this._createBlurPostProcesses(scene, ratio / 4, 2);
  51042. 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);
  51043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  51044. var resolution = new BABYLON.Vector2(0, 0);
  51045. // Lens flare
  51046. this.lensFlarePostProcess.onApply = function (effect) {
  51047. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  51048. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  51049. effect.setFloat("strength", _this.lensFlareStrength);
  51050. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  51051. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  51052. // Shift
  51053. resolution.x = _this.lensFlarePostProcess.width;
  51054. resolution.y = _this.lensFlarePostProcess.height;
  51055. effect.setVector2("resolution", resolution);
  51056. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  51057. };
  51058. // Compose
  51059. 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);
  51060. 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);
  51061. this.lensFlareComposePostProcess.onApply = function (effect) {
  51062. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  51063. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  51064. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  51065. // Lens start rotation matrix
  51066. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  51067. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  51068. 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));
  51069. camRot *= 4.0;
  51070. 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);
  51071. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  51072. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  51073. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  51074. };
  51075. };
  51076. // Create depth-of-field post-process
  51077. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  51078. var _this = this;
  51079. 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);
  51080. this.depthOfFieldPostProcess.onApply = function (effect) {
  51081. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  51082. effect.setTexture("depthSampler", _this._getDepthTexture());
  51083. effect.setFloat("distance", _this.depthOfFieldDistance);
  51084. };
  51085. // Add to pipeline
  51086. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  51087. };
  51088. // Create motion blur post-process
  51089. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  51090. var _this = this;
  51091. 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);
  51092. var motionScale = 0;
  51093. var prevViewProjection = BABYLON.Matrix.Identity();
  51094. var invViewProjection = BABYLON.Matrix.Identity();
  51095. var viewProjection = BABYLON.Matrix.Identity();
  51096. var screenSize = BABYLON.Vector2.Zero();
  51097. this.motionBlurPostProcess.onApply = function (effect) {
  51098. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  51099. viewProjection.invertToRef(invViewProjection);
  51100. effect.setMatrix("inverseViewProjection", invViewProjection);
  51101. effect.setMatrix("prevViewProjection", prevViewProjection);
  51102. prevViewProjection = viewProjection;
  51103. screenSize.x = _this.motionBlurPostProcess.width;
  51104. screenSize.y = _this.motionBlurPostProcess.height;
  51105. effect.setVector2("screenSize", screenSize);
  51106. motionScale = scene.getEngine().getFps() / 60.0;
  51107. effect.setFloat("motionScale", motionScale);
  51108. effect.setFloat("motionStrength", _this.motionStrength);
  51109. effect.setTexture("depthSampler", _this._getDepthTexture());
  51110. };
  51111. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  51112. };
  51113. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  51114. var geometry = this._scene.enableGeometryBufferRenderer();
  51115. if (geometry) {
  51116. return geometry.getGBuffer().textures[0];
  51117. }
  51118. return this._scene.enableDepthRenderer().getDepthMap();
  51119. };
  51120. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  51121. for (var i = 0; i < this._cameras.length; i++) {
  51122. var camera = this._cameras[i];
  51123. if (this.originalPostProcess) {
  51124. this.originalPostProcess.dispose(camera);
  51125. }
  51126. if (this.downSampleX4PostProcess) {
  51127. this.downSampleX4PostProcess.dispose(camera);
  51128. }
  51129. if (this.brightPassPostProcess) {
  51130. this.brightPassPostProcess.dispose(camera);
  51131. }
  51132. if (this.textureAdderPostProcess) {
  51133. this.textureAdderPostProcess.dispose(camera);
  51134. }
  51135. if (this.textureAdderFinalPostProcess) {
  51136. this.textureAdderFinalPostProcess.dispose(camera);
  51137. }
  51138. if (this.volumetricLightPostProcess) {
  51139. this.volumetricLightPostProcess.dispose(camera);
  51140. }
  51141. if (this.volumetricLightSmoothXPostProcess) {
  51142. this.volumetricLightSmoothXPostProcess.dispose(camera);
  51143. }
  51144. if (this.volumetricLightSmoothYPostProcess) {
  51145. this.volumetricLightSmoothYPostProcess.dispose(camera);
  51146. }
  51147. if (this.volumetricLightMergePostProces) {
  51148. this.volumetricLightMergePostProces.dispose(camera);
  51149. }
  51150. if (this.volumetricLightFinalPostProcess) {
  51151. this.volumetricLightFinalPostProcess.dispose(camera);
  51152. }
  51153. if (this.lensFlarePostProcess) {
  51154. this.lensFlarePostProcess.dispose(camera);
  51155. }
  51156. if (this.lensFlareComposePostProcess) {
  51157. this.lensFlareComposePostProcess.dispose(camera);
  51158. }
  51159. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  51160. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  51161. }
  51162. if (this.luminancePostProcess) {
  51163. this.luminancePostProcess.dispose(camera);
  51164. }
  51165. if (this.hdrPostProcess) {
  51166. this.hdrPostProcess.dispose(camera);
  51167. }
  51168. if (this.hdrFinalPostProcess) {
  51169. this.hdrFinalPostProcess.dispose(camera);
  51170. }
  51171. if (this.depthOfFieldPostProcess) {
  51172. this.depthOfFieldPostProcess.dispose(camera);
  51173. }
  51174. if (this.motionBlurPostProcess) {
  51175. this.motionBlurPostProcess.dispose(camera);
  51176. }
  51177. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  51178. this.blurHPostProcesses[j].dispose(camera);
  51179. }
  51180. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  51181. this.blurVPostProcesses[j].dispose(camera);
  51182. }
  51183. }
  51184. this.originalPostProcess = null;
  51185. this.downSampleX4PostProcess = null;
  51186. this.brightPassPostProcess = null;
  51187. this.textureAdderPostProcess = null;
  51188. this.textureAdderFinalPostProcess = null;
  51189. this.volumetricLightPostProcess = null;
  51190. this.volumetricLightSmoothXPostProcess = null;
  51191. this.volumetricLightSmoothYPostProcess = null;
  51192. this.volumetricLightMergePostProces = null;
  51193. this.volumetricLightFinalPostProcess = null;
  51194. this.lensFlarePostProcess = null;
  51195. this.lensFlareComposePostProcess = null;
  51196. this.luminancePostProcess = null;
  51197. this.hdrPostProcess = null;
  51198. this.hdrFinalPostProcess = null;
  51199. this.depthOfFieldPostProcess = null;
  51200. this.motionBlurPostProcess = null;
  51201. this.luminanceDownSamplePostProcesses = [];
  51202. this.blurHPostProcesses = [];
  51203. this.blurVPostProcesses = [];
  51204. };
  51205. // Dispose
  51206. StandardRenderingPipeline.prototype.dispose = function () {
  51207. this._disposePostProcesses();
  51208. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  51209. _super.prototype.dispose.call(this);
  51210. };
  51211. // Serialize rendering pipeline
  51212. StandardRenderingPipeline.prototype.serialize = function () {
  51213. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51214. serializationObject.customType = "StandardRenderingPipeline";
  51215. return serializationObject;
  51216. };
  51217. /**
  51218. * Static members
  51219. */
  51220. // Parse serialized pipeline
  51221. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  51222. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  51223. };
  51224. return StandardRenderingPipeline;
  51225. }(BABYLON.PostProcessRenderPipeline));
  51226. // Luminance steps
  51227. StandardRenderingPipeline.LuminanceSteps = 6;
  51228. __decorate([
  51229. BABYLON.serialize()
  51230. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  51231. __decorate([
  51232. BABYLON.serialize()
  51233. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  51234. __decorate([
  51235. BABYLON.serialize()
  51236. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  51237. __decorate([
  51238. BABYLON.serialize()
  51239. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  51240. __decorate([
  51241. BABYLON.serializeAsTexture("lensTexture")
  51242. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  51243. __decorate([
  51244. BABYLON.serialize()
  51245. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  51246. __decorate([
  51247. BABYLON.serialize()
  51248. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  51249. __decorate([
  51250. BABYLON.serialize()
  51251. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  51252. __decorate([
  51253. BABYLON.serialize()
  51254. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  51255. __decorate([
  51256. BABYLON.serialize()
  51257. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  51258. __decorate([
  51259. BABYLON.serialize()
  51260. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  51261. __decorate([
  51262. BABYLON.serializeAsTexture("lensColorTexture")
  51263. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  51264. __decorate([
  51265. BABYLON.serialize()
  51266. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  51267. __decorate([
  51268. BABYLON.serialize()
  51269. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  51270. __decorate([
  51271. BABYLON.serialize()
  51272. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  51273. __decorate([
  51274. BABYLON.serialize()
  51275. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  51276. __decorate([
  51277. BABYLON.serializeAsTexture("lensStarTexture")
  51278. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  51279. __decorate([
  51280. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  51281. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  51282. __decorate([
  51283. BABYLON.serialize()
  51284. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  51285. __decorate([
  51286. BABYLON.serialize()
  51287. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  51288. __decorate([
  51289. BABYLON.serialize()
  51290. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  51291. __decorate([
  51292. BABYLON.serialize()
  51293. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  51294. __decorate([
  51295. BABYLON.serialize()
  51296. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  51297. __decorate([
  51298. BABYLON.serialize()
  51299. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  51300. __decorate([
  51301. BABYLON.serialize()
  51302. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  51303. __decorate([
  51304. BABYLON.serialize()
  51305. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  51306. __decorate([
  51307. BABYLON.serialize()
  51308. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  51309. __decorate([
  51310. BABYLON.serialize()
  51311. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  51312. __decorate([
  51313. BABYLON.serialize()
  51314. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  51315. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  51316. })(BABYLON || (BABYLON = {}));
  51317. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  51318. var BABYLON;
  51319. (function (BABYLON) {
  51320. var FxaaPostProcess = (function (_super) {
  51321. __extends(FxaaPostProcess, _super);
  51322. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51323. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51324. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  51325. _this.onApplyObservable.add(function (effect) {
  51326. var texelSize = _this.texelSize;
  51327. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  51328. });
  51329. return _this;
  51330. }
  51331. return FxaaPostProcess;
  51332. }(BABYLON.PostProcess));
  51333. BABYLON.FxaaPostProcess = FxaaPostProcess;
  51334. })(BABYLON || (BABYLON = {}));
  51335. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  51336. var BABYLON;
  51337. (function (BABYLON) {
  51338. var DefaultRenderingPipeline = (function (_super) {
  51339. __extends(DefaultRenderingPipeline, _super);
  51340. /**
  51341. * @constructor
  51342. * @param {string} name - The rendering pipeline name
  51343. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51344. * @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)
  51345. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51346. */
  51347. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  51348. var _this = _super.call(this, scene.getEngine(), name) || this;
  51349. _this.PassPostProcessId = "PassPostProcessEffect";
  51350. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  51351. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  51352. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  51353. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  51354. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  51355. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  51356. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  51357. // IAnimatable
  51358. _this.animations = [];
  51359. // Values
  51360. _this._bloomEnabled = false;
  51361. _this._fxaaEnabled = false;
  51362. _this._imageProcessingEnabled = true;
  51363. _this._bloomScale = 0.6;
  51364. /**
  51365. * Specifies the size of the bloom blur kernel, relative to the final output size
  51366. */
  51367. _this.bloomKernel = 64;
  51368. /**
  51369. * Specifies the weight of the bloom in the final rendering
  51370. */
  51371. _this._bloomWeight = 0.15;
  51372. _this._cameras = cameras || [];
  51373. // Initialize
  51374. _this._scene = scene;
  51375. var caps = _this._scene.getEngine().getCaps();
  51376. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  51377. // Misc
  51378. if (_this._hdr) {
  51379. if (caps.textureHalfFloatRender) {
  51380. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51381. }
  51382. else if (caps.textureFloatRender) {
  51383. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51384. }
  51385. }
  51386. else {
  51387. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51388. }
  51389. // Attach
  51390. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51391. _this._buildPipeline();
  51392. return _this;
  51393. }
  51394. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  51395. get: function () {
  51396. return this._bloomWeight;
  51397. },
  51398. set: function (value) {
  51399. if (this._bloomWeight === value) {
  51400. return;
  51401. }
  51402. this._bloomWeight = value;
  51403. if (this._hdr && this.copyBack) {
  51404. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  51405. }
  51406. },
  51407. enumerable: true,
  51408. configurable: true
  51409. });
  51410. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  51411. get: function () {
  51412. return this._bloomScale;
  51413. },
  51414. set: function (value) {
  51415. if (this._bloomScale === value) {
  51416. return;
  51417. }
  51418. this._bloomScale = value;
  51419. this._buildPipeline();
  51420. },
  51421. enumerable: true,
  51422. configurable: true
  51423. });
  51424. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  51425. get: function () {
  51426. return this._bloomEnabled;
  51427. },
  51428. set: function (enabled) {
  51429. if (this._bloomEnabled === enabled) {
  51430. return;
  51431. }
  51432. this._bloomEnabled = enabled;
  51433. this._buildPipeline();
  51434. },
  51435. enumerable: true,
  51436. configurable: true
  51437. });
  51438. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  51439. get: function () {
  51440. return this._fxaaEnabled;
  51441. },
  51442. set: function (enabled) {
  51443. if (this._fxaaEnabled === enabled) {
  51444. return;
  51445. }
  51446. this._fxaaEnabled = enabled;
  51447. this._buildPipeline();
  51448. },
  51449. enumerable: true,
  51450. configurable: true
  51451. });
  51452. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  51453. get: function () {
  51454. return this._imageProcessingEnabled;
  51455. },
  51456. set: function (enabled) {
  51457. if (this._imageProcessingEnabled === enabled) {
  51458. return;
  51459. }
  51460. this._imageProcessingEnabled = enabled;
  51461. this._buildPipeline();
  51462. },
  51463. enumerable: true,
  51464. configurable: true
  51465. });
  51466. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  51467. var _this = this;
  51468. var engine = this._scene.getEngine();
  51469. this._disposePostProcesses();
  51470. this._reset();
  51471. if (this.bloomEnabled) {
  51472. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51473. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  51474. if (!this._hdr) {
  51475. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51476. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  51477. this.highlights.autoClear = false;
  51478. this.highlights.alwaysForcePOT = true;
  51479. }
  51480. 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);
  51481. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  51482. this.blurX.alwaysForcePOT = true;
  51483. this.blurX.autoClear = false;
  51484. this.blurX.onActivateObservable.add(function () {
  51485. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  51486. _this.blurX.kernel = _this.bloomKernel * dw;
  51487. });
  51488. 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);
  51489. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  51490. this.blurY.alwaysForcePOT = true;
  51491. this.blurY.autoClear = false;
  51492. this.blurY.onActivateObservable.add(function () {
  51493. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  51494. _this.blurY.kernel = _this.bloomKernel * dh;
  51495. });
  51496. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51497. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  51498. this.copyBack.alwaysForcePOT = true;
  51499. if (this._hdr) {
  51500. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  51501. var w = this.bloomWeight;
  51502. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  51503. }
  51504. else {
  51505. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  51506. }
  51507. this.copyBack.autoClear = false;
  51508. }
  51509. if (this._imageProcessingEnabled) {
  51510. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51511. if (this._hdr) {
  51512. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  51513. }
  51514. }
  51515. if (this.fxaaEnabled) {
  51516. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51517. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  51518. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  51519. }
  51520. else {
  51521. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51522. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  51523. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  51524. }
  51525. if (this.bloomEnabled) {
  51526. if (this._hdr) {
  51527. this.copyBack.shareOutputWith(this.blurX);
  51528. if (this.imageProcessing) {
  51529. this.imageProcessing.shareOutputWith(this.pass);
  51530. this.imageProcessing.autoClear = false;
  51531. }
  51532. else if (this.fxaa) {
  51533. this.fxaa.shareOutputWith(this.pass);
  51534. }
  51535. else {
  51536. this.finalMerge.shareOutputWith(this.pass);
  51537. }
  51538. }
  51539. else {
  51540. if (this.fxaa) {
  51541. this.fxaa.shareOutputWith(this.pass);
  51542. }
  51543. else {
  51544. this.finalMerge.shareOutputWith(this.pass);
  51545. }
  51546. }
  51547. }
  51548. if (this._cameras !== null) {
  51549. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  51550. }
  51551. };
  51552. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  51553. for (var i = 0; i < this._cameras.length; i++) {
  51554. var camera = this._cameras[i];
  51555. if (this.pass) {
  51556. this.pass.dispose(camera);
  51557. }
  51558. if (this.highlights) {
  51559. this.highlights.dispose(camera);
  51560. }
  51561. if (this.blurX) {
  51562. this.blurX.dispose(camera);
  51563. }
  51564. if (this.blurY) {
  51565. this.blurY.dispose(camera);
  51566. }
  51567. if (this.copyBack) {
  51568. this.copyBack.dispose(camera);
  51569. }
  51570. if (this.imageProcessing) {
  51571. this.imageProcessing.dispose(camera);
  51572. }
  51573. if (this.fxaa) {
  51574. this.fxaa.dispose(camera);
  51575. }
  51576. if (this.finalMerge) {
  51577. this.finalMerge.dispose(camera);
  51578. }
  51579. }
  51580. this.pass = null;
  51581. this.highlights = null;
  51582. this.blurX = null;
  51583. this.blurY = null;
  51584. this.copyBack = null;
  51585. this.imageProcessing = null;
  51586. this.fxaa = null;
  51587. this.finalMerge = null;
  51588. };
  51589. // Dispose
  51590. DefaultRenderingPipeline.prototype.dispose = function () {
  51591. this._disposePostProcesses();
  51592. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  51593. _super.prototype.dispose.call(this);
  51594. };
  51595. // Serialize rendering pipeline
  51596. DefaultRenderingPipeline.prototype.serialize = function () {
  51597. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51598. serializationObject.customType = "DefaultRenderingPipeline";
  51599. return serializationObject;
  51600. };
  51601. // Parse serialized pipeline
  51602. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  51603. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  51604. };
  51605. return DefaultRenderingPipeline;
  51606. }(BABYLON.PostProcessRenderPipeline));
  51607. __decorate([
  51608. BABYLON.serialize()
  51609. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  51610. __decorate([
  51611. BABYLON.serialize()
  51612. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  51613. __decorate([
  51614. BABYLON.serialize()
  51615. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  51616. __decorate([
  51617. BABYLON.serialize()
  51618. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  51619. __decorate([
  51620. BABYLON.serialize()
  51621. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  51622. __decorate([
  51623. BABYLON.serialize()
  51624. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  51625. __decorate([
  51626. BABYLON.serialize()
  51627. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  51628. __decorate([
  51629. BABYLON.serialize()
  51630. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  51631. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  51632. })(BABYLON || (BABYLON = {}));
  51633. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  51634. var BABYLON;
  51635. (function (BABYLON) {
  51636. var GeometryBufferRenderer = (function () {
  51637. function GeometryBufferRenderer(scene, ratio) {
  51638. if (ratio === void 0) { ratio = 1; }
  51639. this._viewMatrix = BABYLON.Matrix.Zero();
  51640. this._projectionMatrix = BABYLON.Matrix.Zero();
  51641. this._transformMatrix = BABYLON.Matrix.Zero();
  51642. this._worldViewProjection = BABYLON.Matrix.Zero();
  51643. this._enablePosition = false;
  51644. this._scene = scene;
  51645. this._ratio = ratio;
  51646. // Render target
  51647. this._createRenderTargets();
  51648. }
  51649. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  51650. set: function (meshes) {
  51651. this._multiRenderTarget.renderList = meshes;
  51652. },
  51653. enumerable: true,
  51654. configurable: true
  51655. });
  51656. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  51657. get: function () {
  51658. return this._multiRenderTarget.isSupported;
  51659. },
  51660. enumerable: true,
  51661. configurable: true
  51662. });
  51663. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  51664. get: function () {
  51665. return this._enablePosition;
  51666. },
  51667. set: function (enable) {
  51668. this._enablePosition = enable;
  51669. this.dispose();
  51670. this._createRenderTargets();
  51671. },
  51672. enumerable: true,
  51673. configurable: true
  51674. });
  51675. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  51676. var material = subMesh.getMaterial();
  51677. if (material && material.disableDepthWrite) {
  51678. return false;
  51679. }
  51680. var defines = [];
  51681. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  51682. var mesh = subMesh.getMesh();
  51683. var scene = mesh.getScene();
  51684. // Alpha test
  51685. if (material && material.needAlphaTesting()) {
  51686. defines.push("#define ALPHATEST");
  51687. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51688. attribs.push(BABYLON.VertexBuffer.UVKind);
  51689. defines.push("#define UV1");
  51690. }
  51691. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51692. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51693. defines.push("#define UV2");
  51694. }
  51695. }
  51696. // Buffers
  51697. if (this._enablePosition) {
  51698. defines.push("#define POSITION");
  51699. }
  51700. // Bones
  51701. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51702. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51703. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51704. if (mesh.numBoneInfluencers > 4) {
  51705. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51706. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51707. }
  51708. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51709. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51710. }
  51711. else {
  51712. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51713. }
  51714. // Instances
  51715. if (useInstances) {
  51716. defines.push("#define INSTANCES");
  51717. attribs.push("world0");
  51718. attribs.push("world1");
  51719. attribs.push("world2");
  51720. attribs.push("world3");
  51721. }
  51722. // Get correct effect
  51723. var join = defines.join("\n");
  51724. if (this._cachedDefines !== join) {
  51725. this._cachedDefines = join;
  51726. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  51727. }
  51728. return this._effect.isReady();
  51729. };
  51730. GeometryBufferRenderer.prototype.getGBuffer = function () {
  51731. return this._multiRenderTarget;
  51732. };
  51733. // Methods
  51734. GeometryBufferRenderer.prototype.dispose = function () {
  51735. this.getGBuffer().dispose();
  51736. };
  51737. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  51738. var _this = this;
  51739. var engine = this._scene.getEngine();
  51740. var count = this._enablePosition ? 3 : 2;
  51741. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  51742. if (!this.isSupported) {
  51743. return null;
  51744. }
  51745. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51746. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51747. this._multiRenderTarget.refreshRate = 1;
  51748. this._multiRenderTarget.renderParticles = false;
  51749. this._multiRenderTarget.renderList = null;
  51750. // set default depth value to 1.0 (far away)
  51751. this._multiRenderTarget.onClearObservable.add(function (engine) {
  51752. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  51753. });
  51754. // Custom render function
  51755. var renderSubMesh = function (subMesh) {
  51756. var mesh = subMesh.getRenderingMesh();
  51757. var scene = _this._scene;
  51758. var engine = scene.getEngine();
  51759. // Culling
  51760. engine.setState(subMesh.getMaterial().backFaceCulling);
  51761. // Managing instances
  51762. var batch = mesh._getInstancesRenderList(subMesh._id);
  51763. if (batch.mustReturn) {
  51764. return;
  51765. }
  51766. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  51767. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51768. engine.enableEffect(_this._effect);
  51769. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  51770. var material = subMesh.getMaterial();
  51771. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51772. _this._effect.setMatrix("view", scene.getViewMatrix());
  51773. // Alpha test
  51774. if (material && material.needAlphaTesting()) {
  51775. var alphaTexture = material.getAlphaTestTexture();
  51776. _this._effect.setTexture("diffuseSampler", alphaTexture);
  51777. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51778. }
  51779. // Bones
  51780. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51781. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51782. }
  51783. // Draw
  51784. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51785. }
  51786. };
  51787. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  51788. var index;
  51789. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51790. renderSubMesh(opaqueSubMeshes.data[index]);
  51791. }
  51792. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51793. renderSubMesh(alphaTestSubMeshes.data[index]);
  51794. }
  51795. };
  51796. };
  51797. return GeometryBufferRenderer;
  51798. }());
  51799. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  51800. })(BABYLON || (BABYLON = {}));
  51801. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  51802. var BABYLON;
  51803. (function (BABYLON) {
  51804. var RefractionPostProcess = (function (_super) {
  51805. __extends(RefractionPostProcess, _super);
  51806. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  51807. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  51808. _this.color = color;
  51809. _this.depth = depth;
  51810. _this.colorLevel = colorLevel;
  51811. _this.onActivateObservable.add(function (cam) {
  51812. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  51813. });
  51814. _this.onApplyObservable.add(function (effect) {
  51815. effect.setColor3("baseColor", _this.color);
  51816. effect.setFloat("depth", _this.depth);
  51817. effect.setFloat("colorLevel", _this.colorLevel);
  51818. effect.setTexture("refractionSampler", _this._refRexture);
  51819. });
  51820. return _this;
  51821. }
  51822. // Methods
  51823. RefractionPostProcess.prototype.dispose = function (camera) {
  51824. if (this._refRexture) {
  51825. this._refRexture.dispose();
  51826. }
  51827. _super.prototype.dispose.call(this, camera);
  51828. };
  51829. return RefractionPostProcess;
  51830. }(BABYLON.PostProcess));
  51831. BABYLON.RefractionPostProcess = RefractionPostProcess;
  51832. })(BABYLON || (BABYLON = {}));
  51833. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  51834. var BABYLON;
  51835. (function (BABYLON) {
  51836. var BlackAndWhitePostProcess = (function (_super) {
  51837. __extends(BlackAndWhitePostProcess, _super);
  51838. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  51839. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  51840. _this.degree = 1;
  51841. _this.onApplyObservable.add(function (effect) {
  51842. effect.setFloat("degree", _this.degree);
  51843. });
  51844. return _this;
  51845. }
  51846. return BlackAndWhitePostProcess;
  51847. }(BABYLON.PostProcess));
  51848. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  51849. })(BABYLON || (BABYLON = {}));
  51850. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  51851. var BABYLON;
  51852. (function (BABYLON) {
  51853. var ConvolutionPostProcess = (function (_super) {
  51854. __extends(ConvolutionPostProcess, _super);
  51855. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  51856. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  51857. _this.kernel = kernel;
  51858. _this.onApply = function (effect) {
  51859. effect.setFloat2("screenSize", _this.width, _this.height);
  51860. effect.setArray("kernel", _this.kernel);
  51861. };
  51862. return _this;
  51863. }
  51864. return ConvolutionPostProcess;
  51865. }(BABYLON.PostProcess));
  51866. // Statics
  51867. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  51868. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  51869. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  51870. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  51871. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  51872. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  51873. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  51874. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  51875. })(BABYLON || (BABYLON = {}));
  51876. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  51877. var BABYLON;
  51878. (function (BABYLON) {
  51879. var FilterPostProcess = (function (_super) {
  51880. __extends(FilterPostProcess, _super);
  51881. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  51882. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  51883. _this.kernelMatrix = kernelMatrix;
  51884. _this.onApply = function (effect) {
  51885. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  51886. };
  51887. return _this;
  51888. }
  51889. return FilterPostProcess;
  51890. }(BABYLON.PostProcess));
  51891. BABYLON.FilterPostProcess = FilterPostProcess;
  51892. })(BABYLON || (BABYLON = {}));
  51893. //# sourceMappingURL=babylon.filterPostProcess.js.map
  51894. var BABYLON;
  51895. (function (BABYLON) {
  51896. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  51897. var VolumetricLightScatteringPostProcess = (function (_super) {
  51898. __extends(VolumetricLightScatteringPostProcess, _super);
  51899. /**
  51900. * @constructor
  51901. * @param {string} name - The post-process name
  51902. * @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)
  51903. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  51904. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  51905. * @param {number} samples - The post-process quality, default 100
  51906. * @param {number} samplingMode - The post-process filtering mode
  51907. * @param {BABYLON.Engine} engine - The babylon engine
  51908. * @param {boolean} reusable - If the post-process is reusable
  51909. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  51910. */
  51911. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  51912. if (samples === void 0) { samples = 100; }
  51913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51914. 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;
  51915. _this._screenCoordinates = BABYLON.Vector2.Zero();
  51916. /**
  51917. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  51918. * @type {Vector3}
  51919. */
  51920. _this.customMeshPosition = BABYLON.Vector3.Zero();
  51921. /**
  51922. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  51923. * @type {boolean}
  51924. */
  51925. _this.useCustomMeshPosition = false;
  51926. /**
  51927. * If the post-process should inverse the light scattering direction
  51928. * @type {boolean}
  51929. */
  51930. _this.invert = true;
  51931. /**
  51932. * Array containing the excluded meshes not rendered in the internal pass
  51933. */
  51934. _this.excludedMeshes = new Array();
  51935. /**
  51936. * Controls the overall intensity of the post-process
  51937. * @type {number}
  51938. */
  51939. _this.exposure = 0.3;
  51940. /**
  51941. * Dissipates each sample's contribution in range [0, 1]
  51942. * @type {number}
  51943. */
  51944. _this.decay = 0.96815;
  51945. /**
  51946. * Controls the overall intensity of each sample
  51947. * @type {number}
  51948. */
  51949. _this.weight = 0.58767;
  51950. /**
  51951. * Controls the density of each sample
  51952. * @type {number}
  51953. */
  51954. _this.density = 0.926;
  51955. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  51956. var engine = scene.getEngine();
  51957. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  51958. // Configure mesh
  51959. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  51960. // Configure
  51961. _this._createPass(scene, ratio.passRatio || ratio);
  51962. _this.onActivate = function (camera) {
  51963. if (!_this.isSupported) {
  51964. _this.dispose(camera);
  51965. }
  51966. _this.onActivate = null;
  51967. };
  51968. _this.onApplyObservable.add(function (effect) {
  51969. _this._updateMeshScreenCoordinates(scene);
  51970. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  51971. effect.setFloat("exposure", _this.exposure);
  51972. effect.setFloat("decay", _this.decay);
  51973. effect.setFloat("weight", _this.weight);
  51974. effect.setFloat("density", _this.density);
  51975. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  51976. });
  51977. return _this;
  51978. }
  51979. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  51980. get: function () {
  51981. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51982. return false;
  51983. },
  51984. set: function (useDiffuseColor) {
  51985. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51986. },
  51987. enumerable: true,
  51988. configurable: true
  51989. });
  51990. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  51991. var mesh = subMesh.getMesh();
  51992. // Render this.mesh as default
  51993. if (mesh === this.mesh) {
  51994. return mesh.material.isReady(mesh);
  51995. }
  51996. var defines = [];
  51997. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51998. var material = subMesh.getMaterial();
  51999. var needUV = false;
  52000. // Alpha test
  52001. if (material) {
  52002. if (material.needAlphaTesting()) {
  52003. defines.push("#define ALPHATEST");
  52004. }
  52005. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52006. attribs.push(BABYLON.VertexBuffer.UVKind);
  52007. defines.push("#define UV1");
  52008. }
  52009. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52010. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52011. defines.push("#define UV2");
  52012. }
  52013. }
  52014. // Bones
  52015. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52016. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52017. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52018. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52019. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52020. }
  52021. else {
  52022. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52023. }
  52024. // Instances
  52025. if (useInstances) {
  52026. defines.push("#define INSTANCES");
  52027. attribs.push("world0");
  52028. attribs.push("world1");
  52029. attribs.push("world2");
  52030. attribs.push("world3");
  52031. }
  52032. // Get correct effect
  52033. var join = defines.join("\n");
  52034. if (this._cachedDefines !== join) {
  52035. this._cachedDefines = join;
  52036. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  52037. }
  52038. return this._volumetricLightScatteringPass.isReady();
  52039. };
  52040. /**
  52041. * Sets the new light position for light scattering effect
  52042. * @param {BABYLON.Vector3} The new custom light position
  52043. */
  52044. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  52045. this.customMeshPosition = position;
  52046. };
  52047. /**
  52048. * Returns the light position for light scattering effect
  52049. * @return {BABYLON.Vector3} The custom light position
  52050. */
  52051. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  52052. return this.customMeshPosition;
  52053. };
  52054. /**
  52055. * Disposes the internal assets and detaches the post-process from the camera
  52056. */
  52057. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  52058. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  52059. if (rttIndex !== -1) {
  52060. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  52061. }
  52062. this._volumetricLightScatteringRTT.dispose();
  52063. _super.prototype.dispose.call(this, camera);
  52064. };
  52065. /**
  52066. * Returns the render target texture used by the post-process
  52067. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52068. */
  52069. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52070. return this._volumetricLightScatteringRTT;
  52071. };
  52072. // Private methods
  52073. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52074. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52075. return true;
  52076. }
  52077. return false;
  52078. };
  52079. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52080. var _this = this;
  52081. var engine = scene.getEngine();
  52082. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52083. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52084. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52085. this._volumetricLightScatteringRTT.renderList = null;
  52086. this._volumetricLightScatteringRTT.renderParticles = false;
  52087. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52088. // Custom render function for submeshes
  52089. var renderSubMesh = function (subMesh) {
  52090. var mesh = subMesh.getRenderingMesh();
  52091. if (_this._meshExcluded(mesh)) {
  52092. return;
  52093. }
  52094. var scene = mesh.getScene();
  52095. var engine = scene.getEngine();
  52096. // Culling
  52097. engine.setState(subMesh.getMaterial().backFaceCulling);
  52098. // Managing instances
  52099. var batch = mesh._getInstancesRenderList(subMesh._id);
  52100. if (batch.mustReturn) {
  52101. return;
  52102. }
  52103. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  52104. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52105. var effect = _this._volumetricLightScatteringPass;
  52106. if (mesh === _this.mesh) {
  52107. if (subMesh.effect) {
  52108. effect = subMesh.effect;
  52109. }
  52110. else {
  52111. effect = subMesh.getMaterial().getEffect();
  52112. }
  52113. }
  52114. engine.enableEffect(effect);
  52115. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52116. if (mesh === _this.mesh) {
  52117. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52118. }
  52119. else {
  52120. var material = subMesh.getMaterial();
  52121. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52122. // Alpha test
  52123. if (material && material.needAlphaTesting()) {
  52124. var alphaTexture = material.getAlphaTestTexture();
  52125. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52126. if (alphaTexture) {
  52127. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52128. }
  52129. }
  52130. // Bones
  52131. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52132. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52133. }
  52134. }
  52135. // Draw
  52136. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52137. }
  52138. };
  52139. // Render target texture callbacks
  52140. var savedSceneClearColor;
  52141. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52142. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52143. savedSceneClearColor = scene.clearColor;
  52144. scene.clearColor = sceneClearColor;
  52145. });
  52146. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52147. scene.clearColor = savedSceneClearColor;
  52148. });
  52149. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52150. var engine = scene.getEngine();
  52151. var index;
  52152. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52153. renderSubMesh(opaqueSubMeshes.data[index]);
  52154. }
  52155. engine.setAlphaTesting(true);
  52156. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52157. renderSubMesh(alphaTestSubMeshes.data[index]);
  52158. }
  52159. engine.setAlphaTesting(false);
  52160. if (transparentSubMeshes.length) {
  52161. // Sort sub meshes
  52162. for (index = 0; index < transparentSubMeshes.length; index++) {
  52163. var submesh = transparentSubMeshes.data[index];
  52164. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52165. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52166. }
  52167. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  52168. sortedArray.sort(function (a, b) {
  52169. // Alpha index first
  52170. if (a._alphaIndex > b._alphaIndex) {
  52171. return 1;
  52172. }
  52173. if (a._alphaIndex < b._alphaIndex) {
  52174. return -1;
  52175. }
  52176. // Then distance to camera
  52177. if (a._distanceToCamera < b._distanceToCamera) {
  52178. return 1;
  52179. }
  52180. if (a._distanceToCamera > b._distanceToCamera) {
  52181. return -1;
  52182. }
  52183. return 0;
  52184. });
  52185. // Render sub meshes
  52186. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52187. for (index = 0; index < sortedArray.length; index++) {
  52188. renderSubMesh(sortedArray[index]);
  52189. }
  52190. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52191. }
  52192. };
  52193. };
  52194. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  52195. var transform = scene.getTransformMatrix();
  52196. var meshPosition;
  52197. if (this.useCustomMeshPosition) {
  52198. meshPosition = this.customMeshPosition;
  52199. }
  52200. else if (this.attachedNode) {
  52201. meshPosition = this.attachedNode.position;
  52202. }
  52203. else {
  52204. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  52205. }
  52206. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  52207. this._screenCoordinates.x = pos.x / this._viewPort.width;
  52208. this._screenCoordinates.y = pos.y / this._viewPort.height;
  52209. if (this.invert)
  52210. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  52211. };
  52212. // Static methods
  52213. /**
  52214. * Creates a default mesh for the Volumeric Light Scattering post-process
  52215. * @param {string} The mesh name
  52216. * @param {BABYLON.Scene} The scene where to create the mesh
  52217. * @return {BABYLON.Mesh} the default mesh
  52218. */
  52219. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  52220. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  52221. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  52222. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  52223. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  52224. mesh.material = material;
  52225. return mesh;
  52226. };
  52227. return VolumetricLightScatteringPostProcess;
  52228. }(BABYLON.PostProcess));
  52229. __decorate([
  52230. BABYLON.serializeAsVector3()
  52231. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  52232. __decorate([
  52233. BABYLON.serialize()
  52234. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  52235. __decorate([
  52236. BABYLON.serialize()
  52237. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  52238. __decorate([
  52239. BABYLON.serializeAsMeshReference()
  52240. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  52241. __decorate([
  52242. BABYLON.serialize()
  52243. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  52244. __decorate([
  52245. BABYLON.serialize()
  52246. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  52247. __decorate([
  52248. BABYLON.serialize()
  52249. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  52250. __decorate([
  52251. BABYLON.serialize()
  52252. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  52253. __decorate([
  52254. BABYLON.serialize()
  52255. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  52256. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  52257. })(BABYLON || (BABYLON = {}));
  52258. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  52259. //
  52260. // This post-process allows the modification of rendered colors by using
  52261. // a 'look-up table' (LUT). This effect is also called Color Grading.
  52262. //
  52263. // The object needs to be provided an url to a texture containing the color
  52264. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  52265. // Use an image editing software to tweak the LUT to match your needs.
  52266. //
  52267. // For an example of a color LUT, see here:
  52268. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  52269. // For explanations on color grading, see here:
  52270. // http://udn.epicgames.com/Three/ColorGrading.html
  52271. //
  52272. var BABYLON;
  52273. (function (BABYLON) {
  52274. var ColorCorrectionPostProcess = (function (_super) {
  52275. __extends(ColorCorrectionPostProcess, _super);
  52276. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  52277. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  52278. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52279. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  52280. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52281. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52282. _this.onApply = function (effect) {
  52283. effect.setTexture("colorTable", _this._colorTableTexture);
  52284. };
  52285. return _this;
  52286. }
  52287. return ColorCorrectionPostProcess;
  52288. }(BABYLON.PostProcess));
  52289. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  52290. })(BABYLON || (BABYLON = {}));
  52291. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  52292. var BABYLON;
  52293. (function (BABYLON) {
  52294. var TonemappingOperator;
  52295. (function (TonemappingOperator) {
  52296. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  52297. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  52298. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  52299. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  52300. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  52301. ;
  52302. var TonemapPostProcess = (function (_super) {
  52303. __extends(TonemapPostProcess, _super);
  52304. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  52305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52306. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52307. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  52308. _this._operator = _operator;
  52309. _this.exposureAdjustment = exposureAdjustment;
  52310. var defines = "#define ";
  52311. if (_this._operator === TonemappingOperator.Hable)
  52312. defines += "HABLE_TONEMAPPING";
  52313. else if (_this._operator === TonemappingOperator.Reinhard)
  52314. defines += "REINHARD_TONEMAPPING";
  52315. else if (_this._operator === TonemappingOperator.HejiDawson)
  52316. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  52317. else if (_this._operator === TonemappingOperator.Photographic)
  52318. defines += "PHOTOGRAPHIC_TONEMAPPING";
  52319. //sadly a second call to create the effect.
  52320. _this.updateEffect(defines);
  52321. _this.onApply = function (effect) {
  52322. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  52323. };
  52324. return _this;
  52325. }
  52326. return TonemapPostProcess;
  52327. }(BABYLON.PostProcess));
  52328. BABYLON.TonemapPostProcess = TonemapPostProcess;
  52329. })(BABYLON || (BABYLON = {}));
  52330. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  52331. var BABYLON;
  52332. (function (BABYLON) {
  52333. var DisplayPassPostProcess = (function (_super) {
  52334. __extends(DisplayPassPostProcess, _super);
  52335. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  52336. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  52337. }
  52338. return DisplayPassPostProcess;
  52339. }(BABYLON.PostProcess));
  52340. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  52341. })(BABYLON || (BABYLON = {}));
  52342. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  52343. var BABYLON;
  52344. (function (BABYLON) {
  52345. var HighlightsPostProcess = (function (_super) {
  52346. __extends(HighlightsPostProcess, _super);
  52347. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52348. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52349. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  52350. }
  52351. return HighlightsPostProcess;
  52352. }(BABYLON.PostProcess));
  52353. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  52354. })(BABYLON || (BABYLON = {}));
  52355. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  52356. var BABYLON;
  52357. (function (BABYLON) {
  52358. var ImageProcessingPostProcess = (function (_super) {
  52359. __extends(ImageProcessingPostProcess, _super);
  52360. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52361. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52362. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  52363. _this._fromLinearSpace = true;
  52364. /**
  52365. * Defines cache preventing GC.
  52366. */
  52367. _this._defines = {
  52368. IMAGEPROCESSING: false,
  52369. VIGNETTE: false,
  52370. VIGNETTEBLENDMODEMULTIPLY: false,
  52371. VIGNETTEBLENDMODEOPAQUE: false,
  52372. TONEMAPPING: false,
  52373. CONTRAST: false,
  52374. COLORCURVES: false,
  52375. COLORGRADING: false,
  52376. FROMLINEARSPACE: false,
  52377. SAMPLER3DGREENDEPTH: false,
  52378. SAMPLER3DBGRMAP: false,
  52379. IMAGEPROCESSINGPOSTPROCESS: false,
  52380. EXPOSURE: false,
  52381. };
  52382. // Setup the default processing configuration to the scene.
  52383. _this._attachImageProcessingConfiguration(null);
  52384. _this.imageProcessingConfiguration.applyByPostProcess = true;
  52385. _this._updateParameters();
  52386. _this.onApply = function (effect) {
  52387. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  52388. };
  52389. return _this;
  52390. }
  52391. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  52392. /**
  52393. * Gets the image processing configuration used either in this material.
  52394. */
  52395. get: function () {
  52396. return this._imageProcessingConfiguration;
  52397. },
  52398. /**
  52399. * Sets the Default image processing configuration used either in the this material.
  52400. *
  52401. * If sets to null, the scene one is in use.
  52402. */
  52403. set: function (value) {
  52404. this._attachImageProcessingConfiguration(value);
  52405. },
  52406. enumerable: true,
  52407. configurable: true
  52408. });
  52409. /**
  52410. * Attaches a new image processing configuration to the PBR Material.
  52411. * @param configuration
  52412. */
  52413. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration) {
  52414. var _this = this;
  52415. if (configuration === this._imageProcessingConfiguration) {
  52416. return;
  52417. }
  52418. // Detaches observer.
  52419. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  52420. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  52421. }
  52422. // Pick the scene configuration if needed.
  52423. if (!configuration) {
  52424. var camera = this.getCamera();
  52425. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  52426. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  52427. }
  52428. else {
  52429. this._imageProcessingConfiguration = configuration;
  52430. }
  52431. // Attaches observer.
  52432. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  52433. _this._updateParameters();
  52434. });
  52435. // Ensure the effect will be rebuilt.
  52436. this._updateParameters();
  52437. };
  52438. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  52439. /**
  52440. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  52441. */
  52442. get: function () {
  52443. return this.imageProcessingConfiguration.colorCurves;
  52444. },
  52445. /**
  52446. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  52447. */
  52448. set: function (value) {
  52449. this.imageProcessingConfiguration.colorCurves = value;
  52450. },
  52451. enumerable: true,
  52452. configurable: true
  52453. });
  52454. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  52455. /**
  52456. * Gets wether the color curves effect is enabled.
  52457. */
  52458. get: function () {
  52459. return this.imageProcessingConfiguration.colorCurvesEnabled;
  52460. },
  52461. /**
  52462. * Sets wether the color curves effect is enabled.
  52463. */
  52464. set: function (value) {
  52465. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  52466. },
  52467. enumerable: true,
  52468. configurable: true
  52469. });
  52470. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  52471. /**
  52472. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  52473. */
  52474. get: function () {
  52475. return this.imageProcessingConfiguration.colorGradingTexture;
  52476. },
  52477. /**
  52478. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  52479. */
  52480. set: function (value) {
  52481. this.imageProcessingConfiguration.colorGradingTexture = value;
  52482. },
  52483. enumerable: true,
  52484. configurable: true
  52485. });
  52486. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  52487. /**
  52488. * Gets wether the color grading effect is enabled.
  52489. */
  52490. get: function () {
  52491. return this.imageProcessingConfiguration.colorGradingEnabled;
  52492. },
  52493. /**
  52494. * Gets wether the color grading effect is enabled.
  52495. */
  52496. set: function (value) {
  52497. this.imageProcessingConfiguration.colorGradingEnabled = value;
  52498. },
  52499. enumerable: true,
  52500. configurable: true
  52501. });
  52502. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  52503. /**
  52504. * Gets exposure used in the effect.
  52505. */
  52506. get: function () {
  52507. return this.imageProcessingConfiguration.exposure;
  52508. },
  52509. /**
  52510. * Sets exposure used in the effect.
  52511. */
  52512. set: function (value) {
  52513. this.imageProcessingConfiguration.exposure = value;
  52514. },
  52515. enumerable: true,
  52516. configurable: true
  52517. });
  52518. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  52519. /**
  52520. * Gets wether tonemapping is enabled or not.
  52521. */
  52522. get: function () {
  52523. return this._imageProcessingConfiguration.toneMappingEnabled;
  52524. },
  52525. /**
  52526. * Sets wether tonemapping is enabled or not
  52527. */
  52528. set: function (value) {
  52529. this._imageProcessingConfiguration.toneMappingEnabled = value;
  52530. },
  52531. enumerable: true,
  52532. configurable: true
  52533. });
  52534. ;
  52535. ;
  52536. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  52537. /**
  52538. * Gets contrast used in the effect.
  52539. */
  52540. get: function () {
  52541. return this.imageProcessingConfiguration.contrast;
  52542. },
  52543. /**
  52544. * Sets contrast used in the effect.
  52545. */
  52546. set: function (value) {
  52547. this.imageProcessingConfiguration.contrast = value;
  52548. },
  52549. enumerable: true,
  52550. configurable: true
  52551. });
  52552. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  52553. /**
  52554. * Gets Vignette stretch size.
  52555. */
  52556. get: function () {
  52557. return this.imageProcessingConfiguration.vignetteStretch;
  52558. },
  52559. /**
  52560. * Sets Vignette stretch size.
  52561. */
  52562. set: function (value) {
  52563. this.imageProcessingConfiguration.vignetteStretch = value;
  52564. },
  52565. enumerable: true,
  52566. configurable: true
  52567. });
  52568. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  52569. /**
  52570. * Gets Vignette centre X Offset.
  52571. */
  52572. get: function () {
  52573. return this.imageProcessingConfiguration.vignetteCentreX;
  52574. },
  52575. /**
  52576. * Sets Vignette centre X Offset.
  52577. */
  52578. set: function (value) {
  52579. this.imageProcessingConfiguration.vignetteCentreX = value;
  52580. },
  52581. enumerable: true,
  52582. configurable: true
  52583. });
  52584. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  52585. /**
  52586. * Gets Vignette centre Y Offset.
  52587. */
  52588. get: function () {
  52589. return this.imageProcessingConfiguration.vignetteCentreY;
  52590. },
  52591. /**
  52592. * Sets Vignette centre Y Offset.
  52593. */
  52594. set: function (value) {
  52595. this.imageProcessingConfiguration.vignetteCentreY = value;
  52596. },
  52597. enumerable: true,
  52598. configurable: true
  52599. });
  52600. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  52601. /**
  52602. * Gets Vignette weight or intensity of the vignette effect.
  52603. */
  52604. get: function () {
  52605. return this.imageProcessingConfiguration.vignetteWeight;
  52606. },
  52607. /**
  52608. * Sets Vignette weight or intensity of the vignette effect.
  52609. */
  52610. set: function (value) {
  52611. this.imageProcessingConfiguration.vignetteWeight = value;
  52612. },
  52613. enumerable: true,
  52614. configurable: true
  52615. });
  52616. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  52617. /**
  52618. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  52619. * if vignetteEnabled is set to true.
  52620. */
  52621. get: function () {
  52622. return this.imageProcessingConfiguration.vignetteColor;
  52623. },
  52624. /**
  52625. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  52626. * if vignetteEnabled is set to true.
  52627. */
  52628. set: function (value) {
  52629. this.imageProcessingConfiguration.vignetteColor = value;
  52630. },
  52631. enumerable: true,
  52632. configurable: true
  52633. });
  52634. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  52635. /**
  52636. * Gets Camera field of view used by the Vignette effect.
  52637. */
  52638. get: function () {
  52639. return this.imageProcessingConfiguration.vignetteCameraFov;
  52640. },
  52641. /**
  52642. * Sets Camera field of view used by the Vignette effect.
  52643. */
  52644. set: function (value) {
  52645. this.imageProcessingConfiguration.vignetteCameraFov = value;
  52646. },
  52647. enumerable: true,
  52648. configurable: true
  52649. });
  52650. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  52651. /**
  52652. * Gets the vignette blend mode allowing different kind of effect.
  52653. */
  52654. get: function () {
  52655. return this.imageProcessingConfiguration.vignetteBlendMode;
  52656. },
  52657. /**
  52658. * Sets the vignette blend mode allowing different kind of effect.
  52659. */
  52660. set: function (value) {
  52661. this.imageProcessingConfiguration.vignetteBlendMode = value;
  52662. },
  52663. enumerable: true,
  52664. configurable: true
  52665. });
  52666. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  52667. /**
  52668. * Gets wether the vignette effect is enabled.
  52669. */
  52670. get: function () {
  52671. return this.imageProcessingConfiguration.vignetteEnabled;
  52672. },
  52673. /**
  52674. * Sets wether the vignette effect is enabled.
  52675. */
  52676. set: function (value) {
  52677. this.imageProcessingConfiguration.vignetteEnabled = value;
  52678. },
  52679. enumerable: true,
  52680. configurable: true
  52681. });
  52682. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  52683. /**
  52684. * Gets wether the input of the processing is in Gamma or Linear Space.
  52685. */
  52686. get: function () {
  52687. return this._fromLinearSpace;
  52688. },
  52689. /**
  52690. * Sets wether the input of the processing is in Gamma or Linear Space.
  52691. */
  52692. set: function (value) {
  52693. if (this._fromLinearSpace === value) {
  52694. return;
  52695. }
  52696. this._fromLinearSpace = value;
  52697. this._updateParameters();
  52698. },
  52699. enumerable: true,
  52700. configurable: true
  52701. });
  52702. ImageProcessingPostProcess.prototype._updateParameters = function () {
  52703. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  52704. this.imageProcessingConfiguration.prepareDefines(this._defines);
  52705. var defines = "";
  52706. for (var define in this._defines) {
  52707. if (this._defines[define]) {
  52708. defines += "#define " + define + ";\r\n";
  52709. }
  52710. }
  52711. var samplers = ["textureSampler"];
  52712. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  52713. var uniforms = ["scale"];
  52714. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  52715. this.updateEffect(defines, uniforms, samplers);
  52716. };
  52717. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  52718. _super.prototype.dispose.call(this, camera);
  52719. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  52720. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  52721. }
  52722. this.imageProcessingConfiguration.applyByPostProcess = false;
  52723. };
  52724. return ImageProcessingPostProcess;
  52725. }(BABYLON.PostProcess));
  52726. __decorate([
  52727. BABYLON.serialize()
  52728. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  52729. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  52730. })(BABYLON || (BABYLON = {}));
  52731. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  52732. var BABYLON;
  52733. (function (BABYLON) {
  52734. var BlurPostProcess = (function (_super) {
  52735. __extends(BlurPostProcess, _super);
  52736. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  52737. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52738. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52739. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  52740. _this.direction = direction;
  52741. _this._packedFloat = false;
  52742. _this.onApplyObservable.add(function (effect) {
  52743. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  52744. });
  52745. _this.kernel = kernel;
  52746. return _this;
  52747. }
  52748. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  52749. /**
  52750. * Gets the length in pixels of the blur sample region
  52751. */
  52752. get: function () {
  52753. return this._idealKernel;
  52754. },
  52755. /**
  52756. * Sets the length in pixels of the blur sample region
  52757. */
  52758. set: function (v) {
  52759. if (this._idealKernel === v) {
  52760. return;
  52761. }
  52762. v = Math.max(v, 1);
  52763. this._idealKernel = v;
  52764. this._kernel = this._nearestBestKernel(v);
  52765. this._updateParameters();
  52766. },
  52767. enumerable: true,
  52768. configurable: true
  52769. });
  52770. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  52771. /**
  52772. * Gets wether or not the blur is unpacking/repacking floats
  52773. */
  52774. get: function () {
  52775. return this._packedFloat;
  52776. },
  52777. /**
  52778. * Sets wether or not the blur needs to unpack/repack floats
  52779. */
  52780. set: function (v) {
  52781. if (this._packedFloat === v) {
  52782. return;
  52783. }
  52784. this._packedFloat = v;
  52785. this._updateParameters();
  52786. },
  52787. enumerable: true,
  52788. configurable: true
  52789. });
  52790. BlurPostProcess.prototype._updateParameters = function () {
  52791. // Generate sampling offsets and weights
  52792. var N = this._kernel;
  52793. var centerIndex = (N - 1) / 2;
  52794. // Generate Gaussian sampling weights over kernel
  52795. var offsets = [];
  52796. var weights = [];
  52797. var totalWeight = 0;
  52798. for (var i = 0; i < N; i++) {
  52799. var u = i / (N - 1);
  52800. var w = this._gaussianWeight(u * 2.0 - 1);
  52801. offsets[i] = (i - centerIndex);
  52802. weights[i] = w;
  52803. totalWeight += w;
  52804. }
  52805. // Normalize weights
  52806. for (var i = 0; i < weights.length; i++) {
  52807. weights[i] /= totalWeight;
  52808. }
  52809. // Optimize: combine samples to take advantage of hardware linear sampling
  52810. // Walk from left to center, combining pairs (symmetrically)
  52811. var linearSamplingWeights = [];
  52812. var linearSamplingOffsets = [];
  52813. var linearSamplingMap = [];
  52814. for (var i = 0; i <= centerIndex; i += 2) {
  52815. var j = Math.min(i + 1, Math.floor(centerIndex));
  52816. var singleCenterSample = i === j;
  52817. if (singleCenterSample) {
  52818. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  52819. }
  52820. else {
  52821. var sharedCell = j === centerIndex;
  52822. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  52823. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  52824. if (offsetLinear === 0) {
  52825. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  52826. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  52827. }
  52828. else {
  52829. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  52830. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  52831. }
  52832. }
  52833. }
  52834. for (var i = 0; i < linearSamplingMap.length; i++) {
  52835. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  52836. linearSamplingWeights[i] = linearSamplingMap[i].w;
  52837. }
  52838. // Replace with optimized
  52839. offsets = linearSamplingOffsets;
  52840. weights = linearSamplingWeights;
  52841. // Generate shaders
  52842. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  52843. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  52844. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  52845. var defines = "";
  52846. for (var i = 0; i < varyingCount; i++) {
  52847. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  52848. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  52849. }
  52850. var depCount = 0;
  52851. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  52852. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  52853. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  52854. depCount++;
  52855. }
  52856. if (this.packedFloat) {
  52857. defines += "#define PACKEDFLOAT 1";
  52858. }
  52859. this.updateEffect(defines, null, null, {
  52860. varyingCount: varyingCount,
  52861. depCount: depCount
  52862. });
  52863. };
  52864. /**
  52865. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  52866. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  52867. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  52868. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  52869. * The gaps between physical kernels are compensated for in the weighting of the samples
  52870. * @param idealKernel Ideal blur kernel.
  52871. * @return Nearest best kernel.
  52872. */
  52873. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  52874. var v = Math.round(idealKernel);
  52875. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  52876. var k = _a[_i];
  52877. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  52878. return Math.max(k, 3);
  52879. }
  52880. }
  52881. return Math.max(v, 3);
  52882. };
  52883. /**
  52884. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  52885. * @param x The point on the Gaussian distribution to sample.
  52886. * @return the value of the Gaussian function at x.
  52887. */
  52888. BlurPostProcess.prototype._gaussianWeight = function (x) {
  52889. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  52890. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  52891. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  52892. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  52893. // truncated at around 1.3% of peak strength.
  52894. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  52895. var sigma = (1 / 3);
  52896. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  52897. var exponent = -((x * x) / (2.0 * sigma * sigma));
  52898. var weight = (1.0 / denominator) * Math.exp(exponent);
  52899. return weight;
  52900. };
  52901. /**
  52902. * Generates a string that can be used as a floating point number in GLSL.
  52903. * @param x Value to print.
  52904. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  52905. * @return GLSL float string.
  52906. */
  52907. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  52908. if (decimalFigures === void 0) { decimalFigures = 8; }
  52909. return x.toFixed(decimalFigures).replace(/0+$/, '');
  52910. };
  52911. return BlurPostProcess;
  52912. }(BABYLON.PostProcess));
  52913. BABYLON.BlurPostProcess = BlurPostProcess;
  52914. })(BABYLON || (BABYLON = {}));
  52915. //# sourceMappingURL=babylon.blurPostProcess.js.map
  52916. /// <reference path="..\babylon.node.ts" />
  52917. var BABYLON;
  52918. (function (BABYLON) {
  52919. var Bone = (function (_super) {
  52920. __extends(Bone, _super);
  52921. function Bone(name, skeleton, parentBone, matrix, restPose) {
  52922. if (parentBone === void 0) { parentBone = null; }
  52923. var _this = _super.call(this, name, skeleton.getScene()) || this;
  52924. _this.name = name;
  52925. _this.children = new Array();
  52926. _this.animations = new Array();
  52927. _this._worldTransform = new BABYLON.Matrix();
  52928. _this._absoluteTransform = new BABYLON.Matrix();
  52929. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  52930. _this._scaleMatrix = BABYLON.Matrix.Identity();
  52931. _this._scaleVector = BABYLON.Vector3.One();
  52932. _this._negateScaleChildren = BABYLON.Vector3.One();
  52933. _this._scalingDeterminant = 1;
  52934. _this._skeleton = skeleton;
  52935. _this._localMatrix = matrix ? matrix : BABYLON.Matrix.Identity();
  52936. _this._baseMatrix = _this._localMatrix.clone();
  52937. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  52938. skeleton.bones.push(_this);
  52939. _this.setParent(parentBone, false);
  52940. _this._updateDifferenceMatrix();
  52941. return _this;
  52942. }
  52943. Object.defineProperty(Bone.prototype, "_matrix", {
  52944. get: function () {
  52945. return this._localMatrix;
  52946. },
  52947. set: function (val) {
  52948. if (this._localMatrix) {
  52949. this._localMatrix.copyFrom(val);
  52950. }
  52951. else {
  52952. this._localMatrix = val;
  52953. }
  52954. },
  52955. enumerable: true,
  52956. configurable: true
  52957. });
  52958. // Members
  52959. Bone.prototype.getSkeleton = function () {
  52960. return this._skeleton;
  52961. };
  52962. Bone.prototype.getParent = function () {
  52963. return this._parent;
  52964. };
  52965. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  52966. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  52967. if (this._parent === parent) {
  52968. return;
  52969. }
  52970. if (this._parent) {
  52971. var index = this._parent.children.indexOf(this);
  52972. if (index !== -1) {
  52973. this._parent.children.splice(index);
  52974. }
  52975. }
  52976. this._parent = parent;
  52977. if (this._parent) {
  52978. this._parent.children.push(this);
  52979. }
  52980. if (updateDifferenceMatrix) {
  52981. this._updateDifferenceMatrix();
  52982. }
  52983. };
  52984. Bone.prototype.getLocalMatrix = function () {
  52985. return this._localMatrix;
  52986. };
  52987. Bone.prototype.getBaseMatrix = function () {
  52988. return this._baseMatrix;
  52989. };
  52990. Bone.prototype.getRestPose = function () {
  52991. return this._restPose;
  52992. };
  52993. Bone.prototype.returnToRest = function () {
  52994. this.updateMatrix(this._restPose.clone());
  52995. };
  52996. Bone.prototype.getWorldMatrix = function () {
  52997. return this._worldTransform;
  52998. };
  52999. Bone.prototype.getInvertedAbsoluteTransform = function () {
  53000. return this._invertedAbsoluteTransform;
  53001. };
  53002. Bone.prototype.getAbsoluteTransform = function () {
  53003. return this._absoluteTransform;
  53004. };
  53005. Object.defineProperty(Bone.prototype, "position", {
  53006. // Properties (matches AbstractMesh properties)
  53007. get: function () {
  53008. return this.getPosition();
  53009. },
  53010. set: function (newPosition) {
  53011. this.setPosition(newPosition);
  53012. },
  53013. enumerable: true,
  53014. configurable: true
  53015. });
  53016. Object.defineProperty(Bone.prototype, "rotation", {
  53017. get: function () {
  53018. return this.getRotation();
  53019. },
  53020. set: function (newRotation) {
  53021. this.setRotation(newRotation);
  53022. },
  53023. enumerable: true,
  53024. configurable: true
  53025. });
  53026. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  53027. get: function () {
  53028. return this.getRotationQuaternion();
  53029. },
  53030. set: function (newRotation) {
  53031. this.setRotationQuaternion(newRotation);
  53032. },
  53033. enumerable: true,
  53034. configurable: true
  53035. });
  53036. Object.defineProperty(Bone.prototype, "scaling", {
  53037. get: function () {
  53038. return this.getScale();
  53039. },
  53040. set: function (newScaling) {
  53041. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  53042. },
  53043. enumerable: true,
  53044. configurable: true
  53045. });
  53046. // Methods
  53047. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  53048. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  53049. this._baseMatrix = matrix.clone();
  53050. this._localMatrix = matrix.clone();
  53051. this._skeleton._markAsDirty();
  53052. if (updateDifferenceMatrix) {
  53053. this._updateDifferenceMatrix();
  53054. }
  53055. };
  53056. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  53057. if (!rootMatrix) {
  53058. rootMatrix = this._baseMatrix;
  53059. }
  53060. if (this._parent) {
  53061. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  53062. }
  53063. else {
  53064. this._absoluteTransform.copyFrom(rootMatrix);
  53065. }
  53066. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  53067. for (var index = 0; index < this.children.length; index++) {
  53068. this.children[index]._updateDifferenceMatrix();
  53069. }
  53070. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  53071. };
  53072. Bone.prototype.markAsDirty = function () {
  53073. this._currentRenderId++;
  53074. this._skeleton._markAsDirty();
  53075. };
  53076. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  53077. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  53078. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  53079. // all animation may be coming from a library skeleton, so may need to create animation
  53080. if (this.animations.length === 0) {
  53081. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  53082. this.animations[0].setKeys([]);
  53083. }
  53084. // get animation info / verify there is such a range from the source bone
  53085. var sourceRange = source.animations[0].getRange(rangeName);
  53086. if (!sourceRange) {
  53087. return false;
  53088. }
  53089. var from = sourceRange.from;
  53090. var to = sourceRange.to;
  53091. var sourceKeys = source.animations[0].getKeys();
  53092. // rescaling prep
  53093. var sourceBoneLength = source.length;
  53094. var sourceParent = source.getParent();
  53095. var parent = this.getParent();
  53096. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  53097. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  53098. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  53099. var destKeys = this.animations[0].getKeys();
  53100. // loop vars declaration
  53101. var orig;
  53102. var origTranslation;
  53103. var mat;
  53104. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  53105. orig = sourceKeys[key];
  53106. if (orig.frame >= from && orig.frame <= to) {
  53107. if (rescaleAsRequired) {
  53108. mat = orig.value.clone();
  53109. // scale based on parent ratio, when bone has parent
  53110. if (parentScalingReqd) {
  53111. origTranslation = mat.getTranslation();
  53112. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  53113. // scale based on skeleton dimension ratio when root bone, and value is passed
  53114. }
  53115. else if (dimensionsScalingReqd) {
  53116. origTranslation = mat.getTranslation();
  53117. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  53118. // use original when root bone, and no data for skelDimensionsRatio
  53119. }
  53120. else {
  53121. mat = orig.value;
  53122. }
  53123. }
  53124. else {
  53125. mat = orig.value;
  53126. }
  53127. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  53128. }
  53129. }
  53130. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  53131. return true;
  53132. };
  53133. /**
  53134. * Translate the bone in local or world space.
  53135. * @param vec The amount to translate the bone.
  53136. * @param space The space that the translation is in.
  53137. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53138. */
  53139. Bone.prototype.translate = function (vec, space, mesh) {
  53140. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53141. var lm = this.getLocalMatrix();
  53142. if (space == BABYLON.Space.LOCAL) {
  53143. lm.m[12] += vec.x;
  53144. lm.m[13] += vec.y;
  53145. lm.m[14] += vec.z;
  53146. }
  53147. else {
  53148. var wm;
  53149. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53150. if (mesh) {
  53151. wm = mesh.getWorldMatrix();
  53152. }
  53153. this._skeleton.computeAbsoluteTransforms();
  53154. var tmat = Bone._tmpMats[0];
  53155. var tvec = Bone._tmpVecs[0];
  53156. if (mesh) {
  53157. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53158. tmat.multiplyToRef(wm, tmat);
  53159. }
  53160. else {
  53161. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53162. }
  53163. tmat.m[12] = 0;
  53164. tmat.m[13] = 0;
  53165. tmat.m[14] = 0;
  53166. tmat.invert();
  53167. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  53168. lm.m[12] += tvec.x;
  53169. lm.m[13] += tvec.y;
  53170. lm.m[14] += tvec.z;
  53171. }
  53172. this.markAsDirty();
  53173. };
  53174. /**
  53175. * Set the postion of the bone in local or world space.
  53176. * @param position The position to set the bone.
  53177. * @param space The space that the position is in.
  53178. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53179. */
  53180. Bone.prototype.setPosition = function (position, space, mesh) {
  53181. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53182. var lm = this.getLocalMatrix();
  53183. if (space == BABYLON.Space.LOCAL) {
  53184. lm.m[12] = position.x;
  53185. lm.m[13] = position.y;
  53186. lm.m[14] = position.z;
  53187. }
  53188. else {
  53189. var wm;
  53190. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53191. if (mesh) {
  53192. wm = mesh.getWorldMatrix();
  53193. }
  53194. this._skeleton.computeAbsoluteTransforms();
  53195. var tmat = Bone._tmpMats[0];
  53196. var vec = Bone._tmpVecs[0];
  53197. if (mesh) {
  53198. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53199. tmat.multiplyToRef(wm, tmat);
  53200. }
  53201. else {
  53202. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53203. }
  53204. tmat.invert();
  53205. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  53206. lm.m[12] = vec.x;
  53207. lm.m[13] = vec.y;
  53208. lm.m[14] = vec.z;
  53209. }
  53210. this.markAsDirty();
  53211. };
  53212. /**
  53213. * Set the absolute postion of the bone (world space).
  53214. * @param position The position to set the bone.
  53215. * @param mesh The mesh that this bone is attached to.
  53216. */
  53217. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  53218. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  53219. };
  53220. /**
  53221. * Set the scale of the bone on the x, y and z axes.
  53222. * @param x The scale of the bone on the x axis.
  53223. * @param x The scale of the bone on the y axis.
  53224. * @param z The scale of the bone on the z axis.
  53225. * @param scaleChildren Set this to true if children of the bone should be scaled.
  53226. */
  53227. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  53228. if (scaleChildren === void 0) { scaleChildren = false; }
  53229. if (this.animations[0] && !this.animations[0].isStopped()) {
  53230. if (!scaleChildren) {
  53231. this._negateScaleChildren.x = 1 / x;
  53232. this._negateScaleChildren.y = 1 / y;
  53233. this._negateScaleChildren.z = 1 / z;
  53234. }
  53235. this._syncScaleVector();
  53236. }
  53237. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  53238. };
  53239. /**
  53240. * Scale the bone on the x, y and z axes.
  53241. * @param x The amount to scale the bone on the x axis.
  53242. * @param x The amount to scale the bone on the y axis.
  53243. * @param z The amount to scale the bone on the z axis.
  53244. * @param scaleChildren Set this to true if children of the bone should be scaled.
  53245. */
  53246. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  53247. if (scaleChildren === void 0) { scaleChildren = false; }
  53248. var locMat = this.getLocalMatrix();
  53249. var origLocMat = Bone._tmpMats[0];
  53250. origLocMat.copyFrom(locMat);
  53251. var origLocMatInv = Bone._tmpMats[1];
  53252. origLocMatInv.copyFrom(origLocMat);
  53253. origLocMatInv.invert();
  53254. var scaleMat = Bone._tmpMats[2];
  53255. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  53256. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  53257. this._scaleVector.x *= x;
  53258. this._scaleVector.y *= y;
  53259. this._scaleVector.z *= z;
  53260. locMat.multiplyToRef(origLocMatInv, locMat);
  53261. locMat.multiplyToRef(scaleMat, locMat);
  53262. locMat.multiplyToRef(origLocMat, locMat);
  53263. var parent = this.getParent();
  53264. if (parent) {
  53265. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  53266. }
  53267. else {
  53268. this.getAbsoluteTransform().copyFrom(locMat);
  53269. }
  53270. var len = this.children.length;
  53271. scaleMat.invert();
  53272. for (var i = 0; i < len; i++) {
  53273. var child = this.children[i];
  53274. var cm = child.getLocalMatrix();
  53275. cm.multiplyToRef(scaleMat, cm);
  53276. var lm = child.getLocalMatrix();
  53277. lm.m[12] *= x;
  53278. lm.m[13] *= y;
  53279. lm.m[14] *= z;
  53280. }
  53281. this.computeAbsoluteTransforms();
  53282. if (scaleChildren) {
  53283. for (var i = 0; i < len; i++) {
  53284. this.children[i].scale(x, y, z, scaleChildren);
  53285. }
  53286. }
  53287. this.markAsDirty();
  53288. };
  53289. /**
  53290. * Set the yaw, pitch, and roll of the bone in local or world space.
  53291. * @param yaw The rotation of the bone on the y axis.
  53292. * @param pitch The rotation of the bone on the x axis.
  53293. * @param roll The rotation of the bone on the z axis.
  53294. * @param space The space that the axes of rotation are in.
  53295. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53296. */
  53297. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  53298. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53299. var rotMat = Bone._tmpMats[0];
  53300. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  53301. var rotMatInv = Bone._tmpMats[1];
  53302. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53303. rotMatInv.multiplyToRef(rotMat, rotMat);
  53304. this._rotateWithMatrix(rotMat, space, mesh);
  53305. };
  53306. /**
  53307. * Rotate the bone on an axis in local or world space.
  53308. * @param axis The axis to rotate the bone on.
  53309. * @param amount The amount to rotate the bone.
  53310. * @param space The space that the axis is in.
  53311. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53312. */
  53313. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  53314. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53315. var rmat = Bone._tmpMats[0];
  53316. rmat.m[12] = 0;
  53317. rmat.m[13] = 0;
  53318. rmat.m[14] = 0;
  53319. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  53320. this._rotateWithMatrix(rmat, space, mesh);
  53321. };
  53322. /**
  53323. * Set the rotation of the bone to a particular axis angle in local or world space.
  53324. * @param axis The axis to rotate the bone on.
  53325. * @param angle The angle that the bone should be rotated to.
  53326. * @param space The space that the axis is in.
  53327. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53328. */
  53329. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  53330. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53331. var rotMat = Bone._tmpMats[0];
  53332. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  53333. var rotMatInv = Bone._tmpMats[1];
  53334. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53335. rotMatInv.multiplyToRef(rotMat, rotMat);
  53336. this._rotateWithMatrix(rotMat, space, mesh);
  53337. };
  53338. /**
  53339. * Set the euler rotation of the bone in local of world space.
  53340. * @param rotation The euler rotation that the bone should be set to.
  53341. * @param space The space that the rotation is in.
  53342. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53343. */
  53344. Bone.prototype.setRotation = function (rotation, space, mesh) {
  53345. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53346. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  53347. };
  53348. /**
  53349. * Set the quaternion rotation of the bone in local of world space.
  53350. * @param quat The quaternion rotation that the bone should be set to.
  53351. * @param space The space that the rotation is in.
  53352. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53353. */
  53354. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  53355. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53356. var rotMatInv = Bone._tmpMats[0];
  53357. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53358. var rotMat = Bone._tmpMats[1];
  53359. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  53360. rotMatInv.multiplyToRef(rotMat, rotMat);
  53361. this._rotateWithMatrix(rotMat, space, mesh);
  53362. };
  53363. /**
  53364. * Set the rotation matrix of the bone in local of world space.
  53365. * @param rotMat The rotation matrix that the bone should be set to.
  53366. * @param space The space that the rotation is in.
  53367. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53368. */
  53369. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  53370. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53371. var rotMatInv = Bone._tmpMats[0];
  53372. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53373. var rotMat2 = Bone._tmpMats[1];
  53374. rotMat2.copyFrom(rotMat);
  53375. rotMatInv.multiplyToRef(rotMat, rotMat2);
  53376. this._rotateWithMatrix(rotMat2, space, mesh);
  53377. };
  53378. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  53379. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53380. var lmat = this.getLocalMatrix();
  53381. var lx = lmat.m[12];
  53382. var ly = lmat.m[13];
  53383. var lz = lmat.m[14];
  53384. var parent = this.getParent();
  53385. var parentScale = Bone._tmpMats[3];
  53386. var parentScaleInv = Bone._tmpMats[4];
  53387. if (parent) {
  53388. if (space == BABYLON.Space.WORLD) {
  53389. if (mesh) {
  53390. parentScale.copyFrom(mesh.getWorldMatrix());
  53391. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  53392. }
  53393. else {
  53394. parentScale.copyFrom(parent.getAbsoluteTransform());
  53395. }
  53396. }
  53397. else {
  53398. parentScale = parent._scaleMatrix;
  53399. }
  53400. parentScaleInv.copyFrom(parentScale);
  53401. parentScaleInv.invert();
  53402. lmat.multiplyToRef(parentScale, lmat);
  53403. lmat.multiplyToRef(rmat, lmat);
  53404. lmat.multiplyToRef(parentScaleInv, lmat);
  53405. }
  53406. else {
  53407. if (space == BABYLON.Space.WORLD && mesh) {
  53408. parentScale.copyFrom(mesh.getWorldMatrix());
  53409. parentScaleInv.copyFrom(parentScale);
  53410. parentScaleInv.invert();
  53411. lmat.multiplyToRef(parentScale, lmat);
  53412. lmat.multiplyToRef(rmat, lmat);
  53413. lmat.multiplyToRef(parentScaleInv, lmat);
  53414. }
  53415. else {
  53416. lmat.multiplyToRef(rmat, lmat);
  53417. }
  53418. }
  53419. lmat.m[12] = lx;
  53420. lmat.m[13] = ly;
  53421. lmat.m[14] = lz;
  53422. this.computeAbsoluteTransforms();
  53423. this.markAsDirty();
  53424. };
  53425. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  53426. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53427. if (space == BABYLON.Space.WORLD) {
  53428. var scaleMatrix = Bone._tmpMats[2];
  53429. scaleMatrix.copyFrom(this._scaleMatrix);
  53430. rotMatInv.copyFrom(this.getAbsoluteTransform());
  53431. if (mesh) {
  53432. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  53433. var meshScale = Bone._tmpMats[3];
  53434. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  53435. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  53436. }
  53437. rotMatInv.invert();
  53438. scaleMatrix.m[0] *= this._scalingDeterminant;
  53439. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  53440. }
  53441. else {
  53442. rotMatInv.copyFrom(this.getLocalMatrix());
  53443. rotMatInv.invert();
  53444. var scaleMatrix = Bone._tmpMats[2];
  53445. scaleMatrix.copyFrom(this._scaleMatrix);
  53446. if (this._parent) {
  53447. var pscaleMatrix = Bone._tmpMats[3];
  53448. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  53449. pscaleMatrix.invert();
  53450. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  53451. }
  53452. else {
  53453. scaleMatrix.m[0] *= this._scalingDeterminant;
  53454. }
  53455. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  53456. }
  53457. };
  53458. /**
  53459. * Get the scale of the bone
  53460. * @returns the scale of the bone
  53461. */
  53462. Bone.prototype.getScale = function () {
  53463. return this._scaleVector.clone();
  53464. };
  53465. /**
  53466. * Copy the scale of the bone to a vector3.
  53467. * @param result The vector3 to copy the scale to
  53468. */
  53469. Bone.prototype.getScaleToRef = function (result) {
  53470. result.copyFrom(this._scaleVector);
  53471. };
  53472. /**
  53473. * Get the position of the bone in local or world space.
  53474. * @param space The space that the returned position is in.
  53475. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53476. * @returns The position of the bone
  53477. */
  53478. Bone.prototype.getPosition = function (space, mesh) {
  53479. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53480. var pos = BABYLON.Vector3.Zero();
  53481. this.getPositionToRef(space, mesh, pos);
  53482. return pos;
  53483. };
  53484. /**
  53485. * Copy the position of the bone to a vector3 in local or world space.
  53486. * @param space The space that the returned position is in.
  53487. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53488. * @param result The vector3 to copy the position to.
  53489. */
  53490. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  53491. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53492. if (space == BABYLON.Space.LOCAL) {
  53493. var lm = this.getLocalMatrix();
  53494. result.x = lm.m[12];
  53495. result.y = lm.m[13];
  53496. result.z = lm.m[14];
  53497. }
  53498. else {
  53499. var wm;
  53500. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53501. if (mesh) {
  53502. wm = mesh.getWorldMatrix();
  53503. }
  53504. this._skeleton.computeAbsoluteTransforms();
  53505. var tmat = Bone._tmpMats[0];
  53506. if (mesh) {
  53507. tmat.copyFrom(this.getAbsoluteTransform());
  53508. tmat.multiplyToRef(wm, tmat);
  53509. }
  53510. else {
  53511. tmat = this.getAbsoluteTransform();
  53512. }
  53513. result.x = tmat.m[12];
  53514. result.y = tmat.m[13];
  53515. result.z = tmat.m[14];
  53516. }
  53517. };
  53518. /**
  53519. * Get the absolute position of the bone (world space).
  53520. * @param mesh The mesh that this bone is attached to.
  53521. * @returns The absolute position of the bone
  53522. */
  53523. Bone.prototype.getAbsolutePosition = function (mesh) {
  53524. var pos = BABYLON.Vector3.Zero();
  53525. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  53526. return pos;
  53527. };
  53528. /**
  53529. * Copy the absolute position of the bone (world space) to the result param.
  53530. * @param mesh The mesh that this bone is attached to.
  53531. * @param result The vector3 to copy the absolute position to.
  53532. */
  53533. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  53534. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  53535. };
  53536. /**
  53537. * Compute the absolute transforms of this bone and its children.
  53538. */
  53539. Bone.prototype.computeAbsoluteTransforms = function () {
  53540. if (this._parent) {
  53541. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  53542. }
  53543. else {
  53544. this._absoluteTransform.copyFrom(this._localMatrix);
  53545. var poseMatrix = this._skeleton.getPoseMatrix();
  53546. if (poseMatrix) {
  53547. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  53548. }
  53549. }
  53550. var children = this.children;
  53551. var len = children.length;
  53552. for (var i = 0; i < len; i++) {
  53553. children[i].computeAbsoluteTransforms();
  53554. }
  53555. };
  53556. Bone.prototype._syncScaleVector = function () {
  53557. var lm = this.getLocalMatrix();
  53558. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  53559. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  53560. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  53561. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  53562. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  53563. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  53564. this._scaleVector.x = xs * Math.sqrt(xsq);
  53565. this._scaleVector.y = ys * Math.sqrt(ysq);
  53566. this._scaleVector.z = zs * Math.sqrt(zsq);
  53567. if (this._parent) {
  53568. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  53569. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  53570. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  53571. }
  53572. 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);
  53573. };
  53574. /**
  53575. * Get the world direction from an axis that is in the local space of the bone.
  53576. * @param localAxis The local direction that is used to compute the world direction.
  53577. * @param mesh The mesh that this bone is attached to.
  53578. * @returns The world direction
  53579. */
  53580. Bone.prototype.getDirection = function (localAxis, mesh) {
  53581. var result = BABYLON.Vector3.Zero();
  53582. this.getDirectionToRef(localAxis, mesh, result);
  53583. return result;
  53584. };
  53585. /**
  53586. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  53587. * @param localAxis The local direction that is used to compute the world direction.
  53588. * @param mesh The mesh that this bone is attached to.
  53589. * @param result The vector3 that the world direction will be copied to.
  53590. */
  53591. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  53592. var wm;
  53593. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53594. if (mesh) {
  53595. wm = mesh.getWorldMatrix();
  53596. }
  53597. this._skeleton.computeAbsoluteTransforms();
  53598. var mat = Bone._tmpMats[0];
  53599. mat.copyFrom(this.getAbsoluteTransform());
  53600. if (mesh) {
  53601. mat.multiplyToRef(wm, mat);
  53602. }
  53603. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  53604. result.normalize();
  53605. };
  53606. /**
  53607. * Get the euler rotation 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 euler rotation
  53611. */
  53612. Bone.prototype.getRotation = function (space, mesh) {
  53613. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53614. var result = BABYLON.Vector3.Zero();
  53615. this.getRotationToRef(space, mesh, result);
  53616. return result;
  53617. };
  53618. /**
  53619. * Copy the euler rotation of the bone to a vector3. 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 vector3 that the rotation should be copied to.
  53623. */
  53624. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  53625. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53626. var quat = Bone._tmpQuat;
  53627. this.getRotationQuaternionToRef(space, mesh, quat);
  53628. quat.toEulerAnglesToRef(result);
  53629. };
  53630. /**
  53631. * Get the quaternion rotation of the bone in either local or world space.
  53632. * @param space The space that the rotation should be in.
  53633. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53634. * @returns The quaternion rotation
  53635. */
  53636. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  53637. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53638. var result = BABYLON.Quaternion.Identity();
  53639. this.getRotationQuaternionToRef(space, mesh, result);
  53640. return result;
  53641. };
  53642. /**
  53643. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  53644. * @param space The space that the rotation should be in.
  53645. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53646. * @param result The quaternion that the rotation should be copied to.
  53647. */
  53648. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  53649. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53650. if (space == BABYLON.Space.LOCAL) {
  53651. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  53652. }
  53653. else {
  53654. var mat = Bone._tmpMats[0];
  53655. var amat = this.getAbsoluteTransform();
  53656. if (mesh) {
  53657. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  53658. }
  53659. else {
  53660. mat.copyFrom(amat);
  53661. }
  53662. mat.m[0] *= this._scalingDeterminant;
  53663. mat.m[1] *= this._scalingDeterminant;
  53664. mat.m[2] *= this._scalingDeterminant;
  53665. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  53666. }
  53667. };
  53668. /**
  53669. * Get the rotation matrix of the bone in local or world space.
  53670. * @param space The space that the rotation should be in.
  53671. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53672. * @returns The rotation matrix
  53673. */
  53674. Bone.prototype.getRotationMatrix = function (space, mesh) {
  53675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53676. var result = BABYLON.Matrix.Identity();
  53677. this.getRotationMatrixToRef(space, mesh, result);
  53678. return result;
  53679. };
  53680. /**
  53681. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  53682. * @param space The space that the rotation should be in.
  53683. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53684. * @param result The quaternion that the rotation should be copied to.
  53685. */
  53686. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  53687. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53688. if (space == BABYLON.Space.LOCAL) {
  53689. this.getLocalMatrix().getRotationMatrixToRef(result);
  53690. }
  53691. else {
  53692. var mat = Bone._tmpMats[0];
  53693. var amat = this.getAbsoluteTransform();
  53694. if (mesh) {
  53695. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  53696. }
  53697. else {
  53698. mat.copyFrom(amat);
  53699. }
  53700. mat.m[0] *= this._scalingDeterminant;
  53701. mat.m[1] *= this._scalingDeterminant;
  53702. mat.m[2] *= this._scalingDeterminant;
  53703. mat.getRotationMatrixToRef(result);
  53704. }
  53705. };
  53706. /**
  53707. * Get the world position of a point that is in the local space of the bone.
  53708. * @param position The local position
  53709. * @param mesh The mesh that this bone is attached to.
  53710. * @returns The world position
  53711. */
  53712. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  53713. var result = BABYLON.Vector3.Zero();
  53714. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  53715. return result;
  53716. };
  53717. /**
  53718. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  53719. * @param position The local position
  53720. * @param mesh The mesh that this bone is attached to.
  53721. * @param result The vector3 that the world position should be copied to.
  53722. */
  53723. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  53724. var wm;
  53725. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53726. if (mesh) {
  53727. wm = mesh.getWorldMatrix();
  53728. }
  53729. this._skeleton.computeAbsoluteTransforms();
  53730. var tmat = Bone._tmpMats[0];
  53731. if (mesh) {
  53732. tmat.copyFrom(this.getAbsoluteTransform());
  53733. tmat.multiplyToRef(wm, tmat);
  53734. }
  53735. else {
  53736. tmat = this.getAbsoluteTransform();
  53737. }
  53738. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  53739. };
  53740. /**
  53741. * Get the local position of a point that is in world space.
  53742. * @param position The world position
  53743. * @param mesh The mesh that this bone is attached to.
  53744. * @returns The local position
  53745. */
  53746. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  53747. var result = BABYLON.Vector3.Zero();
  53748. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  53749. return result;
  53750. };
  53751. /**
  53752. * Get the local position of a point that is in world space and copy it to the result param.
  53753. * @param position The world position
  53754. * @param mesh The mesh that this bone is attached to.
  53755. * @param result The vector3 that the local position should be copied to.
  53756. */
  53757. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  53758. var wm;
  53759. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53760. if (mesh) {
  53761. wm = mesh.getWorldMatrix();
  53762. }
  53763. this._skeleton.computeAbsoluteTransforms();
  53764. var tmat = Bone._tmpMats[0];
  53765. tmat.copyFrom(this.getAbsoluteTransform());
  53766. if (mesh) {
  53767. tmat.multiplyToRef(wm, tmat);
  53768. }
  53769. tmat.invert();
  53770. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  53771. };
  53772. return Bone;
  53773. }(BABYLON.Node));
  53774. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  53775. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  53776. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  53777. BABYLON.Bone = Bone;
  53778. })(BABYLON || (BABYLON = {}));
  53779. //# sourceMappingURL=babylon.bone.js.map
  53780. var BABYLON;
  53781. (function (BABYLON) {
  53782. var BoneIKController = (function () {
  53783. function BoneIKController(mesh, bone, options) {
  53784. this.targetPosition = BABYLON.Vector3.Zero();
  53785. this.poleTargetPosition = BABYLON.Vector3.Zero();
  53786. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  53787. this.poleAngle = 0;
  53788. this.slerpAmount = 1;
  53789. this._bone1Quat = BABYLON.Quaternion.Identity();
  53790. this._bone1Mat = BABYLON.Matrix.Identity();
  53791. this._bone2Ang = Math.PI;
  53792. this._maxAngle = Math.PI;
  53793. this._rightHandedSystem = false;
  53794. this._bendAxis = BABYLON.Vector3.Right();
  53795. this._slerping = false;
  53796. this._adjustRoll = 0;
  53797. this._bone2 = bone;
  53798. this._bone1 = bone.getParent();
  53799. this.mesh = mesh;
  53800. var bonePos = bone.getPosition();
  53801. if (bone.getAbsoluteTransform().determinant() > 0) {
  53802. this._rightHandedSystem = true;
  53803. this._bendAxis.x = 0;
  53804. this._bendAxis.y = 0;
  53805. this._bendAxis.z = -1;
  53806. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  53807. this._adjustRoll = Math.PI * .5;
  53808. this._bendAxis.z = 1;
  53809. }
  53810. }
  53811. if (this._bone1.length) {
  53812. var boneScale1 = this._bone1.getScale();
  53813. var boneScale2 = this._bone2.getScale();
  53814. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  53815. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  53816. }
  53817. else if (this._bone1.children[0]) {
  53818. mesh.computeWorldMatrix(true);
  53819. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  53820. var pos2 = this._bone2.getAbsolutePosition(mesh);
  53821. var pos3 = this._bone1.getAbsolutePosition(mesh);
  53822. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  53823. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  53824. }
  53825. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  53826. this.maxAngle = Math.PI;
  53827. if (options) {
  53828. if (options.targetMesh) {
  53829. this.targetMesh = options.targetMesh;
  53830. this.targetMesh.computeWorldMatrix(true);
  53831. }
  53832. if (options.poleTargetMesh) {
  53833. this.poleTargetMesh = options.poleTargetMesh;
  53834. this.poleTargetMesh.computeWorldMatrix(true);
  53835. }
  53836. else if (options.poleTargetBone) {
  53837. this.poleTargetBone = options.poleTargetBone;
  53838. }
  53839. else if (this._bone1.getParent()) {
  53840. this.poleTargetBone = this._bone1.getParent();
  53841. }
  53842. if (options.poleTargetLocalOffset) {
  53843. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  53844. }
  53845. if (options.poleAngle) {
  53846. this.poleAngle = options.poleAngle;
  53847. }
  53848. if (options.bendAxis) {
  53849. this._bendAxis.copyFrom(options.bendAxis);
  53850. }
  53851. if (options.maxAngle) {
  53852. this.maxAngle = options.maxAngle;
  53853. }
  53854. if (options.slerpAmount) {
  53855. this.slerpAmount = options.slerpAmount;
  53856. }
  53857. }
  53858. }
  53859. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  53860. get: function () {
  53861. return this._maxAngle;
  53862. },
  53863. set: function (value) {
  53864. this._setMaxAngle(value);
  53865. },
  53866. enumerable: true,
  53867. configurable: true
  53868. });
  53869. BoneIKController.prototype._setMaxAngle = function (ang) {
  53870. if (ang < 0) {
  53871. ang = 0;
  53872. }
  53873. if (ang > Math.PI || ang == undefined) {
  53874. ang = Math.PI;
  53875. }
  53876. this._maxAngle = ang;
  53877. var a = this._bone1Length;
  53878. var b = this._bone2Length;
  53879. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  53880. };
  53881. BoneIKController.prototype.update = function () {
  53882. var bone1 = this._bone1;
  53883. var target = this.targetPosition;
  53884. var poleTarget = this.poleTargetPosition;
  53885. var mat1 = BoneIKController._tmpMats[0];
  53886. var mat2 = BoneIKController._tmpMats[1];
  53887. if (this.targetMesh) {
  53888. target.copyFrom(this.targetMesh.getAbsolutePosition());
  53889. }
  53890. if (this.poleTargetBone) {
  53891. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  53892. }
  53893. else if (this.poleTargetMesh) {
  53894. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  53895. }
  53896. var bonePos = BoneIKController._tmpVecs[0];
  53897. var zaxis = BoneIKController._tmpVecs[1];
  53898. var xaxis = BoneIKController._tmpVecs[2];
  53899. var yaxis = BoneIKController._tmpVecs[3];
  53900. var upAxis = BoneIKController._tmpVecs[4];
  53901. var _tmpQuat = BoneIKController._tmpQuat;
  53902. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  53903. poleTarget.subtractToRef(bonePos, upAxis);
  53904. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  53905. upAxis.y = 1;
  53906. }
  53907. else {
  53908. upAxis.normalize();
  53909. }
  53910. target.subtractToRef(bonePos, yaxis);
  53911. yaxis.normalize();
  53912. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  53913. zaxis.normalize();
  53914. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  53915. xaxis.normalize();
  53916. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  53917. var a = this._bone1Length;
  53918. var b = this._bone2Length;
  53919. var c = BABYLON.Vector3.Distance(bonePos, target);
  53920. if (this._maxReach > 0) {
  53921. c = Math.min(this._maxReach, c);
  53922. }
  53923. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  53924. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  53925. if (acosa > 1) {
  53926. acosa = 1;
  53927. }
  53928. if (acosb > 1) {
  53929. acosb = 1;
  53930. }
  53931. if (acosa < -1) {
  53932. acosa = -1;
  53933. }
  53934. if (acosb < -1) {
  53935. acosb = -1;
  53936. }
  53937. var angA = Math.acos(acosa);
  53938. var angB = Math.acos(acosb);
  53939. var angC = -angA - angB;
  53940. if (this._rightHandedSystem) {
  53941. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  53942. mat2.multiplyToRef(mat1, mat1);
  53943. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  53944. mat2.multiplyToRef(mat1, mat1);
  53945. }
  53946. else {
  53947. var _tmpVec = BoneIKController._tmpVecs[5];
  53948. _tmpVec.copyFrom(this._bendAxis);
  53949. _tmpVec.x *= -1;
  53950. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  53951. mat2.multiplyToRef(mat1, mat1);
  53952. }
  53953. if (this.poleAngle) {
  53954. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  53955. mat1.multiplyToRef(mat2, mat1);
  53956. }
  53957. if (this.slerpAmount < 1) {
  53958. if (!this._slerping) {
  53959. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  53960. }
  53961. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  53962. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  53963. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  53964. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  53965. this._slerping = true;
  53966. }
  53967. else {
  53968. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  53969. this._bone1Mat.copyFrom(mat1);
  53970. this._slerping = false;
  53971. }
  53972. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  53973. this._bone2Ang = angC;
  53974. };
  53975. return BoneIKController;
  53976. }());
  53977. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  53978. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  53979. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  53980. BABYLON.BoneIKController = BoneIKController;
  53981. })(BABYLON || (BABYLON = {}));
  53982. //# sourceMappingURL=babylon.boneIKController.js.map
  53983. var BABYLON;
  53984. (function (BABYLON) {
  53985. var BoneLookController = (function () {
  53986. /**
  53987. * Create a BoneLookController
  53988. * @param mesh the mesh that the bone belongs to
  53989. * @param bone the bone that will be looking to the target
  53990. * @param target the target Vector3 to look at
  53991. * @param settings optional settings:
  53992. * - maxYaw: the maximum angle the bone will yaw to
  53993. * - minYaw: the minimum angle the bone will yaw to
  53994. * - maxPitch: the maximum angle the bone will pitch to
  53995. * - minPitch: the minimum angle the bone will yaw to
  53996. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  53997. * - upAxis: the up axis of the coordinate system
  53998. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  53999. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  54000. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  54001. * - adjustYaw: used to make an adjustment to the yaw of the bone
  54002. * - adjustPitch: used to make an adjustment to the pitch of the bone
  54003. * - adjustRoll: used to make an adjustment to the roll of the bone
  54004. **/
  54005. function BoneLookController(mesh, bone, target, options) {
  54006. /**
  54007. * The up axis of the coordinate system that is used when the bone is rotated.
  54008. */
  54009. this.upAxis = BABYLON.Vector3.Up();
  54010. /**
  54011. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  54012. */
  54013. this.upAxisSpace = BABYLON.Space.LOCAL;
  54014. /**
  54015. * Used to make an adjustment to the yaw of the bone.
  54016. */
  54017. this.adjustYaw = 0;
  54018. /**
  54019. * Used to make an adjustment to the pitch of the bone.
  54020. */
  54021. this.adjustPitch = 0;
  54022. /**
  54023. * Used to make an adjustment to the roll of the bone.
  54024. */
  54025. this.adjustRoll = 0;
  54026. /**
  54027. * 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).
  54028. */
  54029. this.slerpAmount = 1;
  54030. this._boneQuat = BABYLON.Quaternion.Identity();
  54031. this._slerping = false;
  54032. this._firstFrameSkipped = false;
  54033. this._fowardAxis = BABYLON.Vector3.Forward();
  54034. this.mesh = mesh;
  54035. this.bone = bone;
  54036. this.target = target;
  54037. if (options) {
  54038. if (options.adjustYaw) {
  54039. this.adjustYaw = options.adjustYaw;
  54040. }
  54041. if (options.adjustPitch) {
  54042. this.adjustPitch = options.adjustPitch;
  54043. }
  54044. if (options.adjustRoll) {
  54045. this.adjustRoll = options.adjustRoll;
  54046. }
  54047. if (options.maxYaw != null) {
  54048. this.maxYaw = options.maxYaw;
  54049. }
  54050. else {
  54051. this.maxYaw = Math.PI;
  54052. }
  54053. if (options.minYaw != null) {
  54054. this.minYaw = options.minYaw;
  54055. }
  54056. else {
  54057. this.minYaw = -Math.PI;
  54058. }
  54059. if (options.maxPitch != null) {
  54060. this.maxPitch = options.maxPitch;
  54061. }
  54062. else {
  54063. this.maxPitch = Math.PI;
  54064. }
  54065. if (options.minPitch != null) {
  54066. this.minPitch = options.minPitch;
  54067. }
  54068. else {
  54069. this.minPitch = -Math.PI;
  54070. }
  54071. if (options.slerpAmount != null) {
  54072. this.slerpAmount = options.slerpAmount;
  54073. }
  54074. if (options.upAxis != null) {
  54075. this.upAxis = options.upAxis;
  54076. }
  54077. if (options.upAxisSpace != null) {
  54078. this.upAxisSpace = options.upAxisSpace;
  54079. }
  54080. if (options.yawAxis != null || options.pitchAxis != null) {
  54081. var newYawAxis = BABYLON.Axis.Y;
  54082. var newPitchAxis = BABYLON.Axis.X;
  54083. if (options.yawAxis != null) {
  54084. newYawAxis = options.yawAxis.clone();
  54085. newYawAxis.normalize();
  54086. }
  54087. if (options.pitchAxis != null) {
  54088. newPitchAxis = options.pitchAxis.clone();
  54089. newPitchAxis.normalize();
  54090. }
  54091. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  54092. this._transformYawPitch = BABYLON.Matrix.Identity();
  54093. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  54094. this._transformYawPitchInv = this._transformYawPitch.clone();
  54095. this._transformYawPitch.invert();
  54096. }
  54097. }
  54098. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  54099. this.upAxisSpace = BABYLON.Space.LOCAL;
  54100. }
  54101. }
  54102. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  54103. /**
  54104. * Get/set the minimum yaw angle that the bone can look to.
  54105. */
  54106. get: function () {
  54107. return this._minYaw;
  54108. },
  54109. set: function (value) {
  54110. this._minYaw = value;
  54111. this._minYawSin = Math.sin(value);
  54112. this._minYawCos = Math.cos(value);
  54113. if (this._maxYaw != null) {
  54114. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  54115. this._yawRange = this._maxYaw - this._minYaw;
  54116. }
  54117. },
  54118. enumerable: true,
  54119. configurable: true
  54120. });
  54121. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  54122. /**
  54123. * Get/set the maximum yaw angle that the bone can look to.
  54124. */
  54125. get: function () {
  54126. return this._maxYaw;
  54127. },
  54128. set: function (value) {
  54129. this._maxYaw = value;
  54130. this._maxYawSin = Math.sin(value);
  54131. this._maxYawCos = Math.cos(value);
  54132. if (this._minYaw != null) {
  54133. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  54134. this._yawRange = this._maxYaw - this._minYaw;
  54135. }
  54136. },
  54137. enumerable: true,
  54138. configurable: true
  54139. });
  54140. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  54141. /**
  54142. * Get/set the minimum pitch angle that the bone can look to.
  54143. */
  54144. get: function () {
  54145. return this._minPitch;
  54146. },
  54147. set: function (value) {
  54148. this._minPitch = value;
  54149. this._minPitchTan = Math.tan(value);
  54150. },
  54151. enumerable: true,
  54152. configurable: true
  54153. });
  54154. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  54155. /**
  54156. * Get/set the maximum pitch angle that the bone can look to.
  54157. */
  54158. get: function () {
  54159. return this._maxPitch;
  54160. },
  54161. set: function (value) {
  54162. this._maxPitch = value;
  54163. this._maxPitchTan = Math.tan(value);
  54164. },
  54165. enumerable: true,
  54166. configurable: true
  54167. });
  54168. /**
  54169. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  54170. */
  54171. BoneLookController.prototype.update = function () {
  54172. //skip the first frame when slerping so that the mesh rotation is correct
  54173. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  54174. this._firstFrameSkipped = true;
  54175. return;
  54176. }
  54177. var bone = this.bone;
  54178. var bonePos = BoneLookController._tmpVecs[0];
  54179. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  54180. var target = this.target;
  54181. var _tmpMat1 = BoneLookController._tmpMats[0];
  54182. var _tmpMat2 = BoneLookController._tmpMats[1];
  54183. var mesh = this.mesh;
  54184. var parentBone = bone.getParent();
  54185. var upAxis = BoneLookController._tmpVecs[1];
  54186. upAxis.copyFrom(this.upAxis);
  54187. if (this.upAxisSpace == BABYLON.Space.BONE) {
  54188. if (this._transformYawPitch) {
  54189. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  54190. }
  54191. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  54192. }
  54193. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  54194. mesh.getDirectionToRef(upAxis, upAxis);
  54195. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  54196. upAxis.normalize();
  54197. }
  54198. }
  54199. var checkYaw = false;
  54200. var checkPitch = false;
  54201. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  54202. checkYaw = true;
  54203. }
  54204. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  54205. checkPitch = true;
  54206. }
  54207. if (checkYaw || checkPitch) {
  54208. var spaceMat = BoneLookController._tmpMats[2];
  54209. var spaceMatInv = BoneLookController._tmpMats[3];
  54210. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  54211. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  54212. }
  54213. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  54214. spaceMat.copyFrom(mesh.getWorldMatrix());
  54215. }
  54216. else {
  54217. var forwardAxis = BoneLookController._tmpVecs[2];
  54218. forwardAxis.copyFrom(this._fowardAxis);
  54219. if (this._transformYawPitch) {
  54220. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  54221. }
  54222. if (parentBone) {
  54223. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  54224. }
  54225. else {
  54226. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  54227. }
  54228. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  54229. rightAxis.normalize();
  54230. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  54231. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  54232. }
  54233. spaceMat.invertToRef(spaceMatInv);
  54234. var xzlen;
  54235. if (checkPitch) {
  54236. var localTarget = BoneLookController._tmpVecs[3];
  54237. target.subtractToRef(bonePos, localTarget);
  54238. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  54239. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  54240. var pitch = Math.atan2(localTarget.y, xzlen);
  54241. var newPitch = pitch;
  54242. if (pitch > this._maxPitch) {
  54243. localTarget.y = this._maxPitchTan * xzlen;
  54244. newPitch = this._maxPitch;
  54245. }
  54246. else if (pitch < this._minPitch) {
  54247. localTarget.y = this._minPitchTan * xzlen;
  54248. newPitch = this._minPitch;
  54249. }
  54250. if (pitch != newPitch) {
  54251. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  54252. localTarget.addInPlace(bonePos);
  54253. target = localTarget;
  54254. }
  54255. }
  54256. if (checkYaw) {
  54257. var localTarget = BoneLookController._tmpVecs[4];
  54258. target.subtractToRef(bonePos, localTarget);
  54259. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  54260. var yaw = Math.atan2(localTarget.x, localTarget.z);
  54261. var newYaw = yaw;
  54262. if (yaw > this._maxYaw || yaw < this._minYaw) {
  54263. if (xzlen == null) {
  54264. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  54265. }
  54266. if (this._yawRange > Math.PI) {
  54267. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  54268. localTarget.z = this._maxYawCos * xzlen;
  54269. localTarget.x = this._maxYawSin * xzlen;
  54270. newYaw = this._maxYaw;
  54271. }
  54272. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  54273. localTarget.z = this._minYawCos * xzlen;
  54274. localTarget.x = this._minYawSin * xzlen;
  54275. newYaw = this._minYaw;
  54276. }
  54277. }
  54278. else {
  54279. if (yaw > this._maxYaw) {
  54280. localTarget.z = this._maxYawCos * xzlen;
  54281. localTarget.x = this._maxYawSin * xzlen;
  54282. newYaw = this._maxYaw;
  54283. }
  54284. else if (yaw < this._minYaw) {
  54285. localTarget.z = this._minYawCos * xzlen;
  54286. localTarget.x = this._minYawSin * xzlen;
  54287. newYaw = this._minYaw;
  54288. }
  54289. }
  54290. }
  54291. if (this._slerping && this._yawRange > Math.PI) {
  54292. //are we going to be crossing into the min/max region?
  54293. var boneFwd = BoneLookController._tmpVecs[8];
  54294. boneFwd.copyFrom(BABYLON.Axis.Z);
  54295. if (this._transformYawPitch) {
  54296. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  54297. }
  54298. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  54299. this._boneQuat.toRotationMatrix(boneRotMat);
  54300. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  54301. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  54302. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  54303. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  54304. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  54305. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  54306. if (angBtwTar > angBtwMidYaw) {
  54307. if (xzlen == null) {
  54308. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  54309. }
  54310. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  54311. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  54312. if (angBtwMin < angBtwMax) {
  54313. newYaw = boneYaw + Math.PI * .75;
  54314. localTarget.z = Math.cos(newYaw) * xzlen;
  54315. localTarget.x = Math.sin(newYaw) * xzlen;
  54316. }
  54317. else {
  54318. newYaw = boneYaw - Math.PI * .75;
  54319. localTarget.z = Math.cos(newYaw) * xzlen;
  54320. localTarget.x = Math.sin(newYaw) * xzlen;
  54321. }
  54322. }
  54323. }
  54324. if (yaw != newYaw) {
  54325. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  54326. localTarget.addInPlace(bonePos);
  54327. target = localTarget;
  54328. }
  54329. }
  54330. }
  54331. var zaxis = BoneLookController._tmpVecs[5];
  54332. var xaxis = BoneLookController._tmpVecs[6];
  54333. var yaxis = BoneLookController._tmpVecs[7];
  54334. var _tmpQuat = BoneLookController._tmpQuat;
  54335. target.subtractToRef(bonePos, zaxis);
  54336. zaxis.normalize();
  54337. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  54338. xaxis.normalize();
  54339. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  54340. yaxis.normalize();
  54341. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  54342. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  54343. return;
  54344. }
  54345. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  54346. return;
  54347. }
  54348. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  54349. return;
  54350. }
  54351. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  54352. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  54353. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  54354. }
  54355. if (this.slerpAmount < 1) {
  54356. if (!this._slerping) {
  54357. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  54358. }
  54359. if (this._transformYawPitch) {
  54360. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  54361. }
  54362. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  54363. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  54364. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  54365. this._slerping = true;
  54366. }
  54367. else {
  54368. if (this._transformYawPitch) {
  54369. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  54370. }
  54371. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  54372. this._slerping = false;
  54373. }
  54374. };
  54375. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  54376. var angDiff = ang2 - ang1;
  54377. angDiff %= Math.PI * 2;
  54378. if (angDiff > Math.PI) {
  54379. angDiff -= Math.PI * 2;
  54380. }
  54381. else if (angDiff < -Math.PI) {
  54382. angDiff += Math.PI * 2;
  54383. }
  54384. return angDiff;
  54385. };
  54386. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  54387. ang1 %= (2 * Math.PI);
  54388. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  54389. ang2 %= (2 * Math.PI);
  54390. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  54391. var ab = 0;
  54392. if (ang1 < ang2) {
  54393. ab = ang2 - ang1;
  54394. }
  54395. else {
  54396. ab = ang1 - ang2;
  54397. }
  54398. if (ab > Math.PI) {
  54399. ab = Math.PI * 2 - ab;
  54400. }
  54401. return ab;
  54402. };
  54403. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  54404. ang %= (2 * Math.PI);
  54405. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  54406. ang1 %= (2 * Math.PI);
  54407. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  54408. ang2 %= (2 * Math.PI);
  54409. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  54410. if (ang1 < ang2) {
  54411. if (ang > ang1 && ang < ang2) {
  54412. return true;
  54413. }
  54414. }
  54415. else {
  54416. if (ang > ang2 && ang < ang1) {
  54417. return true;
  54418. }
  54419. }
  54420. return false;
  54421. };
  54422. return BoneLookController;
  54423. }());
  54424. 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()];
  54425. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  54426. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  54427. BABYLON.BoneLookController = BoneLookController;
  54428. })(BABYLON || (BABYLON = {}));
  54429. //# sourceMappingURL=babylon.boneLookController.js.map
  54430. var BABYLON;
  54431. (function (BABYLON) {
  54432. var Skeleton = (function () {
  54433. function Skeleton(name, id, scene) {
  54434. this.name = name;
  54435. this.id = id;
  54436. this.bones = new Array();
  54437. this.needInitialSkinMatrix = false;
  54438. this._isDirty = true;
  54439. this._meshesWithPoseMatrix = new Array();
  54440. this._identity = BABYLON.Matrix.Identity();
  54441. this._ranges = {};
  54442. this._lastAbsoluteTransformsUpdateId = -1;
  54443. // Events
  54444. /**
  54445. * An event triggered before computing the skeleton's matrices
  54446. * @type {BABYLON.Observable}
  54447. */
  54448. this.onBeforeComputeObservable = new BABYLON.Observable();
  54449. this.bones = [];
  54450. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54451. scene.skeletons.push(this);
  54452. //make sure it will recalculate the matrix next time prepare is called.
  54453. this._isDirty = true;
  54454. }
  54455. // Members
  54456. Skeleton.prototype.getTransformMatrices = function (mesh) {
  54457. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  54458. return mesh._bonesTransformMatrices;
  54459. }
  54460. if (!this._transformMatrices) {
  54461. this.prepare();
  54462. }
  54463. return this._transformMatrices;
  54464. };
  54465. Skeleton.prototype.getScene = function () {
  54466. return this._scene;
  54467. };
  54468. // Methods
  54469. /**
  54470. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  54471. */
  54472. Skeleton.prototype.toString = function (fullDetails) {
  54473. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  54474. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  54475. if (fullDetails) {
  54476. ret += ", Ranges: {";
  54477. var first = true;
  54478. for (var name_1 in this._ranges) {
  54479. if (first) {
  54480. ret += ", ";
  54481. first = false;
  54482. }
  54483. ret += name_1;
  54484. }
  54485. ret += "}";
  54486. }
  54487. return ret;
  54488. };
  54489. /**
  54490. * Get bone's index searching by name
  54491. * @param {string} name is bone's name to search for
  54492. * @return {number} Indice of the bone. Returns -1 if not found
  54493. */
  54494. Skeleton.prototype.getBoneIndexByName = function (name) {
  54495. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  54496. if (this.bones[boneIndex].name === name) {
  54497. return boneIndex;
  54498. }
  54499. }
  54500. return -1;
  54501. };
  54502. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  54503. // check name not already in use
  54504. if (!this._ranges[name]) {
  54505. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  54506. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  54507. if (this.bones[i].animations[0]) {
  54508. this.bones[i].animations[0].createRange(name, from, to);
  54509. }
  54510. }
  54511. }
  54512. };
  54513. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  54514. if (deleteFrames === void 0) { deleteFrames = true; }
  54515. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  54516. if (this.bones[i].animations[0]) {
  54517. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  54518. }
  54519. }
  54520. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  54521. };
  54522. Skeleton.prototype.getAnimationRange = function (name) {
  54523. return this._ranges[name];
  54524. };
  54525. /**
  54526. * Returns as an Array, all AnimationRanges defined on this skeleton
  54527. */
  54528. Skeleton.prototype.getAnimationRanges = function () {
  54529. var animationRanges = [];
  54530. var name;
  54531. var i = 0;
  54532. for (name in this._ranges) {
  54533. animationRanges[i] = this._ranges[name];
  54534. i++;
  54535. }
  54536. return animationRanges;
  54537. };
  54538. /**
  54539. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  54540. */
  54541. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  54542. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  54543. if (this._ranges[name] || !source.getAnimationRange(name)) {
  54544. return false;
  54545. }
  54546. var ret = true;
  54547. var frameOffset = this._getHighestAnimationFrame() + 1;
  54548. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  54549. var boneDict = {};
  54550. var sourceBones = source.bones;
  54551. var nBones;
  54552. var i;
  54553. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  54554. boneDict[sourceBones[i].name] = sourceBones[i];
  54555. }
  54556. if (this.bones.length !== sourceBones.length) {
  54557. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  54558. ret = false;
  54559. }
  54560. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  54561. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  54562. var boneName = this.bones[i].name;
  54563. var sourceBone = boneDict[boneName];
  54564. if (sourceBone) {
  54565. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  54566. }
  54567. else {
  54568. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  54569. ret = false;
  54570. }
  54571. }
  54572. // do not call createAnimationRange(), since it also is done to bones, which was already done
  54573. var range = source.getAnimationRange(name);
  54574. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  54575. return ret;
  54576. };
  54577. Skeleton.prototype.returnToRest = function () {
  54578. for (var index = 0; index < this.bones.length; index++) {
  54579. this.bones[index].returnToRest();
  54580. }
  54581. };
  54582. Skeleton.prototype._getHighestAnimationFrame = function () {
  54583. var ret = 0;
  54584. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  54585. if (this.bones[i].animations[0]) {
  54586. var highest = this.bones[i].animations[0].getHighestFrame();
  54587. if (ret < highest) {
  54588. ret = highest;
  54589. }
  54590. }
  54591. }
  54592. return ret;
  54593. };
  54594. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  54595. var range = this.getAnimationRange(name);
  54596. if (!range) {
  54597. return null;
  54598. }
  54599. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  54600. };
  54601. Skeleton.prototype._markAsDirty = function () {
  54602. this._isDirty = true;
  54603. };
  54604. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  54605. this._meshesWithPoseMatrix.push(mesh);
  54606. };
  54607. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  54608. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  54609. if (index > -1) {
  54610. this._meshesWithPoseMatrix.splice(index, 1);
  54611. }
  54612. };
  54613. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  54614. this.onBeforeComputeObservable.notifyObservers(this);
  54615. for (var index = 0; index < this.bones.length; index++) {
  54616. var bone = this.bones[index];
  54617. var parentBone = bone.getParent();
  54618. if (parentBone) {
  54619. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  54620. }
  54621. else {
  54622. if (initialSkinMatrix) {
  54623. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  54624. }
  54625. else {
  54626. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  54627. }
  54628. }
  54629. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  54630. }
  54631. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  54632. };
  54633. Skeleton.prototype.prepare = function () {
  54634. if (!this._isDirty) {
  54635. return;
  54636. }
  54637. if (this.needInitialSkinMatrix) {
  54638. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  54639. var mesh = this._meshesWithPoseMatrix[index];
  54640. var poseMatrix = mesh.getPoseMatrix();
  54641. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  54642. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  54643. }
  54644. if (this._synchronizedWithMesh !== mesh) {
  54645. this._synchronizedWithMesh = mesh;
  54646. // Prepare bones
  54647. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  54648. var bone = this.bones[boneIndex];
  54649. if (!bone.getParent()) {
  54650. var matrix = bone.getBaseMatrix();
  54651. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  54652. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  54653. }
  54654. }
  54655. }
  54656. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  54657. }
  54658. }
  54659. else {
  54660. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  54661. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  54662. }
  54663. this._computeTransformMatrices(this._transformMatrices, null);
  54664. }
  54665. this._isDirty = false;
  54666. this._scene._activeBones.addCount(this.bones.length, false);
  54667. };
  54668. Skeleton.prototype.getAnimatables = function () {
  54669. if (!this._animatables || this._animatables.length !== this.bones.length) {
  54670. this._animatables = [];
  54671. for (var index = 0; index < this.bones.length; index++) {
  54672. this._animatables.push(this.bones[index]);
  54673. }
  54674. }
  54675. return this._animatables;
  54676. };
  54677. Skeleton.prototype.clone = function (name, id) {
  54678. var result = new Skeleton(name, id || name, this._scene);
  54679. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  54680. for (var index = 0; index < this.bones.length; index++) {
  54681. var source = this.bones[index];
  54682. var parentBone = null;
  54683. if (source.getParent()) {
  54684. var parentIndex = this.bones.indexOf(source.getParent());
  54685. parentBone = result.bones[parentIndex];
  54686. }
  54687. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  54688. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  54689. }
  54690. if (this._ranges) {
  54691. result._ranges = {};
  54692. for (var rangeName in this._ranges) {
  54693. result._ranges[rangeName] = this._ranges[rangeName].clone();
  54694. }
  54695. }
  54696. this._isDirty = true;
  54697. return result;
  54698. };
  54699. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  54700. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  54701. this.bones.forEach(function (bone) {
  54702. bone.animations.forEach(function (animation) {
  54703. animation.enableBlending = true;
  54704. animation.blendingSpeed = blendingSpeed;
  54705. });
  54706. });
  54707. };
  54708. Skeleton.prototype.dispose = function () {
  54709. this._meshesWithPoseMatrix = [];
  54710. // Animations
  54711. this.getScene().stopAnimation(this);
  54712. // Remove from scene
  54713. this.getScene().removeSkeleton(this);
  54714. };
  54715. Skeleton.prototype.serialize = function () {
  54716. var serializationObject = {};
  54717. serializationObject.name = this.name;
  54718. serializationObject.id = this.id;
  54719. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  54720. serializationObject.bones = [];
  54721. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  54722. for (var index = 0; index < this.bones.length; index++) {
  54723. var bone = this.bones[index];
  54724. var serializedBone = {
  54725. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  54726. name: bone.name,
  54727. matrix: bone.getBaseMatrix().toArray(),
  54728. rest: bone.getRestPose().toArray()
  54729. };
  54730. serializationObject.bones.push(serializedBone);
  54731. if (bone.length) {
  54732. serializedBone.length = bone.length;
  54733. }
  54734. if (bone.animations && bone.animations.length > 0) {
  54735. serializedBone.animation = bone.animations[0].serialize();
  54736. }
  54737. serializationObject.ranges = [];
  54738. for (var name in this._ranges) {
  54739. var range = {};
  54740. range.name = name;
  54741. range.from = this._ranges[name].from;
  54742. range.to = this._ranges[name].to;
  54743. serializationObject.ranges.push(range);
  54744. }
  54745. }
  54746. return serializationObject;
  54747. };
  54748. Skeleton.Parse = function (parsedSkeleton, scene) {
  54749. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  54750. if (parsedSkeleton.dimensionsAtRest) {
  54751. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  54752. }
  54753. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  54754. var index;
  54755. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  54756. var parsedBone = parsedSkeleton.bones[index];
  54757. var parentBone = null;
  54758. if (parsedBone.parentBoneIndex > -1) {
  54759. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  54760. }
  54761. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  54762. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  54763. if (parsedBone.length) {
  54764. bone.length = parsedBone.length;
  54765. }
  54766. if (parsedBone.animation) {
  54767. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  54768. }
  54769. }
  54770. // placed after bones, so createAnimationRange can cascade down
  54771. if (parsedSkeleton.ranges) {
  54772. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  54773. var data = parsedSkeleton.ranges[index];
  54774. skeleton.createAnimationRange(data.name, data.from, data.to);
  54775. }
  54776. }
  54777. return skeleton;
  54778. };
  54779. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  54780. if (forceUpdate === void 0) { forceUpdate = false; }
  54781. var renderId = this._scene.getRenderId();
  54782. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  54783. this.bones[0].computeAbsoluteTransforms();
  54784. this._lastAbsoluteTransformsUpdateId = renderId;
  54785. }
  54786. };
  54787. Skeleton.prototype.getPoseMatrix = function () {
  54788. var poseMatrix;
  54789. if (this._meshesWithPoseMatrix.length > 0) {
  54790. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  54791. }
  54792. return poseMatrix;
  54793. };
  54794. return Skeleton;
  54795. }());
  54796. BABYLON.Skeleton = Skeleton;
  54797. })(BABYLON || (BABYLON = {}));
  54798. //# sourceMappingURL=babylon.skeleton.js.map
  54799. var BABYLON;
  54800. (function (BABYLON) {
  54801. var Internals;
  54802. (function (Internals) {
  54803. var FileFaceOrientation = (function () {
  54804. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  54805. this.name = name;
  54806. this.worldAxisForNormal = worldAxisForNormal;
  54807. this.worldAxisForFileX = worldAxisForFileX;
  54808. this.worldAxisForFileY = worldAxisForFileY;
  54809. }
  54810. return FileFaceOrientation;
  54811. }());
  54812. ;
  54813. /**
  54814. * Helper class dealing with the extraction of spherical polynomial dataArray
  54815. * from a cube map.
  54816. */
  54817. var CubeMapToSphericalPolynomialTools = (function () {
  54818. function CubeMapToSphericalPolynomialTools() {
  54819. }
  54820. /**
  54821. * Converts a cubemap to the according Spherical Polynomial data.
  54822. * This extracts the first 3 orders only as they are the only one used in the lighting.
  54823. *
  54824. * @param cubeInfo The Cube map to extract the information from.
  54825. * @return The Spherical Polynomial data.
  54826. */
  54827. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  54828. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  54829. var totalSolidAngle = 0.0;
  54830. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  54831. var du = 2.0 / cubeInfo.size;
  54832. var dv = du;
  54833. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  54834. var minUV = du * 0.5 - 1.0;
  54835. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54836. var fileFace = this.FileFaces[faceIndex];
  54837. var dataArray = cubeInfo[fileFace.name];
  54838. var v = minUV;
  54839. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  54840. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  54841. // Because SP is still linear, so summation is fine in that basis.
  54842. for (var y = 0; y < cubeInfo.size; y++) {
  54843. var u = minUV;
  54844. for (var x = 0; x < cubeInfo.size; x++) {
  54845. // World direction (not normalised)
  54846. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  54847. worldDirection.normalize();
  54848. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  54849. if (1) {
  54850. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  54851. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  54852. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  54853. var color = new BABYLON.Color3(r, g, b);
  54854. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54855. }
  54856. else {
  54857. if (faceIndex == 0) {
  54858. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54859. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54860. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54861. }
  54862. else if (faceIndex == 1) {
  54863. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54864. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54865. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54866. }
  54867. else if (faceIndex == 2) {
  54868. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54869. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54870. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54871. }
  54872. else if (faceIndex == 3) {
  54873. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54874. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54875. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54876. }
  54877. else if (faceIndex == 4) {
  54878. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54879. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54880. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54881. }
  54882. else if (faceIndex == 5) {
  54883. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54884. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54885. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54886. }
  54887. 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]);
  54888. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54889. }
  54890. totalSolidAngle += deltaSolidAngle;
  54891. u += du;
  54892. }
  54893. v += dv;
  54894. }
  54895. }
  54896. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  54897. var correction = correctSolidAngle / totalSolidAngle;
  54898. sphericalHarmonics.scale(correction);
  54899. // Additionally scale by pi -- audit needed
  54900. sphericalHarmonics.scale(1.0 / Math.PI);
  54901. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  54902. };
  54903. return CubeMapToSphericalPolynomialTools;
  54904. }());
  54905. CubeMapToSphericalPolynomialTools.FileFaces = [
  54906. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  54907. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  54908. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  54909. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  54910. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  54911. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  54912. ];
  54913. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  54914. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54915. })(BABYLON || (BABYLON = {}));
  54916. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  54917. var BABYLON;
  54918. (function (BABYLON) {
  54919. var Internals;
  54920. (function (Internals) {
  54921. /**
  54922. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  54923. */
  54924. var PanoramaToCubeMapTools = (function () {
  54925. function PanoramaToCubeMapTools() {
  54926. }
  54927. /**
  54928. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  54929. *
  54930. * @param float32Array The source data.
  54931. * @param inputWidth The width of the input panorama.
  54932. * @param inputhHeight The height of the input panorama.
  54933. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  54934. * @return The cubemap data
  54935. */
  54936. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  54937. if (!float32Array) {
  54938. throw "ConvertPanoramaToCubemap: input cannot be null";
  54939. }
  54940. if (float32Array.length != inputWidth * inputHeight * 3) {
  54941. throw "ConvertPanoramaToCubemap: input size is wrong";
  54942. }
  54943. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  54944. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  54945. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  54946. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  54947. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  54948. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  54949. return {
  54950. front: textureFront,
  54951. back: textureBack,
  54952. left: textureLeft,
  54953. right: textureRight,
  54954. up: textureUp,
  54955. down: textureDown,
  54956. size: size
  54957. };
  54958. };
  54959. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  54960. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  54961. var textureArray = new Float32Array(buffer);
  54962. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  54963. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  54964. var dy = 1 / texSize;
  54965. var fy = 0;
  54966. for (var y = 0; y < texSize; y++) {
  54967. var xv1 = faceData[0];
  54968. var xv2 = faceData[2];
  54969. for (var x = 0; x < texSize; x++) {
  54970. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  54971. v.normalize();
  54972. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  54973. // 3 channels per pixels
  54974. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  54975. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  54976. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  54977. xv1 = xv1.add(rotDX1);
  54978. xv2 = xv2.add(rotDX2);
  54979. }
  54980. fy += dy;
  54981. }
  54982. return textureArray;
  54983. };
  54984. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  54985. var theta = Math.atan2(vDir.z, vDir.x);
  54986. var phi = Math.acos(vDir.y);
  54987. while (theta < -Math.PI)
  54988. theta += 2 * Math.PI;
  54989. while (theta > Math.PI)
  54990. theta -= 2 * Math.PI;
  54991. var dx = theta / Math.PI;
  54992. var dy = phi / Math.PI;
  54993. // recenter.
  54994. dx = dx * 0.5 + 0.5;
  54995. var px = Math.round(dx * inputWidth);
  54996. if (px < 0)
  54997. px = 0;
  54998. else if (px >= inputWidth)
  54999. px = inputWidth - 1;
  55000. var py = Math.round(dy * inputHeight);
  55001. if (py < 0)
  55002. py = 0;
  55003. else if (py >= inputHeight)
  55004. py = inputHeight - 1;
  55005. var inputY = (inputHeight - py - 1);
  55006. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  55007. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  55008. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  55009. return {
  55010. r: r,
  55011. g: g,
  55012. b: b
  55013. };
  55014. };
  55015. return PanoramaToCubeMapTools;
  55016. }());
  55017. PanoramaToCubeMapTools.FACE_FRONT = [
  55018. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55019. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55020. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55021. new BABYLON.Vector3(1.0, 1.0, -1.0)
  55022. ];
  55023. PanoramaToCubeMapTools.FACE_BACK = [
  55024. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55025. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55026. new BABYLON.Vector3(1.0, 1.0, 1.0),
  55027. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  55028. ];
  55029. PanoramaToCubeMapTools.FACE_RIGHT = [
  55030. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55031. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55032. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55033. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55034. ];
  55035. PanoramaToCubeMapTools.FACE_LEFT = [
  55036. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55037. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55038. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55039. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  55040. ];
  55041. PanoramaToCubeMapTools.FACE_DOWN = [
  55042. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55043. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55044. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55045. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55046. ];
  55047. PanoramaToCubeMapTools.FACE_UP = [
  55048. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55049. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55050. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55051. new BABYLON.Vector3(1.0, -1.0, -1.0)
  55052. ];
  55053. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  55054. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55055. })(BABYLON || (BABYLON = {}));
  55056. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  55057. var BABYLON;
  55058. (function (BABYLON) {
  55059. var Internals;
  55060. (function (Internals) {
  55061. ;
  55062. /**
  55063. * This groups tools to convert HDR texture to native colors array.
  55064. */
  55065. var HDRTools = (function () {
  55066. function HDRTools() {
  55067. }
  55068. HDRTools.Ldexp = function (mantissa, exponent) {
  55069. if (exponent > 1023) {
  55070. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  55071. }
  55072. if (exponent < -1074) {
  55073. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  55074. }
  55075. return mantissa * Math.pow(2, exponent);
  55076. };
  55077. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  55078. if (exponent > 0) {
  55079. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  55080. float32array[index + 0] = red * exponent;
  55081. float32array[index + 1] = green * exponent;
  55082. float32array[index + 2] = blue * exponent;
  55083. }
  55084. else {
  55085. float32array[index + 0] = 0;
  55086. float32array[index + 1] = 0;
  55087. float32array[index + 2] = 0;
  55088. }
  55089. };
  55090. HDRTools.readStringLine = function (uint8array, startIndex) {
  55091. var line = "";
  55092. var character = "";
  55093. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  55094. character = String.fromCharCode(uint8array[i]);
  55095. if (character == "\n") {
  55096. break;
  55097. }
  55098. line += character;
  55099. }
  55100. return line;
  55101. };
  55102. /**
  55103. * Reads header information from an RGBE texture stored in a native array.
  55104. * More information on this format are available here:
  55105. * https://en.wikipedia.org/wiki/RGBE_image_format
  55106. *
  55107. * @param uint8array The binary file stored in native array.
  55108. * @return The header information.
  55109. */
  55110. HDRTools.RGBE_ReadHeader = function (uint8array) {
  55111. var height = 0;
  55112. var width = 0;
  55113. var line = this.readStringLine(uint8array, 0);
  55114. if (line[0] != '#' || line[1] != '?') {
  55115. throw "Bad HDR Format.";
  55116. }
  55117. var endOfHeader = false;
  55118. var findFormat = false;
  55119. var lineIndex = 0;
  55120. do {
  55121. lineIndex += (line.length + 1);
  55122. line = this.readStringLine(uint8array, lineIndex);
  55123. if (line == "FORMAT=32-bit_rle_rgbe") {
  55124. findFormat = true;
  55125. }
  55126. else if (line.length == 0) {
  55127. endOfHeader = true;
  55128. }
  55129. } while (!endOfHeader);
  55130. if (!findFormat) {
  55131. throw "HDR Bad header format, unsupported FORMAT";
  55132. }
  55133. lineIndex += (line.length + 1);
  55134. line = this.readStringLine(uint8array, lineIndex);
  55135. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  55136. var match = sizeRegexp.exec(line);
  55137. // TODO. Support +Y and -X if needed.
  55138. if (match.length < 3) {
  55139. throw "HDR Bad header format, no size";
  55140. }
  55141. width = parseInt(match[2]);
  55142. height = parseInt(match[1]);
  55143. if (width < 8 || width > 0x7fff) {
  55144. throw "HDR Bad header format, unsupported size";
  55145. }
  55146. lineIndex += (line.length + 1);
  55147. return {
  55148. height: height,
  55149. width: width,
  55150. dataPosition: lineIndex
  55151. };
  55152. };
  55153. /**
  55154. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  55155. * This RGBE texture needs to store the information as a panorama.
  55156. *
  55157. * More information on this format are available here:
  55158. * https://en.wikipedia.org/wiki/RGBE_image_format
  55159. *
  55160. * @param buffer The binary file stored in an array buffer.
  55161. * @param size The expected size of the extracted cubemap.
  55162. * @return The Cube Map information.
  55163. */
  55164. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  55165. var uint8array = new Uint8Array(buffer);
  55166. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  55167. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55168. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  55169. return cubeMapData;
  55170. };
  55171. /**
  55172. * Returns the pixels data extracted from an RGBE texture.
  55173. * This pixels will be stored left to right up to down in the R G B order in one array.
  55174. *
  55175. * More information on this format are available here:
  55176. * https://en.wikipedia.org/wiki/RGBE_image_format
  55177. *
  55178. * @param uint8array The binary file stored in an array buffer.
  55179. * @param hdrInfo The header information of the file.
  55180. * @return The pixels data in RGB right to left up to down order.
  55181. */
  55182. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  55183. // Keep for multi format supports.
  55184. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55185. };
  55186. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  55187. var num_scanlines = hdrInfo.height;
  55188. var scanline_width = hdrInfo.width;
  55189. var a, b, c, d, count;
  55190. var dataIndex = hdrInfo.dataPosition;
  55191. var index = 0, endIndex = 0, i = 0;
  55192. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  55193. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  55194. // 3 channels of 4 bytes per pixel in float.
  55195. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  55196. var resultArray = new Float32Array(resultBuffer);
  55197. // read in each successive scanline
  55198. while (num_scanlines > 0) {
  55199. a = uint8array[dataIndex++];
  55200. b = uint8array[dataIndex++];
  55201. c = uint8array[dataIndex++];
  55202. d = uint8array[dataIndex++];
  55203. if (a != 2 || b != 2 || (c & 0x80)) {
  55204. // this file is not run length encoded
  55205. throw "HDR Bad header format, not RLE";
  55206. }
  55207. if (((c << 8) | d) != scanline_width) {
  55208. throw "HDR Bad header format, wrong scan line width";
  55209. }
  55210. index = 0;
  55211. // read each of the four channels for the scanline into the buffer
  55212. for (i = 0; i < 4; i++) {
  55213. endIndex = (i + 1) * scanline_width;
  55214. while (index < endIndex) {
  55215. a = uint8array[dataIndex++];
  55216. b = uint8array[dataIndex++];
  55217. if (a > 128) {
  55218. // a run of the same value
  55219. count = a - 128;
  55220. if ((count == 0) || (count > endIndex - index)) {
  55221. throw "HDR Bad Format, bad scanline data (run)";
  55222. }
  55223. while (count-- > 0) {
  55224. scanLineArray[index++] = b;
  55225. }
  55226. }
  55227. else {
  55228. // a non-run
  55229. count = a;
  55230. if ((count == 0) || (count > endIndex - index)) {
  55231. throw "HDR Bad Format, bad scanline data (non-run)";
  55232. }
  55233. scanLineArray[index++] = b;
  55234. if (--count > 0) {
  55235. for (var j = 0; j < count; j++) {
  55236. scanLineArray[index++] = uint8array[dataIndex++];
  55237. }
  55238. }
  55239. }
  55240. }
  55241. }
  55242. // now convert data from buffer into floats
  55243. for (i = 0; i < scanline_width; i++) {
  55244. a = scanLineArray[i];
  55245. b = scanLineArray[i + scanline_width];
  55246. c = scanLineArray[i + 2 * scanline_width];
  55247. d = scanLineArray[i + 3 * scanline_width];
  55248. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  55249. }
  55250. num_scanlines--;
  55251. }
  55252. return resultArray;
  55253. };
  55254. return HDRTools;
  55255. }());
  55256. Internals.HDRTools = HDRTools;
  55257. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55258. })(BABYLON || (BABYLON = {}));
  55259. //# sourceMappingURL=babylon.hdr.js.map
  55260. //_______________________________________________________________
  55261. // Extracted from CubeMapGen:
  55262. // https://code.google.com/archive/p/cubemapgen/
  55263. //
  55264. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55265. //_______________________________________________________________
  55266. var BABYLON;
  55267. (function (BABYLON) {
  55268. var Internals;
  55269. (function (Internals) {
  55270. /**
  55271. * The bounding box information used during the conversion process.
  55272. */
  55273. var CMGBoundinBox = (function () {
  55274. function CMGBoundinBox() {
  55275. this.min = new BABYLON.Vector3(0, 0, 0);
  55276. this.max = new BABYLON.Vector3(0, 0, 0);
  55277. this.clear();
  55278. }
  55279. CMGBoundinBox.prototype.clear = function () {
  55280. this.min.x = CMGBoundinBox.MAX;
  55281. this.min.y = CMGBoundinBox.MAX;
  55282. this.min.z = CMGBoundinBox.MAX;
  55283. this.max.x = CMGBoundinBox.MIN;
  55284. this.max.y = CMGBoundinBox.MIN;
  55285. this.max.z = CMGBoundinBox.MIN;
  55286. };
  55287. CMGBoundinBox.prototype.augment = function (x, y, z) {
  55288. this.min.x = Math.min(this.min.x, x);
  55289. this.min.y = Math.min(this.min.y, y);
  55290. this.min.z = Math.min(this.min.z, z);
  55291. this.max.x = Math.max(this.max.x, x);
  55292. this.max.y = Math.max(this.max.y, y);
  55293. this.max.z = Math.max(this.max.z, z);
  55294. };
  55295. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  55296. this.min.x = Math.max(this.min.x, x);
  55297. this.min.y = Math.max(this.min.y, y);
  55298. this.min.z = Math.max(this.min.z, z);
  55299. };
  55300. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  55301. this.max.x = Math.min(this.max.x, x);
  55302. this.max.y = Math.min(this.max.y, y);
  55303. this.max.z = Math.min(this.max.z, z);
  55304. };
  55305. CMGBoundinBox.prototype.empty = function () {
  55306. if ((this.min.x > this.max.y) ||
  55307. (this.min.y > this.max.y) ||
  55308. (this.min.z > this.max.y)) {
  55309. return true;
  55310. }
  55311. else {
  55312. return false;
  55313. }
  55314. };
  55315. return CMGBoundinBox;
  55316. }());
  55317. CMGBoundinBox.MAX = Number.MAX_VALUE;
  55318. CMGBoundinBox.MIN = Number.MIN_VALUE;
  55319. /**
  55320. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  55321. * required by the glossinees of a material.
  55322. *
  55323. * This only supports the cosine drop power as well as Warp fixup generation method.
  55324. *
  55325. * This is using the process from CubeMapGen described here:
  55326. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55327. */
  55328. var PMREMGenerator = (function () {
  55329. /**
  55330. * Constructor of the generator.
  55331. *
  55332. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  55333. * @param inputSize The size of the cubemap faces
  55334. * @param outputSize The size of the output cubemap faces
  55335. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  55336. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  55337. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  55338. * @param specularPower The max specular level of the desired cubemap
  55339. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  55340. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  55341. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  55342. */
  55343. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  55344. this.input = input;
  55345. this.inputSize = inputSize;
  55346. this.outputSize = outputSize;
  55347. this.maxNumMipLevels = maxNumMipLevels;
  55348. this.numChannels = numChannels;
  55349. this.isFloat = isFloat;
  55350. this.specularPower = specularPower;
  55351. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  55352. this.excludeBase = excludeBase;
  55353. this.fixup = fixup;
  55354. this._outputSurface = [];
  55355. this._numMipLevels = 0;
  55356. }
  55357. /**
  55358. * Launches the filter process and return the result.
  55359. *
  55360. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  55361. */
  55362. PMREMGenerator.prototype.filterCubeMap = function () {
  55363. // Init cubemap processor
  55364. this.init();
  55365. // Filters the cubemap
  55366. this.filterCubeMapMipChain();
  55367. // Returns the filtered mips.
  55368. return this._outputSurface;
  55369. };
  55370. PMREMGenerator.prototype.init = function () {
  55371. var i;
  55372. var j;
  55373. var mipLevelSize;
  55374. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  55375. if (this.maxNumMipLevels == 0) {
  55376. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  55377. }
  55378. //first miplevel size
  55379. mipLevelSize = this.outputSize;
  55380. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  55381. for (j = 0; j < this.maxNumMipLevels; j++) {
  55382. this._outputSurface.length++;
  55383. this._outputSurface[j] = [];
  55384. //Iterate over faces for output images
  55385. for (i = 0; i < 6; i++) {
  55386. this._outputSurface[j].length++;
  55387. // Initializes a new array for the output.
  55388. if (this.isFloat) {
  55389. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55390. }
  55391. else {
  55392. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55393. }
  55394. }
  55395. //next mip level is half size
  55396. mipLevelSize >>= 1;
  55397. this._numMipLevels++;
  55398. //terminate if mip chain becomes too small
  55399. if (mipLevelSize == 0) {
  55400. this.maxNumMipLevels = j;
  55401. return;
  55402. }
  55403. }
  55404. };
  55405. //--------------------------------------------------------------------------------------
  55406. //Cube map filtering and mip chain generation.
  55407. // the cube map filtereing is specified using a number of parameters:
  55408. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  55409. // indicates the region of the hemisphere to filter over for each tap.
  55410. //
  55411. // Note that the top mip level is also a filtered version of the original input images
  55412. // as well in order to create mip chains for diffuse environment illumination.
  55413. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  55414. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  55415. //
  55416. // Then the mip angle used to genreate the next level of the mip chain from the first level
  55417. // is a_InitialMipAngle
  55418. //
  55419. // The angle for the subsequent levels of the mip chain are specified by their parents
  55420. // filtering angle and a per-level scale and bias
  55421. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  55422. //
  55423. //--------------------------------------------------------------------------------------
  55424. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  55425. // First, take count of the lighting model to modify SpecularPower
  55426. // 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;
  55427. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  55428. //Cone angle start (for generating subsequent mip levels)
  55429. var currentSpecularPower = this.specularPower;
  55430. //Build filter lookup tables based on the source miplevel size
  55431. this.precomputeFilterLookupTables(this.inputSize);
  55432. // Note that we need to filter the first level before generating mipmap
  55433. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  55434. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  55435. // TODO : Write a function to copy and scale the base mipmap in output
  55436. // I am just lazy here and just put a high specular power value, and do some if.
  55437. if (this.excludeBase && (levelIndex == 0)) {
  55438. // 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).
  55439. currentSpecularPower = 100000.0;
  55440. }
  55441. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  55442. var srcCubeImage = this.input;
  55443. var dstCubeImage = this._outputSurface[levelIndex];
  55444. var dstSize = this.outputSize >> levelIndex;
  55445. // Compute required angle.
  55446. var angle = this.getBaseFilterAngle(currentSpecularPower);
  55447. // filter cube surfaces
  55448. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  55449. // fix seams
  55450. if (this.fixup) {
  55451. this.fixupCubeEdges(dstCubeImage, dstSize);
  55452. }
  55453. // Decrease the specular power to generate the mipmap chain
  55454. // TODO : Use another method for Exclude (see first comment at start of the function
  55455. if (this.excludeBase && (levelIndex == 0)) {
  55456. currentSpecularPower = this.specularPower;
  55457. }
  55458. currentSpecularPower *= this.cosinePowerDropPerMip;
  55459. }
  55460. };
  55461. //--------------------------------------------------------------------------------------
  55462. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  55463. // It allow to optimize the texel to access base on the specular power.
  55464. //--------------------------------------------------------------------------------------
  55465. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  55466. // We want to find the alpha such that:
  55467. // cos(alpha)^cosinePower = epsilon
  55468. // That's: acos(epsilon^(1/cosinePower))
  55469. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  55470. var angle = 180.0;
  55471. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  55472. angle *= 180.0 / Math.PI; // Convert to degree
  55473. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  55474. return angle;
  55475. };
  55476. //--------------------------------------------------------------------------------------
  55477. //Builds the following lookup tables prior to filtering:
  55478. // -normalizer cube map
  55479. // -tap weight lookup table
  55480. //
  55481. //--------------------------------------------------------------------------------------
  55482. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  55483. var srcTexelAngle;
  55484. var iCubeFace;
  55485. //clear pre-existing normalizer cube map
  55486. this._normCubeMap = [];
  55487. //Normalized vectors per cubeface and per-texel solid angle
  55488. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  55489. };
  55490. //--------------------------------------------------------------------------------------
  55491. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  55492. //
  55493. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  55494. //
  55495. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  55496. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  55497. // below
  55498. //--------------------------------------------------------------------------------------
  55499. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  55500. var iCubeFace;
  55501. var u;
  55502. var v;
  55503. //iterate over cube faces
  55504. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55505. //First three channels for norm cube, and last channel for solid angle
  55506. this._normCubeMap.push(new Float32Array(size * size * 4));
  55507. //fast texture walk, build normalizer cube map
  55508. var facesData = this.input[iCubeFace];
  55509. for (v = 0; v < size; v++) {
  55510. for (u = 0; u < size; u++) {
  55511. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  55512. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  55513. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  55514. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  55515. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  55516. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  55517. }
  55518. }
  55519. }
  55520. };
  55521. //--------------------------------------------------------------------------------------
  55522. // Convert cubemap face texel coordinates and face idx to 3D vector
  55523. // note the U and V coords are integer coords and range from 0 to size-1
  55524. // this routine can be used to generate a normalizer cube map
  55525. //--------------------------------------------------------------------------------------
  55526. // SL BEGIN
  55527. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  55528. var nvcU;
  55529. var nvcV;
  55530. var tempVec;
  55531. // Change from original AMD code
  55532. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55533. // + 0.5f is for texel center addressing
  55534. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  55535. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  55536. // warp fixup
  55537. if (fixup && size > 1) {
  55538. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  55539. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  55540. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  55541. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  55542. }
  55543. // Get current vector
  55544. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  55545. // U contribution
  55546. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55547. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  55548. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  55549. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  55550. // V contribution and Sum
  55551. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55552. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  55553. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  55554. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  55555. //add face axis
  55556. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  55557. PMREMGenerator._vectorTemp.x += faceAxis[0];
  55558. PMREMGenerator._vectorTemp.y += faceAxis[1];
  55559. PMREMGenerator._vectorTemp.z += faceAxis[2];
  55560. //normalize vector
  55561. PMREMGenerator._vectorTemp.normalize();
  55562. return PMREMGenerator._vectorTemp;
  55563. };
  55564. //--------------------------------------------------------------------------------------
  55565. // Convert 3D vector to cubemap face texel coordinates and face idx
  55566. // note the U and V coords are integer coords and range from 0 to size-1
  55567. // this routine can be used to generate a normalizer cube map
  55568. //
  55569. // returns face IDX and texel coords
  55570. //--------------------------------------------------------------------------------------
  55571. // SL BEGIN
  55572. /*
  55573. Mapping Texture Coordinates to Cube Map Faces
  55574. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  55575. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  55576. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  55577. map arrangement in Pixar's RenderMan package.
  55578. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  55579. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  55580. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  55581. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  55582. the major axis direction). The target column in the table below explains how the major axis direction
  55583. maps to the 2D image of a particular cube map target.
  55584. major axis
  55585. direction target sc tc ma
  55586. ---------- --------------------------------- --- --- ---
  55587. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  55588. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  55589. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  55590. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  55591. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  55592. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  55593. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  55594. an updated (s,t) is calculated as follows
  55595. s = ( sc/|ma| + 1 ) / 2
  55596. t = ( tc/|ma| + 1 ) / 2
  55597. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  55598. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  55599. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  55600. */
  55601. // Note this method return U and V in range from 0 to size-1
  55602. // SL END
  55603. // Store the information in vector3 for convenience (faceindex, u, v)
  55604. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  55605. var maxCoord;
  55606. var faceIdx;
  55607. //absolute value 3
  55608. var absX = Math.abs(x);
  55609. var absY = Math.abs(y);
  55610. var absZ = Math.abs(z);
  55611. if (absX >= absY && absX >= absZ) {
  55612. maxCoord = absX;
  55613. if (x >= 0) {
  55614. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  55615. }
  55616. else {
  55617. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55618. }
  55619. }
  55620. else if (absY >= absX && absY >= absZ) {
  55621. maxCoord = absY;
  55622. if (y >= 0) {
  55623. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55624. }
  55625. else {
  55626. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55627. }
  55628. }
  55629. else {
  55630. maxCoord = absZ;
  55631. if (z >= 0) {
  55632. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55633. }
  55634. else {
  55635. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55636. }
  55637. }
  55638. //divide through by max coord so face vector lies on cube face
  55639. var scale = 1 / maxCoord;
  55640. x *= scale;
  55641. y *= scale;
  55642. z *= scale;
  55643. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55644. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  55645. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55646. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  55647. // Modify original AMD code to return value from 0 to Size - 1
  55648. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  55649. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  55650. PMREMGenerator._vectorTemp.x = faceIdx;
  55651. PMREMGenerator._vectorTemp.y = u;
  55652. PMREMGenerator._vectorTemp.z = v;
  55653. return PMREMGenerator._vectorTemp;
  55654. };
  55655. //--------------------------------------------------------------------------------------
  55656. //Original code from Ignacio CastaÒo
  55657. // This formula is from Manne ÷hrstrˆm's thesis.
  55658. // Take two coordiantes in the range [-1, 1] that define a portion of a
  55659. // cube face and return the area of the projection of that portion on the
  55660. // surface of the sphere.
  55661. //--------------------------------------------------------------------------------------
  55662. PMREMGenerator.prototype.areaElement = function (x, y) {
  55663. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  55664. };
  55665. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  55666. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55667. // (+ 0.5f is for texel center addressing)
  55668. u = (2.0 * (u + 0.5) / size) - 1.0;
  55669. v = (2.0 * (v + 0.5) / size) - 1.0;
  55670. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  55671. var invResolution = 1.0 / size;
  55672. // U and V are the -1..1 texture coordinate on the current face.
  55673. // Get projected area for this texel
  55674. var x0 = u - invResolution;
  55675. var y0 = v - invResolution;
  55676. var x1 = u + invResolution;
  55677. var y1 = v + invResolution;
  55678. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  55679. return solidAngle;
  55680. };
  55681. //--------------------------------------------------------------------------------------
  55682. //The key to the speed of these filtering routines is to quickly define a per-face
  55683. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  55684. // Later these pixels are selectively processed based on their dot products to see if
  55685. // they reside within the filtering cone.
  55686. //
  55687. //This is done by computing the smallest per-texel angle to get a conservative estimate
  55688. // of the number of texels needed to be covered in width and height order to filter the
  55689. // region. the bounding box for the center taps face is defined first, and if the
  55690. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  55691. // defined next
  55692. //--------------------------------------------------------------------------------------
  55693. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  55694. // note that pixels within these regions may be rejected
  55695. // based on the anlge
  55696. var iCubeFace;
  55697. var u;
  55698. var v;
  55699. // bounding box per face to specify region to process
  55700. var filterExtents = [];
  55701. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55702. filterExtents.push(new CMGBoundinBox());
  55703. }
  55704. // min angle a src texel can cover (in degrees)
  55705. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55706. // angle about center tap to define filter cone
  55707. // filter angle is 1/2 the cone angle
  55708. var filterAngle = filterConeAngle / 2.0;
  55709. //ensure filter angle is larger than a texel
  55710. if (filterAngle < srcTexelAngle) {
  55711. filterAngle = srcTexelAngle;
  55712. }
  55713. //ensure filter cone is always smaller than the hemisphere
  55714. if (filterAngle > 90.0) {
  55715. filterAngle = 90.0;
  55716. }
  55717. // the maximum number of texels in 1D the filter cone angle will cover
  55718. // used to determine bounding box size for filter extents
  55719. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55720. // ensure conservative region always covers at least one texel
  55721. if (filterSize < 1) {
  55722. filterSize = 1;
  55723. }
  55724. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55725. // reside within the cone angle
  55726. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55727. // process required faces
  55728. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55729. //iterate over dst cube map face texel
  55730. for (v = 0; v < dstSize; v++) {
  55731. for (u = 0; u < dstSize; u++) {
  55732. //get center tap direction
  55733. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  55734. //clear old per-face filter extents
  55735. this.clearFilterExtents(filterExtents);
  55736. //define per-face filter extents
  55737. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  55738. //perform filtering of src faces using filter extents
  55739. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  55740. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  55741. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  55742. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  55743. }
  55744. }
  55745. }
  55746. };
  55747. //--------------------------------------------------------------------------------------
  55748. //Clear filter extents for the 6 cube map faces
  55749. //--------------------------------------------------------------------------------------
  55750. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  55751. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  55752. filterExtents[iCubeFaces].clear();
  55753. }
  55754. };
  55755. //--------------------------------------------------------------------------------------
  55756. //Define per-face bounding box filter extents
  55757. //
  55758. // These define conservative texel regions in each of the faces the filter can possibly
  55759. // process. When the pixels in the regions are actually processed, the dot product
  55760. // between the tap vector and the center tap vector is used to determine the weight of
  55761. // the tap and whether or not the tap is within the cone.
  55762. //
  55763. //--------------------------------------------------------------------------------------
  55764. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  55765. //neighboring face and bleed over amount, and width of BBOX for
  55766. // left, right, top, and bottom edges of this face
  55767. var bleedOverAmount = [0, 0, 0, 0];
  55768. var bleedOverBBoxMin = [0, 0, 0, 0];
  55769. var bleedOverBBoxMax = [0, 0, 0, 0];
  55770. var neighborFace;
  55771. var neighborEdge;
  55772. var oppositeFaceIdx;
  55773. //get face idx, and u, v info from center tap dir
  55774. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  55775. var faceIdx = result.x;
  55776. var u = result.y;
  55777. var v = result.z;
  55778. //define bbox size within face
  55779. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  55780. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  55781. filterExtents[faceIdx].clampMin(0, 0, 0);
  55782. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  55783. //u and v extent in face corresponding to center tap
  55784. var minU = filterExtents[faceIdx].min.x;
  55785. var minV = filterExtents[faceIdx].min.y;
  55786. var maxU = filterExtents[faceIdx].max.x;
  55787. var maxV = filterExtents[faceIdx].max.y;
  55788. //bleed over amounts for face across u=0 edge (left)
  55789. bleedOverAmount[0] = (bboxSize - u);
  55790. bleedOverBBoxMin[0] = minV;
  55791. bleedOverBBoxMax[0] = maxV;
  55792. //bleed over amounts for face across u=1 edge (right)
  55793. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  55794. bleedOverBBoxMin[1] = minV;
  55795. bleedOverBBoxMax[1] = maxV;
  55796. //bleed over to face across v=0 edge (up)
  55797. bleedOverAmount[2] = (bboxSize - v);
  55798. bleedOverBBoxMin[2] = minU;
  55799. bleedOverBBoxMax[2] = maxU;
  55800. //bleed over to face across v=1 edge (down)
  55801. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  55802. bleedOverBBoxMin[3] = minU;
  55803. bleedOverBBoxMax[3] = maxU;
  55804. //compute bleed over regions in neighboring faces
  55805. for (var i = 0; i < 4; i++) {
  55806. if (bleedOverAmount[i] > 0) {
  55807. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  55808. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  55809. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  55810. // be flipped: the cases are
  55811. // if a left edge mates with a left or bottom edge on the neighbor
  55812. // if a top edge mates with a top or right edge on the neighbor
  55813. // if a right edge mates with a right or top edge on the neighbor
  55814. // if a bottom edge mates with a bottom or left edge on the neighbor
  55815. //Seeing as the edges are enumerated as follows
  55816. // left =0
  55817. // right =1
  55818. // top =2
  55819. // bottom =3
  55820. //
  55821. // so if the edge enums are the same, or the sum of the enums == 3,
  55822. // the bbox needs to be flipped
  55823. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  55824. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  55825. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  55826. }
  55827. //The way the bounding box is extended onto the neighboring face
  55828. // depends on which edge of neighboring face abuts with this one
  55829. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  55830. case PMREMGenerator.CP_EDGE_LEFT:
  55831. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  55832. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55833. break;
  55834. case PMREMGenerator.CP_EDGE_RIGHT:
  55835. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  55836. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55837. break;
  55838. case PMREMGenerator.CP_EDGE_TOP:
  55839. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  55840. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  55841. break;
  55842. case PMREMGenerator.CP_EDGE_BOTTOM:
  55843. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  55844. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  55845. break;
  55846. }
  55847. //clamp filter extents in non-center tap faces to remain within surface
  55848. filterExtents[neighborFace].clampMin(0, 0, 0);
  55849. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  55850. }
  55851. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  55852. // from the center tap face, then process the opposite face entirely for now.
  55853. //Note that the cases in which this happens, what usually happens is that
  55854. // more than one edge bleeds onto the opposite face, and the bounding box
  55855. // encompasses the entire cube map face.
  55856. if (bleedOverAmount[i] > srcSize) {
  55857. //determine opposite face
  55858. switch (faceIdx) {
  55859. case PMREMGenerator.CP_FACE_X_POS:
  55860. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55861. break;
  55862. case PMREMGenerator.CP_FACE_X_NEG:
  55863. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  55864. break;
  55865. case PMREMGenerator.CP_FACE_Y_POS:
  55866. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55867. break;
  55868. case PMREMGenerator.CP_FACE_Y_NEG:
  55869. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55870. break;
  55871. case PMREMGenerator.CP_FACE_Z_POS:
  55872. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55873. break;
  55874. case PMREMGenerator.CP_FACE_Z_NEG:
  55875. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55876. break;
  55877. default:
  55878. break;
  55879. }
  55880. //just encompass entire face for now
  55881. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  55882. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  55883. }
  55884. }
  55885. };
  55886. //--------------------------------------------------------------------------------------
  55887. //ProcessFilterExtents
  55888. // Process bounding box in each cube face
  55889. //
  55890. //--------------------------------------------------------------------------------------
  55891. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  55892. //accumulators are 64-bit floats in order to have the precision needed
  55893. // over a summation of a large number of pixels
  55894. var dstAccum = [0, 0, 0, 0];
  55895. var weightAccum = 0;
  55896. var k = 0;
  55897. var nSrcChannels = this.numChannels;
  55898. // norm cube map and srcCubeMap have same face width
  55899. var faceWidth = srcSize;
  55900. //amount to add to pointer to move to next scanline in images
  55901. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  55902. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  55903. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  55904. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  55905. // iterate over cubefaces
  55906. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  55907. //if bbox is non empty
  55908. if (!filterExtents[iFaceIdx].empty()) {
  55909. var uStart = filterExtents[iFaceIdx].min.x;
  55910. var vStart = filterExtents[iFaceIdx].min.y;
  55911. var uEnd = filterExtents[iFaceIdx].max.x;
  55912. var vEnd = filterExtents[iFaceIdx].max.y;
  55913. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  55914. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  55915. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  55916. for (var v = vStart; v <= vEnd; v++) {
  55917. var normCubeRowWalk = 0;
  55918. var srcCubeRowWalk = 0;
  55919. for (var u = uStart; u <= uEnd; u++) {
  55920. //pointer to direction in cube map associated with texel
  55921. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  55922. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  55923. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  55924. //check dot product to see if texel is within cone
  55925. var tapDotProd = texelVectX * centerTapDir.x +
  55926. texelVectY * centerTapDir.y +
  55927. texelVectZ * centerTapDir.z;
  55928. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  55929. //solid angle stored in 4th channel of normalizer/solid angle cube map
  55930. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  55931. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  55932. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  55933. // so just adding one to specularpower do the trick.
  55934. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  55935. //iterate over channels
  55936. for (k = 0; k < nSrcChannels; k++) {
  55937. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  55938. srcCubeRowWalk++;
  55939. }
  55940. weightAccum += weight; //accumulate weight
  55941. }
  55942. else {
  55943. //step across source pixel
  55944. srcCubeRowWalk += nSrcChannels;
  55945. }
  55946. normCubeRowWalk += 4; // 4 channels per norm cube map.
  55947. }
  55948. startIndexNormCubeMap += normCubePitch;
  55949. startIndexSrcCubeMap += srcCubePitch;
  55950. }
  55951. }
  55952. }
  55953. //divide through by weights if weight is non zero
  55954. if (weightAccum != 0.0) {
  55955. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  55956. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  55957. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  55958. if (this.numChannels > 3) {
  55959. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  55960. }
  55961. }
  55962. else {
  55963. // otherwise sample nearest
  55964. // get face idx and u, v texel coordinate in face
  55965. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  55966. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  55967. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  55968. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  55969. if (this.numChannels > 3) {
  55970. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  55971. }
  55972. }
  55973. return PMREMGenerator._vectorTemp;
  55974. };
  55975. //--------------------------------------------------------------------------------------
  55976. // Fixup cube edges
  55977. //
  55978. // average texels on cube map faces across the edges
  55979. // WARP/BENT Method Only.
  55980. //--------------------------------------------------------------------------------------
  55981. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  55982. var k;
  55983. var j;
  55984. var i;
  55985. var iFace;
  55986. var iCorner = 0;
  55987. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  55988. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  55989. // note that if functionality to filter across the three texels for each corner, then
  55990. //indexed by corner and face idx. the array contains the face the start points belongs to.
  55991. var cornerPtr = [
  55992. [[], [], []],
  55993. [[], [], []],
  55994. [[], [], []],
  55995. [[], [], []],
  55996. [[], [], []],
  55997. [[], [], []],
  55998. [[], [], []],
  55999. [[], [], []]
  56000. ];
  56001. //if there is no fixup, or fixup width = 0, do nothing
  56002. if (cubeMapSize < 1) {
  56003. return;
  56004. }
  56005. //special case 1x1 cubemap, average face colors
  56006. if (cubeMapSize == 1) {
  56007. //iterate over channels
  56008. for (k = 0; k < this.numChannels; k++) {
  56009. var accum = 0.0;
  56010. //iterate over faces to accumulate face colors
  56011. for (iFace = 0; iFace < 6; iFace++) {
  56012. accum += cubeMap[iFace][k];
  56013. }
  56014. //compute average over 6 face colors
  56015. accum /= 6.0;
  56016. //iterate over faces to distribute face colors
  56017. for (iFace = 0; iFace < 6; iFace++) {
  56018. cubeMap[iFace][k] = accum;
  56019. }
  56020. }
  56021. return;
  56022. }
  56023. //iterate over faces to collect list of corner texel pointers
  56024. for (iFace = 0; iFace < 6; iFace++) {
  56025. //the 4 corner pointers for this face
  56026. faceCornerStartIndicies[0] = [iFace, 0];
  56027. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  56028. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  56029. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  56030. //iterate over face corners to collect cube corner pointers
  56031. for (iCorner = 0; iCorner < 4; iCorner++) {
  56032. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  56033. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  56034. cornerNumPtrs[corner]++;
  56035. }
  56036. }
  56037. //iterate over corners to average across corner tap values
  56038. for (iCorner = 0; iCorner < 8; iCorner++) {
  56039. for (k = 0; k < this.numChannels; k++) {
  56040. var cornerTapAccum = 0.0;
  56041. //iterate over corner texels and average results
  56042. for (i = 0; i < 3; i++) {
  56043. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  56044. }
  56045. //divide by 3 to compute average of corner tap values
  56046. cornerTapAccum *= (1.0 / 3.0);
  56047. //iterate over corner texels and average results
  56048. for (i = 0; i < 3; i++) {
  56049. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  56050. }
  56051. }
  56052. }
  56053. //iterate over the twelve edges of the cube to average across edges
  56054. for (i = 0; i < 12; i++) {
  56055. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  56056. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  56057. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  56058. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  56059. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  56060. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  56061. var edgeWalk = 0;
  56062. var neighborEdgeWalk = 0;
  56063. //Determine walking pointers based on edge type
  56064. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  56065. switch (edge) {
  56066. case PMREMGenerator.CP_EDGE_LEFT:
  56067. // no change to faceEdgeStartPtr
  56068. edgeWalk = this.numChannels * cubeMapSize;
  56069. break;
  56070. case PMREMGenerator.CP_EDGE_RIGHT:
  56071. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56072. edgeWalk = this.numChannels * cubeMapSize;
  56073. break;
  56074. case PMREMGenerator.CP_EDGE_TOP:
  56075. // no change to faceEdgeStartPtr
  56076. edgeWalk = this.numChannels;
  56077. break;
  56078. case PMREMGenerator.CP_EDGE_BOTTOM:
  56079. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56080. edgeWalk = this.numChannels;
  56081. break;
  56082. }
  56083. //For certain types of edge abutments, the neighbor edge walk needs to
  56084. // be flipped: the cases are
  56085. // if a left edge mates with a left or bottom edge on the neighbor
  56086. // if a top edge mates with a top or right edge on the neighbor
  56087. // if a right edge mates with a right or top edge on the neighbor
  56088. // if a bottom edge mates with a bottom or left edge on the neighbor
  56089. //Seeing as the edges are enumerated as follows
  56090. // left =0
  56091. // right =1
  56092. // top =2
  56093. // bottom =3
  56094. //
  56095. //If the edge enums are the same, or the sum of the enums == 3,
  56096. // the neighbor edge walk needs to be flipped
  56097. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  56098. switch (neighborEdge) {
  56099. case PMREMGenerator.CP_EDGE_LEFT:
  56100. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  56101. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56102. break;
  56103. case PMREMGenerator.CP_EDGE_RIGHT:
  56104. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56105. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56106. break;
  56107. case PMREMGenerator.CP_EDGE_TOP:
  56108. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56109. neighborEdgeWalk = -this.numChannels;
  56110. break;
  56111. case PMREMGenerator.CP_EDGE_BOTTOM:
  56112. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56113. neighborEdgeWalk = -this.numChannels;
  56114. break;
  56115. }
  56116. }
  56117. else {
  56118. //swapped direction neighbor edge walk
  56119. switch (neighborEdge) {
  56120. case PMREMGenerator.CP_EDGE_LEFT:
  56121. //no change to neighborEdgeStartPtr for this case since it points
  56122. // to the upper left corner already
  56123. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56124. break;
  56125. case PMREMGenerator.CP_EDGE_RIGHT:
  56126. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56127. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56128. break;
  56129. case PMREMGenerator.CP_EDGE_TOP:
  56130. //no change to neighborEdgeStartPtr for this case since it points
  56131. // to the upper left corner already
  56132. neighborEdgeWalk = this.numChannels;
  56133. break;
  56134. case PMREMGenerator.CP_EDGE_BOTTOM:
  56135. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56136. neighborEdgeWalk = this.numChannels;
  56137. break;
  56138. }
  56139. }
  56140. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  56141. //nearby neighborhood
  56142. //step ahead one texel on edge
  56143. edgeStartIndex += edgeWalk;
  56144. neighborEdgeStartIndex += neighborEdgeWalk;
  56145. // note that this loop does not process the corner texels, since they have already been
  56146. // averaged across faces across earlier
  56147. for (j = 1; j < (cubeMapSize - 1); j++) {
  56148. //for each set of taps along edge, average them
  56149. // and rewrite the results into the edges
  56150. for (k = 0; k < this.numChannels; k++) {
  56151. var edgeTap = cubeMap[face][edgeStartIndex + k];
  56152. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  56153. //compute average of tap intensity values
  56154. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  56155. //propagate average of taps to edge taps
  56156. cubeMap[face][edgeStartIndex + k] = avgTap;
  56157. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  56158. }
  56159. edgeStartIndex += edgeWalk;
  56160. neighborEdgeStartIndex += neighborEdgeWalk;
  56161. }
  56162. }
  56163. };
  56164. return PMREMGenerator;
  56165. }());
  56166. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  56167. PMREMGenerator.CP_UDIR = 0;
  56168. PMREMGenerator.CP_VDIR = 1;
  56169. PMREMGenerator.CP_FACEAXIS = 2;
  56170. //used to index cube faces
  56171. PMREMGenerator.CP_FACE_X_POS = 0;
  56172. PMREMGenerator.CP_FACE_X_NEG = 1;
  56173. PMREMGenerator.CP_FACE_Y_POS = 2;
  56174. PMREMGenerator.CP_FACE_Y_NEG = 3;
  56175. PMREMGenerator.CP_FACE_Z_POS = 4;
  56176. PMREMGenerator.CP_FACE_Z_NEG = 5;
  56177. //used to index image edges
  56178. // NOTE.. the actual number corresponding to the edge is important
  56179. // do not change these, or the code will break
  56180. //
  56181. // CP_EDGE_LEFT is u = 0
  56182. // CP_EDGE_RIGHT is u = width-1
  56183. // CP_EDGE_TOP is v = 0
  56184. // CP_EDGE_BOTTOM is v = height-1
  56185. PMREMGenerator.CP_EDGE_LEFT = 0;
  56186. PMREMGenerator.CP_EDGE_RIGHT = 1;
  56187. PMREMGenerator.CP_EDGE_TOP = 2;
  56188. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  56189. //corners of CUBE map (P or N specifys if it corresponds to the
  56190. // positive or negative direction each of X, Y, and Z
  56191. PMREMGenerator.CP_CORNER_NNN = 0;
  56192. PMREMGenerator.CP_CORNER_NNP = 1;
  56193. PMREMGenerator.CP_CORNER_NPN = 2;
  56194. PMREMGenerator.CP_CORNER_NPP = 3;
  56195. PMREMGenerator.CP_CORNER_PNN = 4;
  56196. PMREMGenerator.CP_CORNER_PNP = 5;
  56197. PMREMGenerator.CP_CORNER_PPN = 6;
  56198. PMREMGenerator.CP_CORNER_PPP = 7;
  56199. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  56200. //3x2 matrices that map cube map indexing vectors in 3d
  56201. // (after face selection and divide through by the
  56202. // _ABSOLUTE VALUE_ of the max coord)
  56203. // into NVC space
  56204. //Note this currently assumes the D3D cube face ordering and orientation
  56205. PMREMGenerator._sgFace2DMapping = [
  56206. //XPOS face
  56207. [[0, 0, -1],
  56208. [0, -1, 0],
  56209. [1, 0, 0]],
  56210. //XNEG face
  56211. [[0, 0, 1],
  56212. [0, -1, 0],
  56213. [-1, 0, 0]],
  56214. //YPOS face
  56215. [[1, 0, 0],
  56216. [0, 0, 1],
  56217. [0, 1, 0]],
  56218. //YNEG face
  56219. [[1, 0, 0],
  56220. [0, 0, -1],
  56221. [0, -1, 0]],
  56222. //ZPOS face
  56223. [[1, 0, 0],
  56224. [0, -1, 0],
  56225. [0, 0, 1]],
  56226. //ZNEG face
  56227. [[-1, 0, 0],
  56228. [0, -1, 0],
  56229. [0, 0, -1]],
  56230. ];
  56231. //------------------------------------------------------------------------------
  56232. // D3D cube map face specification
  56233. // mapping from 3D x,y,z cube map lookup coordinates
  56234. // to 2D within face u,v coordinates
  56235. //
  56236. // --------------------> U direction
  56237. // | (within-face texture space)
  56238. // | _____
  56239. // | | |
  56240. // | | +Y |
  56241. // | _____|_____|_____ _____
  56242. // | | | | | |
  56243. // | | -X | +Z | +X | -Z |
  56244. // | |_____|_____|_____|_____|
  56245. // | | |
  56246. // | | -Y |
  56247. // | |_____|
  56248. // |
  56249. // v V direction
  56250. // (within-face texture space)
  56251. //------------------------------------------------------------------------------
  56252. //Information about neighbors and how texture coorrdinates change across faces
  56253. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  56254. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  56255. //Note this currently assumes the D3D cube face ordering and orientation
  56256. PMREMGenerator._sgCubeNgh = [
  56257. //XPOS face
  56258. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56259. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56260. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56261. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  56262. //XNEG face
  56263. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56264. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  56265. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  56266. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  56267. //YPOS face
  56268. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56269. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56270. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56271. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  56272. //YNEG face
  56273. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56274. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56275. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56276. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  56277. //ZPOS face
  56278. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56279. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56280. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56281. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  56282. //ZNEG face
  56283. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56284. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56285. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  56286. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  56287. ];
  56288. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  56289. // this table is used to average over the edges.
  56290. PMREMGenerator._sgCubeEdgeList = [
  56291. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56292. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56293. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56294. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56295. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56296. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56297. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56298. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56299. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  56300. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56301. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56302. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  56303. ];
  56304. //Information about which of the 8 cube corners are correspond to the
  56305. // the 4 corners in each cube face
  56306. // the order is upper left, upper right, lower left, lower right
  56307. PMREMGenerator._sgCubeCornerList = [
  56308. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  56309. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  56310. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  56311. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  56312. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  56313. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  56314. ];
  56315. Internals.PMREMGenerator = PMREMGenerator;
  56316. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56317. })(BABYLON || (BABYLON = {}));
  56318. //# sourceMappingURL=babylon.pmremgenerator.js.map
  56319. var BABYLON;
  56320. (function (BABYLON) {
  56321. /**
  56322. * This represents a texture coming from an HDR input.
  56323. *
  56324. * The only supported format is currently panorama picture stored in RGBE format.
  56325. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56326. */
  56327. var HDRCubeTexture = (function (_super) {
  56328. __extends(HDRCubeTexture, _super);
  56329. /**
  56330. * Instantiates an HDRTexture from the following parameters.
  56331. *
  56332. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56333. * @param scene The scene the texture will be used in
  56334. * @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.
  56335. * @param noMipmap Forces to not generate the mipmap if true
  56336. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56337. * @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)
  56338. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56339. */
  56340. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  56341. if (noMipmap === void 0) { noMipmap = false; }
  56342. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56343. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56344. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56345. if (onLoad === void 0) { onLoad = null; }
  56346. if (onError === void 0) { onError = null; }
  56347. var _this = _super.call(this, scene) || this;
  56348. _this._useInGammaSpace = false;
  56349. _this._generateHarmonics = true;
  56350. _this._isBABYLONPreprocessed = false;
  56351. _this._onLoad = null;
  56352. _this._onError = null;
  56353. /**
  56354. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56355. */
  56356. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56357. /**
  56358. * The spherical polynomial data extracted from the texture.
  56359. */
  56360. _this.sphericalPolynomial = null;
  56361. /**
  56362. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56363. * This is usefull at run time to apply the good shader.
  56364. */
  56365. _this.isPMREM = false;
  56366. _this._isBlocking = true;
  56367. if (!url) {
  56368. return _this;
  56369. }
  56370. _this.name = url;
  56371. _this.url = url;
  56372. _this.hasAlpha = false;
  56373. _this.isCube = true;
  56374. _this._textureMatrix = BABYLON.Matrix.Identity();
  56375. _this._onLoad = onLoad;
  56376. _this._onError = onError;
  56377. if (size) {
  56378. _this._isBABYLONPreprocessed = false;
  56379. _this._noMipmap = noMipmap;
  56380. _this._size = size;
  56381. _this._useInGammaSpace = useInGammaSpace;
  56382. _this._usePMREMGenerator = usePMREMGenerator &&
  56383. scene.getEngine().getCaps().textureLOD &&
  56384. _this.getScene().getEngine().getCaps().textureFloat &&
  56385. !_this._useInGammaSpace;
  56386. }
  56387. else {
  56388. _this._isBABYLONPreprocessed = true;
  56389. _this._noMipmap = false;
  56390. _this._useInGammaSpace = false;
  56391. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56392. _this.getScene().getEngine().getCaps().textureFloat &&
  56393. !_this._useInGammaSpace;
  56394. }
  56395. _this.isPMREM = _this._usePMREMGenerator;
  56396. _this._texture = _this._getFromCache(url, _this._noMipmap);
  56397. if (!_this._texture) {
  56398. if (!scene.useDelayedTextureLoading) {
  56399. _this.loadTexture();
  56400. }
  56401. else {
  56402. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56403. }
  56404. }
  56405. return _this;
  56406. }
  56407. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  56408. /**
  56409. * Gets wether or not the texture is blocking during loading.
  56410. */
  56411. get: function () {
  56412. return this._isBlocking;
  56413. },
  56414. /**
  56415. * Sets wether or not the texture is blocking during loading.
  56416. */
  56417. set: function (value) {
  56418. this._isBlocking = value;
  56419. },
  56420. enumerable: true,
  56421. configurable: true
  56422. });
  56423. /**
  56424. * Occurs when the file is a preprocessed .babylon.hdr file.
  56425. */
  56426. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56427. var _this = this;
  56428. var mipLevels = 0;
  56429. var floatArrayView = null;
  56430. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56431. var mips = [];
  56432. var startIndex = 30;
  56433. for (var level = 0; level < mipLevels; level++) {
  56434. mips.push([]);
  56435. // Fill each pixel of the mip level.
  56436. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56437. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56438. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56439. mips[level].push(faceData);
  56440. startIndex += faceSize;
  56441. }
  56442. }
  56443. return mips;
  56444. } : null;
  56445. var callback = function (buffer) {
  56446. // Create Native Array Views
  56447. var intArrayView = new Int32Array(buffer);
  56448. floatArrayView = new Float32Array(buffer);
  56449. // Fill header.
  56450. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56451. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56452. // Update Texture Information.
  56453. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56454. // Fill polynomial information.
  56455. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56456. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56457. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56458. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56459. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56460. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56461. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56462. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56463. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56464. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56465. // Fill pixel data.
  56466. mipLevels = intArrayView[29]; // Number of mip levels.
  56467. var startIndex = 30;
  56468. var data = [];
  56469. var faceSize = Math.pow(_this._size, 2) * 3;
  56470. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56471. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56472. startIndex += faceSize;
  56473. }
  56474. var results = [];
  56475. var byteArray = null;
  56476. // Push each faces.
  56477. for (var k = 0; k < 6; k++) {
  56478. var dataFace = null;
  56479. // If special cases.
  56480. if (!mipmapGenerator) {
  56481. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  56482. dataFace = data[j];
  56483. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56484. // 3 channels of 1 bytes per pixel in bytes.
  56485. var byteBuffer = new ArrayBuffer(faceSize);
  56486. byteArray = new Uint8Array(byteBuffer);
  56487. }
  56488. for (var i = 0; i < _this._size * _this._size; i++) {
  56489. // Put in gamma space if requested.
  56490. if (_this._useInGammaSpace) {
  56491. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56492. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56493. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56494. }
  56495. // Convert to int texture for fallback.
  56496. if (byteArray) {
  56497. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56498. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56499. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56500. // May use luminance instead if the result is not accurate.
  56501. var max = Math.max(Math.max(r, g), b);
  56502. if (max > 255) {
  56503. var scale = 255 / max;
  56504. r *= scale;
  56505. g *= scale;
  56506. b *= scale;
  56507. }
  56508. byteArray[(i * 3) + 0] = r;
  56509. byteArray[(i * 3) + 1] = g;
  56510. byteArray[(i * 3) + 2] = b;
  56511. }
  56512. }
  56513. }
  56514. else {
  56515. dataFace = data[k];
  56516. }
  56517. // Fill the array accordingly.
  56518. if (byteArray) {
  56519. results.push(byteArray);
  56520. }
  56521. else {
  56522. results.push(dataFace);
  56523. }
  56524. }
  56525. return results;
  56526. };
  56527. 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);
  56528. };
  56529. /**
  56530. * Occurs when the file is raw .hdr file.
  56531. */
  56532. HDRCubeTexture.prototype.loadHDRTexture = function () {
  56533. var _this = this;
  56534. var callback = function (buffer) {
  56535. // Extract the raw linear data.
  56536. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  56537. // Generate harmonics if needed.
  56538. if (_this._generateHarmonics) {
  56539. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  56540. }
  56541. var results = [];
  56542. var byteArray = null;
  56543. // Push each faces.
  56544. for (var j = 0; j < 6; j++) {
  56545. // Create uintarray fallback.
  56546. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56547. // 3 channels of 1 bytes per pixel in bytes.
  56548. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  56549. byteArray = new Uint8Array(byteBuffer);
  56550. }
  56551. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  56552. // If special cases.
  56553. if (_this._useInGammaSpace || byteArray) {
  56554. for (var i = 0; i < _this._size * _this._size; i++) {
  56555. // Put in gamma space if requested.
  56556. if (_this._useInGammaSpace) {
  56557. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56558. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56559. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56560. }
  56561. // Convert to int texture for fallback.
  56562. if (byteArray) {
  56563. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56564. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56565. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56566. // May use luminance instead if the result is not accurate.
  56567. var max = Math.max(Math.max(r, g), b);
  56568. if (max > 255) {
  56569. var scale = 255 / max;
  56570. r *= scale;
  56571. g *= scale;
  56572. b *= scale;
  56573. }
  56574. byteArray[(i * 3) + 0] = r;
  56575. byteArray[(i * 3) + 1] = g;
  56576. byteArray[(i * 3) + 2] = b;
  56577. }
  56578. }
  56579. }
  56580. if (byteArray) {
  56581. results.push(byteArray);
  56582. }
  56583. else {
  56584. results.push(dataFace);
  56585. }
  56586. }
  56587. return results;
  56588. };
  56589. var mipmapGenerator = null;
  56590. if (!this._noMipmap &&
  56591. this._usePMREMGenerator) {
  56592. mipmapGenerator = function (data) {
  56593. // Custom setup of the generator matching with the PBR shader values.
  56594. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  56595. return generator.filterCubeMap();
  56596. };
  56597. }
  56598. 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);
  56599. };
  56600. /**
  56601. * Starts the loading process of the texture.
  56602. */
  56603. HDRCubeTexture.prototype.loadTexture = function () {
  56604. if (this._isBABYLONPreprocessed) {
  56605. this.loadBabylonTexture();
  56606. }
  56607. else {
  56608. this.loadHDRTexture();
  56609. }
  56610. };
  56611. HDRCubeTexture.prototype.clone = function () {
  56612. var size = this._isBABYLONPreprocessed ? null : this._size;
  56613. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56614. // Base texture
  56615. newTexture.level = this.level;
  56616. newTexture.wrapU = this.wrapU;
  56617. newTexture.wrapV = this.wrapV;
  56618. newTexture.coordinatesIndex = this.coordinatesIndex;
  56619. newTexture.coordinatesMode = this.coordinatesMode;
  56620. return newTexture;
  56621. };
  56622. // Methods
  56623. HDRCubeTexture.prototype.delayLoad = function () {
  56624. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56625. return;
  56626. }
  56627. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56628. this._texture = this._getFromCache(this.url, this._noMipmap);
  56629. if (!this._texture) {
  56630. this.loadTexture();
  56631. }
  56632. };
  56633. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56634. return this._textureMatrix;
  56635. };
  56636. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56637. var texture = null;
  56638. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56639. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56640. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  56641. texture.name = parsedTexture.name;
  56642. texture.hasAlpha = parsedTexture.hasAlpha;
  56643. texture.level = parsedTexture.level;
  56644. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56645. texture.isBlocking = parsedTexture.isBlocking;
  56646. }
  56647. return texture;
  56648. };
  56649. HDRCubeTexture.prototype.serialize = function () {
  56650. if (!this.name) {
  56651. return null;
  56652. }
  56653. var serializationObject = {};
  56654. serializationObject.name = this.name;
  56655. serializationObject.hasAlpha = this.hasAlpha;
  56656. serializationObject.isCube = true;
  56657. serializationObject.level = this.level;
  56658. serializationObject.size = this._size;
  56659. serializationObject.coordinatesMode = this.coordinatesMode;
  56660. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56661. serializationObject.generateHarmonics = this._generateHarmonics;
  56662. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56663. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56664. serializationObject.customType = "BABYLON.HDRCubeTexture";
  56665. serializationObject.noMipmap = this._noMipmap;
  56666. serializationObject.isBlocking = this._isBlocking;
  56667. return serializationObject;
  56668. };
  56669. /**
  56670. * Saves as a file the data contained in the texture in a binary format.
  56671. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56672. * as the spherical used in the lighting.
  56673. * @param url The HDR file url.
  56674. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56675. * @param onError Method called if any error happens during download.
  56676. * @return The packed binary data.
  56677. */
  56678. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56679. if (onError === void 0) { onError = null; }
  56680. var callback = function (buffer) {
  56681. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56682. // Returns a URL you can use as a href.
  56683. var objUrl = window.URL.createObjectURL(data);
  56684. // Simulates a link to it and click to dowload.
  56685. var a = document.createElement("a");
  56686. document.body.appendChild(a);
  56687. a.style.display = "none";
  56688. a.href = objUrl;
  56689. a.download = "envmap.babylon.hdr";
  56690. a.click();
  56691. };
  56692. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56693. };
  56694. /**
  56695. * Serializes the data contained in the texture in a binary format.
  56696. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56697. * as the spherical used in the lighting.
  56698. * @param url The HDR file url.
  56699. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56700. * @param onError Method called if any error happens during download.
  56701. * @return The packed binary data.
  56702. */
  56703. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56704. if (onError === void 0) { onError = null; }
  56705. // Needs the url tho create the texture.
  56706. if (!url) {
  56707. return null;
  56708. }
  56709. // Check Power of two size.
  56710. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56711. return null;
  56712. }
  56713. var getDataCallback = function (dataBuffer) {
  56714. // Extract the raw linear data.
  56715. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  56716. // Generate harmonics if needed.
  56717. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  56718. // Generate seamless faces
  56719. var mipGeneratorArray = [];
  56720. // Data are known to be in +X +Y +Z -X -Y -Z
  56721. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56722. mipGeneratorArray.push(cubeData.right); // +X
  56723. mipGeneratorArray.push(cubeData.left); // -X
  56724. mipGeneratorArray.push(cubeData.up); // +Y
  56725. mipGeneratorArray.push(cubeData.down); // -Y
  56726. mipGeneratorArray.push(cubeData.front); // +Z
  56727. mipGeneratorArray.push(cubeData.back); // -Z
  56728. // Custom setup of the generator matching with the PBR shader values.
  56729. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56730. var mippedData = generator.filterCubeMap();
  56731. // Compute required byte length.
  56732. var byteLength = 1 * 4; // Raw Data Version int32.
  56733. byteLength += 4; // CubeMap max mip face size int32.
  56734. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56735. // Add data size.
  56736. byteLength += 4; // Number of mip levels int32.
  56737. for (var level = 0; level < mippedData.length; level++) {
  56738. var mipSize = size >> level;
  56739. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56740. }
  56741. // Prepare binary structure.
  56742. var buffer = new ArrayBuffer(byteLength);
  56743. var intArrayView = new Int32Array(buffer);
  56744. var floatArrayView = new Float32Array(buffer);
  56745. // Fill header.
  56746. intArrayView[0] = 1; // Version 1.
  56747. intArrayView[1] = size; // CubeMap max mip face size.
  56748. // Fill polynomial information.
  56749. sphericalPolynomial.x.toArray(floatArrayView, 2);
  56750. sphericalPolynomial.y.toArray(floatArrayView, 5);
  56751. sphericalPolynomial.z.toArray(floatArrayView, 8);
  56752. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  56753. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  56754. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  56755. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  56756. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  56757. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  56758. // Fill pixel data.
  56759. intArrayView[29] = mippedData.length; // Number of mip levels.
  56760. var startIndex = 30;
  56761. for (var level = 0; level < mippedData.length; level++) {
  56762. // Fill each pixel of the mip level.
  56763. var faceSize = Math.pow(size >> level, 2) * 3;
  56764. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56765. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  56766. startIndex += faceSize;
  56767. }
  56768. }
  56769. // Callback.
  56770. callback(buffer);
  56771. };
  56772. // Download and process.
  56773. BABYLON.Tools.LoadFile(url, function (data) {
  56774. getDataCallback(data);
  56775. }, null, null, true, onError);
  56776. };
  56777. return HDRCubeTexture;
  56778. }(BABYLON.BaseTexture));
  56779. HDRCubeTexture._facesMapping = [
  56780. "right",
  56781. "up",
  56782. "front",
  56783. "left",
  56784. "down",
  56785. "back"
  56786. ];
  56787. BABYLON.HDRCubeTexture = HDRCubeTexture;
  56788. })(BABYLON || (BABYLON = {}));
  56789. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  56790. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  56791. // Huge respect for a such great lib.
  56792. // Earcut license:
  56793. // Copyright (c) 2016, Mapbox
  56794. //
  56795. // Permission to use, copy, modify, and/or distribute this software for any purpose
  56796. // with or without fee is hereby granted, provided that the above copyright notice
  56797. // and this permission notice appear in all copies.
  56798. //
  56799. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  56800. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  56801. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  56802. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  56803. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  56804. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  56805. // THIS SOFTWARE.
  56806. var Earcut;
  56807. (function (Earcut) {
  56808. /**
  56809. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  56810. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  56811. * @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).
  56812. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  56813. */
  56814. function earcut(data, holeIndices, dim) {
  56815. dim = dim || 2;
  56816. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  56817. if (!outerNode)
  56818. return triangles;
  56819. var minX, minY, maxX, maxY, x, y, size;
  56820. if (hasHoles)
  56821. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  56822. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  56823. if (data.length > 80 * dim) {
  56824. minX = maxX = data[0];
  56825. minY = maxY = data[1];
  56826. for (var i = dim; i < outerLen; i += dim) {
  56827. x = data[i];
  56828. y = data[i + 1];
  56829. if (x < minX)
  56830. minX = x;
  56831. if (y < minY)
  56832. minY = y;
  56833. if (x > maxX)
  56834. maxX = x;
  56835. if (y > maxY)
  56836. maxY = y;
  56837. }
  56838. // minX, minY and size are later used to transform coords into integers for z-order calculation
  56839. size = Math.max(maxX - minX, maxY - minY);
  56840. }
  56841. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  56842. return triangles;
  56843. }
  56844. Earcut.earcut = earcut;
  56845. // create a circular doubly linked list from polygon points in the specified winding order
  56846. function linkedList(data, start, end, dim, clockwise) {
  56847. var i, last;
  56848. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  56849. for (i = start; i < end; i += dim)
  56850. last = insertNode(i, data[i], data[i + 1], last);
  56851. }
  56852. else {
  56853. for (i = end - dim; i >= start; i -= dim)
  56854. last = insertNode(i, data[i], data[i + 1], last);
  56855. }
  56856. if (last && equals(last, last.next)) {
  56857. removeNode(last);
  56858. last = last.next;
  56859. }
  56860. return last;
  56861. }
  56862. // eliminate colinear or duplicate points
  56863. function filterPoints(start, end) {
  56864. if (!start)
  56865. return start;
  56866. if (!end)
  56867. end = start;
  56868. var p = start, again;
  56869. do {
  56870. again = false;
  56871. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  56872. removeNode(p);
  56873. p = end = p.prev;
  56874. if (p === p.next)
  56875. return null;
  56876. again = true;
  56877. }
  56878. else {
  56879. p = p.next;
  56880. }
  56881. } while (again || p !== end);
  56882. return end;
  56883. }
  56884. // main ear slicing loop which triangulates a polygon (given as a linked list)
  56885. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  56886. if (!ear)
  56887. return;
  56888. // interlink polygon nodes in z-order
  56889. if (!pass && size)
  56890. indexCurve(ear, minX, minY, size);
  56891. var stop = ear, prev, next;
  56892. // iterate through ears, slicing them one by one
  56893. while (ear.prev !== ear.next) {
  56894. prev = ear.prev;
  56895. next = ear.next;
  56896. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  56897. // cut off the triangle
  56898. triangles.push(prev.i / dim);
  56899. triangles.push(ear.i / dim);
  56900. triangles.push(next.i / dim);
  56901. removeNode(ear);
  56902. // skipping the next vertice leads to less sliver triangles
  56903. ear = next.next;
  56904. stop = next.next;
  56905. continue;
  56906. }
  56907. ear = next;
  56908. // if we looped through the whole remaining polygon and can't find any more ears
  56909. if (ear === stop) {
  56910. // try filtering points and slicing again
  56911. if (!pass) {
  56912. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  56913. // if this didn't work, try curing all small self-intersections locally
  56914. }
  56915. else if (pass === 1) {
  56916. ear = cureLocalIntersections(ear, triangles, dim);
  56917. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  56918. // as a last resort, try splitting the remaining polygon into two
  56919. }
  56920. else if (pass === 2) {
  56921. splitEarcut(ear, triangles, dim, minX, minY, size);
  56922. }
  56923. break;
  56924. }
  56925. }
  56926. }
  56927. // check whether a polygon node forms a valid ear with adjacent nodes
  56928. function isEar(ear) {
  56929. var a = ear.prev, b = ear, c = ear.next;
  56930. if (area(a, b, c) >= 0)
  56931. return false; // reflex, can't be an ear
  56932. // now make sure we don't have other points inside the potential ear
  56933. var p = ear.next.next;
  56934. while (p !== ear.prev) {
  56935. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56936. area(p.prev, p, p.next) >= 0)
  56937. return false;
  56938. p = p.next;
  56939. }
  56940. return true;
  56941. }
  56942. function isEarHashed(ear, minX, minY, size) {
  56943. var a = ear.prev, b = ear, c = ear.next;
  56944. if (area(a, b, c) >= 0)
  56945. return false; // reflex, can't be an ear
  56946. // triangle bbox; min & max are calculated like this for speed
  56947. 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);
  56948. // z-order range for the current triangle bbox;
  56949. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  56950. // first look for points inside the triangle in increasing z-order
  56951. var p = ear.nextZ;
  56952. while (p && p.z <= maxZ) {
  56953. if (p !== ear.prev &&
  56954. p !== ear.next &&
  56955. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56956. area(p.prev, p, p.next) >= 0)
  56957. return false;
  56958. p = p.nextZ;
  56959. }
  56960. // then look for points in decreasing z-order
  56961. p = ear.prevZ;
  56962. while (p && p.z >= minZ) {
  56963. if (p !== ear.prev &&
  56964. p !== ear.next &&
  56965. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56966. area(p.prev, p, p.next) >= 0)
  56967. return false;
  56968. p = p.prevZ;
  56969. }
  56970. return true;
  56971. }
  56972. // go through all polygon nodes and cure small local self-intersections
  56973. function cureLocalIntersections(start, triangles, dim) {
  56974. var p = start;
  56975. do {
  56976. var a = p.prev, b = p.next.next;
  56977. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  56978. triangles.push(a.i / dim);
  56979. triangles.push(p.i / dim);
  56980. triangles.push(b.i / dim);
  56981. // remove two nodes involved
  56982. removeNode(p);
  56983. removeNode(p.next);
  56984. p = start = b;
  56985. }
  56986. p = p.next;
  56987. } while (p !== start);
  56988. return p;
  56989. }
  56990. // try splitting polygon into two and triangulate them independently
  56991. function splitEarcut(start, triangles, dim, minX, minY, size) {
  56992. // look for a valid diagonal that divides the polygon into two
  56993. var a = start;
  56994. do {
  56995. var b = a.next.next;
  56996. while (b !== a.prev) {
  56997. if (a.i !== b.i && isValidDiagonal(a, b)) {
  56998. // split the polygon in two by the diagonal
  56999. var c = splitPolygon(a, b);
  57000. // filter colinear points around the cuts
  57001. a = filterPoints(a, a.next);
  57002. c = filterPoints(c, c.next);
  57003. // run earcut on each half
  57004. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  57005. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  57006. return;
  57007. }
  57008. b = b.next;
  57009. }
  57010. a = a.next;
  57011. } while (a !== start);
  57012. }
  57013. // link every hole into the outer loop, producing a single-ring polygon without holes
  57014. function eliminateHoles(data, holeIndices, outerNode, dim) {
  57015. var queue = [], i, len, start, end, list;
  57016. for (i = 0, len = holeIndices.length; i < len; i++) {
  57017. start = holeIndices[i] * dim;
  57018. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57019. list = linkedList(data, start, end, dim, false);
  57020. if (list === list.next)
  57021. list.steiner = true;
  57022. queue.push(getLeftmost(list));
  57023. }
  57024. queue.sort(compareX);
  57025. // process holes from left to right
  57026. for (i = 0; i < queue.length; i++) {
  57027. eliminateHole(queue[i], outerNode);
  57028. outerNode = filterPoints(outerNode, outerNode.next);
  57029. }
  57030. return outerNode;
  57031. }
  57032. function compareX(a, b) {
  57033. return a.x - b.x;
  57034. }
  57035. // find a bridge between vertices that connects hole with an outer ring and and link it
  57036. function eliminateHole(hole, outerNode) {
  57037. outerNode = findHoleBridge(hole, outerNode);
  57038. if (outerNode) {
  57039. var b = splitPolygon(outerNode, hole);
  57040. filterPoints(b, b.next);
  57041. }
  57042. }
  57043. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  57044. function findHoleBridge(hole, outerNode) {
  57045. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  57046. // find a segment intersected by a ray from the hole's leftmost point to the left;
  57047. // segment's endpoint with lesser x will be potential connection point
  57048. do {
  57049. if (hy <= p.y && hy >= p.next.y) {
  57050. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  57051. if (x <= hx && x > qx) {
  57052. qx = x;
  57053. if (x === hx) {
  57054. if (hy === p.y)
  57055. return p;
  57056. if (hy === p.next.y)
  57057. return p.next;
  57058. }
  57059. m = p.x < p.next.x ? p : p.next;
  57060. }
  57061. }
  57062. p = p.next;
  57063. } while (p !== outerNode);
  57064. if (!m)
  57065. return null;
  57066. if (hx === qx)
  57067. return m.prev; // hole touches outer segment; pick lower endpoint
  57068. // look for points inside the triangle of hole point, segment intersection and endpoint;
  57069. // if there are no points found, we have a valid connection;
  57070. // otherwise choose the point of the minimum angle with the ray as connection point
  57071. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  57072. p = m.next;
  57073. while (p !== stop) {
  57074. if (hx >= p.x &&
  57075. p.x >= mx &&
  57076. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  57077. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  57078. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  57079. m = p;
  57080. tanMin = tan;
  57081. }
  57082. }
  57083. p = p.next;
  57084. }
  57085. return m;
  57086. }
  57087. // interlink polygon nodes in z-order
  57088. function indexCurve(start, minX, minY, size) {
  57089. var p = start;
  57090. do {
  57091. if (p.z === null)
  57092. p.z = zOrder(p.x, p.y, minX, minY, size);
  57093. p.prevZ = p.prev;
  57094. p.nextZ = p.next;
  57095. p = p.next;
  57096. } while (p !== start);
  57097. p.prevZ.nextZ = null;
  57098. p.prevZ = null;
  57099. sortLinked(p);
  57100. }
  57101. // Simon Tatham's linked list merge sort algorithm
  57102. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  57103. function sortLinked(list) {
  57104. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  57105. do {
  57106. p = list;
  57107. list = null;
  57108. tail = null;
  57109. numMerges = 0;
  57110. while (p) {
  57111. numMerges++;
  57112. q = p;
  57113. pSize = 0;
  57114. for (i = 0; i < inSize; i++) {
  57115. pSize++;
  57116. q = q.nextZ;
  57117. if (!q)
  57118. break;
  57119. }
  57120. qSize = inSize;
  57121. while (pSize > 0 || (qSize > 0 && q)) {
  57122. if (pSize === 0) {
  57123. e = q;
  57124. q = q.nextZ;
  57125. qSize--;
  57126. }
  57127. else if (qSize === 0 || !q) {
  57128. e = p;
  57129. p = p.nextZ;
  57130. pSize--;
  57131. }
  57132. else if (p.z <= q.z) {
  57133. e = p;
  57134. p = p.nextZ;
  57135. pSize--;
  57136. }
  57137. else {
  57138. e = q;
  57139. q = q.nextZ;
  57140. qSize--;
  57141. }
  57142. if (tail)
  57143. tail.nextZ = e;
  57144. else
  57145. list = e;
  57146. e.prevZ = tail;
  57147. tail = e;
  57148. }
  57149. p = q;
  57150. }
  57151. tail.nextZ = null;
  57152. inSize *= 2;
  57153. } while (numMerges > 1);
  57154. return list;
  57155. }
  57156. // z-order of a point given coords and size of the data bounding box
  57157. function zOrder(x, y, minX, minY, size) {
  57158. // coords are transformed into non-negative 15-bit integer range
  57159. x = 32767 * (x - minX) / size;
  57160. y = 32767 * (y - minY) / size;
  57161. x = (x | (x << 8)) & 0x00FF00FF;
  57162. x = (x | (x << 4)) & 0x0F0F0F0F;
  57163. x = (x | (x << 2)) & 0x33333333;
  57164. x = (x | (x << 1)) & 0x55555555;
  57165. y = (y | (y << 8)) & 0x00FF00FF;
  57166. y = (y | (y << 4)) & 0x0F0F0F0F;
  57167. y = (y | (y << 2)) & 0x33333333;
  57168. y = (y | (y << 1)) & 0x55555555;
  57169. return x | (y << 1);
  57170. }
  57171. // find the leftmost node of a polygon ring
  57172. function getLeftmost(start) {
  57173. var p = start, leftmost = start;
  57174. do {
  57175. if (p.x < leftmost.x)
  57176. leftmost = p;
  57177. p = p.next;
  57178. } while (p !== start);
  57179. return leftmost;
  57180. }
  57181. // check if a point lies within a convex triangle
  57182. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  57183. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  57184. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  57185. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  57186. }
  57187. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  57188. function isValidDiagonal(a, b) {
  57189. return a.next.i !== b.i &&
  57190. a.prev.i !== b.i &&
  57191. !intersectsPolygon(a, b) &&
  57192. locallyInside(a, b) &&
  57193. locallyInside(b, a) &&
  57194. middleInside(a, b);
  57195. }
  57196. // signed area of a triangle
  57197. function area(p, q, r) {
  57198. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  57199. }
  57200. // check if two points are equal
  57201. function equals(p1, p2) {
  57202. return p1.x === p2.x && p1.y === p2.y;
  57203. }
  57204. // check if two segments intersect
  57205. function intersects(p1, q1, p2, q2) {
  57206. if ((equals(p1, q1) && equals(p2, q2)) ||
  57207. (equals(p1, q2) && equals(p2, q1)))
  57208. return true;
  57209. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  57210. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  57211. }
  57212. // check if a polygon diagonal intersects any polygon segments
  57213. function intersectsPolygon(a, b) {
  57214. var p = a;
  57215. do {
  57216. if (p.i !== a.i &&
  57217. p.next.i !== a.i &&
  57218. p.i !== b.i &&
  57219. p.next.i !== b.i &&
  57220. intersects(p, p.next, a, b))
  57221. return true;
  57222. p = p.next;
  57223. } while (p !== a);
  57224. return false;
  57225. }
  57226. // check if a polygon diagonal is locally inside the polygon
  57227. function locallyInside(a, b) {
  57228. return area(a.prev, a, a.next) < 0
  57229. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  57230. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  57231. }
  57232. // check if the middle point of a polygon diagonal is inside the polygon
  57233. function middleInside(a, b) {
  57234. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  57235. do {
  57236. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  57237. inside = !inside;
  57238. p = p.next;
  57239. } while (p !== a);
  57240. return inside;
  57241. }
  57242. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  57243. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  57244. function splitPolygon(a, b) {
  57245. 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;
  57246. a.next = b;
  57247. b.prev = a;
  57248. a2.next = an;
  57249. an.prev = a2;
  57250. b2.next = a2;
  57251. a2.prev = b2;
  57252. bp.next = b2;
  57253. b2.prev = bp;
  57254. return b2;
  57255. }
  57256. // create a node and optionally link it with previous one (in a circular doubly linked list)
  57257. function insertNode(i, x, y, last) {
  57258. var p = new Node(i, x, y);
  57259. if (!last) {
  57260. p.prev = p;
  57261. p.next = p;
  57262. }
  57263. else {
  57264. p.next = last.next;
  57265. p.prev = last;
  57266. last.next.prev = p;
  57267. last.next = p;
  57268. }
  57269. return p;
  57270. }
  57271. function removeNode(p) {
  57272. p.next.prev = p.prev;
  57273. p.prev.next = p.next;
  57274. if (p.prevZ)
  57275. p.prevZ.nextZ = p.nextZ;
  57276. if (p.nextZ)
  57277. p.nextZ.prevZ = p.prevZ;
  57278. }
  57279. function Node(i, x, y) {
  57280. // vertice index in coordinates array
  57281. this.i = i;
  57282. // vertex coordinates
  57283. this.x = x;
  57284. this.y = y;
  57285. // previous and next vertice nodes in a polygon ring
  57286. this.prev = null;
  57287. this.next = null;
  57288. // z-order curve value
  57289. this.z = null;
  57290. // previous and next nodes in z-order
  57291. this.prevZ = null;
  57292. this.nextZ = null;
  57293. // indicates whether this is a steiner point
  57294. this.steiner = false;
  57295. }
  57296. /**
  57297. * return a percentage difference between the polygon area and its triangulation area;
  57298. * used to verify correctness of triangulation
  57299. */
  57300. function deviation(data, holeIndices, dim, triangles) {
  57301. var hasHoles = holeIndices && holeIndices.length;
  57302. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  57303. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  57304. if (hasHoles) {
  57305. for (var i = 0, len = holeIndices.length; i < len; i++) {
  57306. var start = holeIndices[i] * dim;
  57307. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57308. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  57309. }
  57310. }
  57311. var trianglesArea = 0;
  57312. for (i = 0; i < triangles.length; i += 3) {
  57313. var a = triangles[i] * dim;
  57314. var b = triangles[i + 1] * dim;
  57315. var c = triangles[i + 2] * dim;
  57316. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  57317. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  57318. }
  57319. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  57320. }
  57321. Earcut.deviation = deviation;
  57322. ;
  57323. function signedArea(data, start, end, dim) {
  57324. var sum = 0;
  57325. for (var i = start, j = end - dim; i < end; i += dim) {
  57326. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  57327. j = i;
  57328. }
  57329. return sum;
  57330. }
  57331. /**
  57332. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  57333. */
  57334. function flatten(data) {
  57335. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  57336. for (var i = 0; i < data.length; i++) {
  57337. for (var j = 0; j < data[i].length; j++) {
  57338. for (var d = 0; d < dim; d++)
  57339. result.vertices.push(data[i][j][d]);
  57340. }
  57341. if (i > 0) {
  57342. holeIndex += data[i - 1].length;
  57343. result.holes.push(holeIndex);
  57344. }
  57345. }
  57346. return result;
  57347. }
  57348. Earcut.flatten = flatten;
  57349. ;
  57350. })(Earcut || (Earcut = {}));
  57351. //# sourceMappingURL=babylon.earcut.js.map
  57352. /// <reference path="..\Math\babylon.math.ts" />
  57353. var BABYLON;
  57354. (function (BABYLON) {
  57355. var IndexedVector2 = (function (_super) {
  57356. __extends(IndexedVector2, _super);
  57357. function IndexedVector2(original, index) {
  57358. var _this = _super.call(this, original.x, original.y) || this;
  57359. _this.index = index;
  57360. return _this;
  57361. }
  57362. return IndexedVector2;
  57363. }(BABYLON.Vector2));
  57364. var PolygonPoints = (function () {
  57365. function PolygonPoints() {
  57366. this.elements = new Array();
  57367. }
  57368. PolygonPoints.prototype.add = function (originalPoints) {
  57369. var _this = this;
  57370. var result = new Array();
  57371. originalPoints.forEach(function (point) {
  57372. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  57373. var newPoint = new IndexedVector2(point, _this.elements.length);
  57374. result.push(newPoint);
  57375. _this.elements.push(newPoint);
  57376. }
  57377. });
  57378. return result;
  57379. };
  57380. PolygonPoints.prototype.computeBounds = function () {
  57381. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  57382. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  57383. this.elements.forEach(function (point) {
  57384. // x
  57385. if (point.x < lmin.x) {
  57386. lmin.x = point.x;
  57387. }
  57388. else if (point.x > lmax.x) {
  57389. lmax.x = point.x;
  57390. }
  57391. // y
  57392. if (point.y < lmin.y) {
  57393. lmin.y = point.y;
  57394. }
  57395. else if (point.y > lmax.y) {
  57396. lmax.y = point.y;
  57397. }
  57398. });
  57399. return {
  57400. min: lmin,
  57401. max: lmax,
  57402. width: lmax.x - lmin.x,
  57403. height: lmax.y - lmin.y
  57404. };
  57405. };
  57406. return PolygonPoints;
  57407. }());
  57408. var Polygon = (function () {
  57409. function Polygon() {
  57410. }
  57411. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  57412. return [
  57413. new BABYLON.Vector2(xmin, ymin),
  57414. new BABYLON.Vector2(xmax, ymin),
  57415. new BABYLON.Vector2(xmax, ymax),
  57416. new BABYLON.Vector2(xmin, ymax)
  57417. ];
  57418. };
  57419. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  57420. if (cx === void 0) { cx = 0; }
  57421. if (cy === void 0) { cy = 0; }
  57422. if (numberOfSides === void 0) { numberOfSides = 32; }
  57423. var result = new Array();
  57424. var angle = 0;
  57425. var increment = (Math.PI * 2) / numberOfSides;
  57426. for (var i = 0; i < numberOfSides; i++) {
  57427. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  57428. angle -= increment;
  57429. }
  57430. return result;
  57431. };
  57432. Polygon.Parse = function (input) {
  57433. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  57434. var i, result = [];
  57435. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  57436. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  57437. }
  57438. return result;
  57439. };
  57440. Polygon.StartingAt = function (x, y) {
  57441. return BABYLON.Path2.StartingAt(x, y);
  57442. };
  57443. return Polygon;
  57444. }());
  57445. BABYLON.Polygon = Polygon;
  57446. var PolygonMeshBuilder = (function () {
  57447. function PolygonMeshBuilder(name, contours, scene) {
  57448. this._points = new PolygonPoints();
  57449. this._outlinepoints = new PolygonPoints();
  57450. this._holes = [];
  57451. this._epoints = new Array();
  57452. this._eholes = new Array();
  57453. this._name = name;
  57454. this._scene = scene;
  57455. var points;
  57456. if (contours instanceof BABYLON.Path2) {
  57457. points = contours.getPoints();
  57458. }
  57459. else {
  57460. points = contours;
  57461. }
  57462. this._addToepoint(points);
  57463. this._points.add(points);
  57464. this._outlinepoints.add(points);
  57465. }
  57466. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  57467. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  57468. var p = points_1[_i];
  57469. this._epoints.push(p.x, p.y);
  57470. }
  57471. };
  57472. PolygonMeshBuilder.prototype.addHole = function (hole) {
  57473. this._points.add(hole);
  57474. var holepoints = new PolygonPoints();
  57475. holepoints.add(hole);
  57476. this._holes.push(holepoints);
  57477. this._eholes.push(this._epoints.length / 2);
  57478. this._addToepoint(hole);
  57479. return this;
  57480. };
  57481. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  57482. var _this = this;
  57483. if (updatable === void 0) { updatable = false; }
  57484. var result = new BABYLON.Mesh(this._name, this._scene);
  57485. var normals = [];
  57486. var positions = [];
  57487. var uvs = [];
  57488. var bounds = this._points.computeBounds();
  57489. this._points.elements.forEach(function (p) {
  57490. normals.push(0, 1.0, 0);
  57491. positions.push(p.x, 0, p.y);
  57492. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  57493. });
  57494. var indices = [];
  57495. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  57496. for (var i = 0; i < res.length; i++) {
  57497. indices.push(res[i]);
  57498. }
  57499. if (depth > 0) {
  57500. var positionscount = (positions.length / 3); //get the current pointcount
  57501. this._points.elements.forEach(function (p) {
  57502. normals.push(0, -1.0, 0);
  57503. positions.push(p.x, -depth, p.y);
  57504. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  57505. });
  57506. var totalCount = indices.length;
  57507. for (var i = 0; i < totalCount; i += 3) {
  57508. var i0 = indices[i + 0];
  57509. var i1 = indices[i + 1];
  57510. var i2 = indices[i + 2];
  57511. indices.push(i2 + positionscount);
  57512. indices.push(i1 + positionscount);
  57513. indices.push(i0 + positionscount);
  57514. }
  57515. //Add the sides
  57516. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  57517. this._holes.forEach(function (hole) {
  57518. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  57519. });
  57520. }
  57521. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  57522. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  57523. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  57524. result.setIndices(indices);
  57525. return result;
  57526. };
  57527. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  57528. var StartIndex = positions.length / 3;
  57529. var ulength = 0;
  57530. for (var i = 0; i < points.elements.length; i++) {
  57531. var p = points.elements[i];
  57532. var p1;
  57533. if ((i + 1) > points.elements.length - 1) {
  57534. p1 = points.elements[0];
  57535. }
  57536. else {
  57537. p1 = points.elements[i + 1];
  57538. }
  57539. positions.push(p.x, 0, p.y);
  57540. positions.push(p.x, -depth, p.y);
  57541. positions.push(p1.x, 0, p1.y);
  57542. positions.push(p1.x, -depth, p1.y);
  57543. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  57544. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  57545. var v3 = v2.subtract(v1);
  57546. var v4 = new BABYLON.Vector3(0, 1, 0);
  57547. var vn = BABYLON.Vector3.Cross(v3, v4);
  57548. vn = vn.normalize();
  57549. uvs.push(ulength / bounds.width, 0);
  57550. uvs.push(ulength / bounds.width, 1);
  57551. ulength += v3.length();
  57552. uvs.push((ulength / bounds.width), 0);
  57553. uvs.push((ulength / bounds.width), 1);
  57554. if (!flip) {
  57555. normals.push(-vn.x, -vn.y, -vn.z);
  57556. normals.push(-vn.x, -vn.y, -vn.z);
  57557. normals.push(-vn.x, -vn.y, -vn.z);
  57558. normals.push(-vn.x, -vn.y, -vn.z);
  57559. indices.push(StartIndex);
  57560. indices.push(StartIndex + 1);
  57561. indices.push(StartIndex + 2);
  57562. indices.push(StartIndex + 1);
  57563. indices.push(StartIndex + 3);
  57564. indices.push(StartIndex + 2);
  57565. }
  57566. else {
  57567. normals.push(vn.x, vn.y, vn.z);
  57568. normals.push(vn.x, vn.y, vn.z);
  57569. normals.push(vn.x, vn.y, vn.z);
  57570. normals.push(vn.x, vn.y, vn.z);
  57571. indices.push(StartIndex);
  57572. indices.push(StartIndex + 2);
  57573. indices.push(StartIndex + 1);
  57574. indices.push(StartIndex + 1);
  57575. indices.push(StartIndex + 2);
  57576. indices.push(StartIndex + 3);
  57577. }
  57578. StartIndex += 4;
  57579. }
  57580. ;
  57581. };
  57582. return PolygonMeshBuilder;
  57583. }());
  57584. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  57585. })(BABYLON || (BABYLON = {}));
  57586. //# sourceMappingURL=babylon.polygonMesh.js.map
  57587. var BABYLON;
  57588. (function (BABYLON) {
  57589. // Unique ID when we import meshes from Babylon to CSG
  57590. var currentCSGMeshId = 0;
  57591. // # class Vertex
  57592. // Represents a vertex of a polygon. Use your own vertex class instead of this
  57593. // one to provide additional features like texture coordinates and vertex
  57594. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  57595. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  57596. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  57597. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  57598. // is not used anywhere else.
  57599. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  57600. var Vertex = (function () {
  57601. function Vertex(pos, normal, uv) {
  57602. this.pos = pos;
  57603. this.normal = normal;
  57604. this.uv = uv;
  57605. }
  57606. Vertex.prototype.clone = function () {
  57607. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  57608. };
  57609. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  57610. // orientation of a polygon is flipped.
  57611. Vertex.prototype.flip = function () {
  57612. this.normal = this.normal.scale(-1);
  57613. };
  57614. // Create a new vertex between this vertex and `other` by linearly
  57615. // interpolating all properties using a parameter of `t`. Subclasses should
  57616. // override this to interpolate additional properties.
  57617. Vertex.prototype.interpolate = function (other, t) {
  57618. 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));
  57619. };
  57620. return Vertex;
  57621. }());
  57622. // # class Plane
  57623. // Represents a plane in 3D space.
  57624. var Plane = (function () {
  57625. function Plane(normal, w) {
  57626. this.normal = normal;
  57627. this.w = w;
  57628. }
  57629. Plane.FromPoints = function (a, b, c) {
  57630. var v0 = c.subtract(a);
  57631. var v1 = b.subtract(a);
  57632. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  57633. return null;
  57634. }
  57635. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  57636. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  57637. };
  57638. Plane.prototype.clone = function () {
  57639. return new Plane(this.normal.clone(), this.w);
  57640. };
  57641. Plane.prototype.flip = function () {
  57642. this.normal.scaleInPlace(-1);
  57643. this.w = -this.w;
  57644. };
  57645. // Split `polygon` by this plane if needed, then put the polygon or polygon
  57646. // fragments in the appropriate lists. Coplanar polygons go into either
  57647. // `coplanarFront` or `coplanarBack` depending on their orientation with
  57648. // respect to this plane. Polygons in front or in back of this plane go into
  57649. // either `front` or `back`.
  57650. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  57651. var COPLANAR = 0;
  57652. var FRONT = 1;
  57653. var BACK = 2;
  57654. var SPANNING = 3;
  57655. // Classify each point as well as the entire polygon into one of the above
  57656. // four classes.
  57657. var polygonType = 0;
  57658. var types = [];
  57659. var i;
  57660. var t;
  57661. for (i = 0; i < polygon.vertices.length; i++) {
  57662. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  57663. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  57664. polygonType |= type;
  57665. types.push(type);
  57666. }
  57667. // Put the polygon in the correct list, splitting it when necessary.
  57668. switch (polygonType) {
  57669. case COPLANAR:
  57670. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  57671. break;
  57672. case FRONT:
  57673. front.push(polygon);
  57674. break;
  57675. case BACK:
  57676. back.push(polygon);
  57677. break;
  57678. case SPANNING:
  57679. var f = [], b = [];
  57680. for (i = 0; i < polygon.vertices.length; i++) {
  57681. var j = (i + 1) % polygon.vertices.length;
  57682. var ti = types[i], tj = types[j];
  57683. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  57684. if (ti !== BACK)
  57685. f.push(vi);
  57686. if (ti !== FRONT)
  57687. b.push(ti !== BACK ? vi.clone() : vi);
  57688. if ((ti | tj) === SPANNING) {
  57689. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  57690. var v = vi.interpolate(vj, t);
  57691. f.push(v);
  57692. b.push(v.clone());
  57693. }
  57694. }
  57695. var poly;
  57696. if (f.length >= 3) {
  57697. poly = new Polygon(f, polygon.shared);
  57698. if (poly.plane)
  57699. front.push(poly);
  57700. }
  57701. if (b.length >= 3) {
  57702. poly = new Polygon(b, polygon.shared);
  57703. if (poly.plane)
  57704. back.push(poly);
  57705. }
  57706. break;
  57707. }
  57708. };
  57709. return Plane;
  57710. }());
  57711. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  57712. // point is on the plane.
  57713. Plane.EPSILON = 1e-5;
  57714. // # class Polygon
  57715. // Represents a convex polygon. The vertices used to initialize a polygon must
  57716. // be coplanar and form a convex loop.
  57717. //
  57718. // Each convex polygon has a `shared` property, which is shared between all
  57719. // polygons that are clones of each other or were split from the same polygon.
  57720. // This can be used to define per-polygon properties (such as surface color).
  57721. var Polygon = (function () {
  57722. function Polygon(vertices, shared) {
  57723. this.vertices = vertices;
  57724. this.shared = shared;
  57725. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  57726. }
  57727. Polygon.prototype.clone = function () {
  57728. var vertices = this.vertices.map(function (v) { return v.clone(); });
  57729. return new Polygon(vertices, this.shared);
  57730. };
  57731. Polygon.prototype.flip = function () {
  57732. this.vertices.reverse().map(function (v) { v.flip(); });
  57733. this.plane.flip();
  57734. };
  57735. return Polygon;
  57736. }());
  57737. // # class Node
  57738. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  57739. // by picking a polygon to split along. That polygon (and all other coplanar
  57740. // polygons) are added directly to that node and the other polygons are added to
  57741. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  57742. // no distinction between internal and leaf nodes.
  57743. var Node = (function () {
  57744. function Node(polygons) {
  57745. this.plane = null;
  57746. this.front = null;
  57747. this.back = null;
  57748. this.polygons = [];
  57749. if (polygons) {
  57750. this.build(polygons);
  57751. }
  57752. }
  57753. Node.prototype.clone = function () {
  57754. var node = new Node();
  57755. node.plane = this.plane && this.plane.clone();
  57756. node.front = this.front && this.front.clone();
  57757. node.back = this.back && this.back.clone();
  57758. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  57759. return node;
  57760. };
  57761. // Convert solid space to empty space and empty space to solid space.
  57762. Node.prototype.invert = function () {
  57763. for (var i = 0; i < this.polygons.length; i++) {
  57764. this.polygons[i].flip();
  57765. }
  57766. if (this.plane) {
  57767. this.plane.flip();
  57768. }
  57769. if (this.front) {
  57770. this.front.invert();
  57771. }
  57772. if (this.back) {
  57773. this.back.invert();
  57774. }
  57775. var temp = this.front;
  57776. this.front = this.back;
  57777. this.back = temp;
  57778. };
  57779. // Recursively remove all polygons in `polygons` that are inside this BSP
  57780. // tree.
  57781. Node.prototype.clipPolygons = function (polygons) {
  57782. if (!this.plane)
  57783. return polygons.slice();
  57784. var front = [], back = [];
  57785. for (var i = 0; i < polygons.length; i++) {
  57786. this.plane.splitPolygon(polygons[i], front, back, front, back);
  57787. }
  57788. if (this.front) {
  57789. front = this.front.clipPolygons(front);
  57790. }
  57791. if (this.back) {
  57792. back = this.back.clipPolygons(back);
  57793. }
  57794. else {
  57795. back = [];
  57796. }
  57797. return front.concat(back);
  57798. };
  57799. // Remove all polygons in this BSP tree that are inside the other BSP tree
  57800. // `bsp`.
  57801. Node.prototype.clipTo = function (bsp) {
  57802. this.polygons = bsp.clipPolygons(this.polygons);
  57803. if (this.front)
  57804. this.front.clipTo(bsp);
  57805. if (this.back)
  57806. this.back.clipTo(bsp);
  57807. };
  57808. // Return a list of all polygons in this BSP tree.
  57809. Node.prototype.allPolygons = function () {
  57810. var polygons = this.polygons.slice();
  57811. if (this.front)
  57812. polygons = polygons.concat(this.front.allPolygons());
  57813. if (this.back)
  57814. polygons = polygons.concat(this.back.allPolygons());
  57815. return polygons;
  57816. };
  57817. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  57818. // new polygons are filtered down to the bottom of the tree and become new
  57819. // nodes there. Each set of polygons is partitioned using the first polygon
  57820. // (no heuristic is used to pick a good split).
  57821. Node.prototype.build = function (polygons) {
  57822. if (!polygons.length)
  57823. return;
  57824. if (!this.plane)
  57825. this.plane = polygons[0].plane.clone();
  57826. var front = [], back = [];
  57827. for (var i = 0; i < polygons.length; i++) {
  57828. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  57829. }
  57830. if (front.length) {
  57831. if (!this.front)
  57832. this.front = new Node();
  57833. this.front.build(front);
  57834. }
  57835. if (back.length) {
  57836. if (!this.back)
  57837. this.back = new Node();
  57838. this.back.build(back);
  57839. }
  57840. };
  57841. return Node;
  57842. }());
  57843. var CSG = (function () {
  57844. function CSG() {
  57845. this.polygons = new Array();
  57846. }
  57847. // Convert BABYLON.Mesh to BABYLON.CSG
  57848. CSG.FromMesh = function (mesh) {
  57849. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  57850. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  57851. if (mesh instanceof BABYLON.Mesh) {
  57852. mesh.computeWorldMatrix(true);
  57853. matrix = mesh.getWorldMatrix();
  57854. meshPosition = mesh.position.clone();
  57855. meshRotation = mesh.rotation.clone();
  57856. if (mesh.rotationQuaternion) {
  57857. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  57858. }
  57859. meshScaling = mesh.scaling.clone();
  57860. }
  57861. else {
  57862. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  57863. }
  57864. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57865. var subMeshes = mesh.subMeshes;
  57866. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  57867. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  57868. vertices = [];
  57869. for (var j = 0; j < 3; j++) {
  57870. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  57871. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  57872. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  57873. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  57874. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  57875. vertex = new Vertex(position, normal, uv);
  57876. vertices.push(vertex);
  57877. }
  57878. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  57879. // To handle the case of degenerated triangle
  57880. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  57881. if (polygon.plane)
  57882. polygons.push(polygon);
  57883. }
  57884. }
  57885. var csg = CSG.FromPolygons(polygons);
  57886. csg.matrix = matrix;
  57887. csg.position = meshPosition;
  57888. csg.rotation = meshRotation;
  57889. csg.scaling = meshScaling;
  57890. csg.rotationQuaternion = meshRotationQuaternion;
  57891. currentCSGMeshId++;
  57892. return csg;
  57893. };
  57894. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  57895. CSG.FromPolygons = function (polygons) {
  57896. var csg = new CSG();
  57897. csg.polygons = polygons;
  57898. return csg;
  57899. };
  57900. CSG.prototype.clone = function () {
  57901. var csg = new CSG();
  57902. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  57903. csg.copyTransformAttributes(this);
  57904. return csg;
  57905. };
  57906. CSG.prototype.toPolygons = function () {
  57907. return this.polygons;
  57908. };
  57909. CSG.prototype.union = function (csg) {
  57910. var a = new Node(this.clone().polygons);
  57911. var b = new Node(csg.clone().polygons);
  57912. a.clipTo(b);
  57913. b.clipTo(a);
  57914. b.invert();
  57915. b.clipTo(a);
  57916. b.invert();
  57917. a.build(b.allPolygons());
  57918. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57919. };
  57920. CSG.prototype.unionInPlace = function (csg) {
  57921. var a = new Node(this.polygons);
  57922. var b = new Node(csg.polygons);
  57923. a.clipTo(b);
  57924. b.clipTo(a);
  57925. b.invert();
  57926. b.clipTo(a);
  57927. b.invert();
  57928. a.build(b.allPolygons());
  57929. this.polygons = a.allPolygons();
  57930. };
  57931. CSG.prototype.subtract = function (csg) {
  57932. var a = new Node(this.clone().polygons);
  57933. var b = new Node(csg.clone().polygons);
  57934. a.invert();
  57935. a.clipTo(b);
  57936. b.clipTo(a);
  57937. b.invert();
  57938. b.clipTo(a);
  57939. b.invert();
  57940. a.build(b.allPolygons());
  57941. a.invert();
  57942. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57943. };
  57944. CSG.prototype.subtractInPlace = function (csg) {
  57945. var a = new Node(this.polygons);
  57946. var b = new Node(csg.polygons);
  57947. a.invert();
  57948. a.clipTo(b);
  57949. b.clipTo(a);
  57950. b.invert();
  57951. b.clipTo(a);
  57952. b.invert();
  57953. a.build(b.allPolygons());
  57954. a.invert();
  57955. this.polygons = a.allPolygons();
  57956. };
  57957. CSG.prototype.intersect = function (csg) {
  57958. var a = new Node(this.clone().polygons);
  57959. var b = new Node(csg.clone().polygons);
  57960. a.invert();
  57961. b.clipTo(a);
  57962. b.invert();
  57963. a.clipTo(b);
  57964. b.clipTo(a);
  57965. a.build(b.allPolygons());
  57966. a.invert();
  57967. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57968. };
  57969. CSG.prototype.intersectInPlace = function (csg) {
  57970. var a = new Node(this.polygons);
  57971. var b = new Node(csg.polygons);
  57972. a.invert();
  57973. b.clipTo(a);
  57974. b.invert();
  57975. a.clipTo(b);
  57976. b.clipTo(a);
  57977. a.build(b.allPolygons());
  57978. a.invert();
  57979. this.polygons = a.allPolygons();
  57980. };
  57981. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  57982. // not modified.
  57983. CSG.prototype.inverse = function () {
  57984. var csg = this.clone();
  57985. csg.inverseInPlace();
  57986. return csg;
  57987. };
  57988. CSG.prototype.inverseInPlace = function () {
  57989. this.polygons.map(function (p) { p.flip(); });
  57990. };
  57991. // This is used to keep meshes transformations so they can be restored
  57992. // when we build back a Babylon Mesh
  57993. // NB : All CSG operations are performed in world coordinates
  57994. CSG.prototype.copyTransformAttributes = function (csg) {
  57995. this.matrix = csg.matrix;
  57996. this.position = csg.position;
  57997. this.rotation = csg.rotation;
  57998. this.scaling = csg.scaling;
  57999. this.rotationQuaternion = csg.rotationQuaternion;
  58000. return this;
  58001. };
  58002. // Build Raw mesh from CSG
  58003. // Coordinates here are in world space
  58004. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  58005. var matrix = this.matrix.clone();
  58006. matrix.invert();
  58007. 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;
  58008. if (keepSubMeshes) {
  58009. // Sort Polygons, since subMeshes are indices range
  58010. polygons.sort(function (a, b) {
  58011. if (a.shared.meshId === b.shared.meshId) {
  58012. return a.shared.subMeshId - b.shared.subMeshId;
  58013. }
  58014. else {
  58015. return a.shared.meshId - b.shared.meshId;
  58016. }
  58017. });
  58018. }
  58019. for (var i = 0, il = polygons.length; i < il; i++) {
  58020. polygon = polygons[i];
  58021. // Building SubMeshes
  58022. if (!subMesh_dict[polygon.shared.meshId]) {
  58023. subMesh_dict[polygon.shared.meshId] = {};
  58024. }
  58025. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  58026. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  58027. indexStart: +Infinity,
  58028. indexEnd: -Infinity,
  58029. materialIndex: polygon.shared.materialIndex
  58030. };
  58031. }
  58032. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  58033. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  58034. polygonIndices[0] = 0;
  58035. polygonIndices[1] = j - 1;
  58036. polygonIndices[2] = j;
  58037. for (var k = 0; k < 3; k++) {
  58038. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  58039. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  58040. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  58041. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  58042. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  58043. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  58044. // Check if 2 points can be merged
  58045. if (!(typeof vertex_idx !== 'undefined' &&
  58046. normals[vertex_idx * 3] === localNormal.x &&
  58047. normals[vertex_idx * 3 + 1] === localNormal.y &&
  58048. normals[vertex_idx * 3 + 2] === localNormal.z &&
  58049. uvs[vertex_idx * 2] === uv.x &&
  58050. uvs[vertex_idx * 2 + 1] === uv.y)) {
  58051. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  58052. uvs.push(uv.x, uv.y);
  58053. normals.push(normal.x, normal.y, normal.z);
  58054. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  58055. }
  58056. indices.push(vertex_idx);
  58057. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  58058. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  58059. currentIndex++;
  58060. }
  58061. }
  58062. }
  58063. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  58064. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  58065. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  58066. mesh.setIndices(indices);
  58067. if (keepSubMeshes) {
  58068. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  58069. var materialIndexOffset = 0, materialMaxIndex;
  58070. mesh.subMeshes = new Array();
  58071. for (var m in subMesh_dict) {
  58072. materialMaxIndex = -1;
  58073. for (var sm in subMesh_dict[m]) {
  58074. subMesh_obj = subMesh_dict[m][sm];
  58075. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  58076. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  58077. }
  58078. materialIndexOffset += ++materialMaxIndex;
  58079. }
  58080. }
  58081. return mesh;
  58082. };
  58083. // Build Mesh from CSG taking material and transforms into account
  58084. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  58085. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  58086. mesh.material = material;
  58087. mesh.position.copyFrom(this.position);
  58088. mesh.rotation.copyFrom(this.rotation);
  58089. if (this.rotationQuaternion) {
  58090. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  58091. }
  58092. mesh.scaling.copyFrom(this.scaling);
  58093. mesh.computeWorldMatrix(true);
  58094. return mesh;
  58095. };
  58096. return CSG;
  58097. }());
  58098. BABYLON.CSG = CSG;
  58099. })(BABYLON || (BABYLON = {}));
  58100. //# sourceMappingURL=babylon.csg.js.map
  58101. var BABYLON;
  58102. (function (BABYLON) {
  58103. var LensFlare = (function () {
  58104. function LensFlare(size, position, color, imgUrl, system) {
  58105. this.size = size;
  58106. this.position = position;
  58107. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  58108. this.dispose = function () {
  58109. if (this.texture) {
  58110. this.texture.dispose();
  58111. }
  58112. // Remove from scene
  58113. var index = this._system.lensFlares.indexOf(this);
  58114. this._system.lensFlares.splice(index, 1);
  58115. };
  58116. this.color = color || new BABYLON.Color3(1, 1, 1);
  58117. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  58118. this._system = system;
  58119. system.lensFlares.push(this);
  58120. }
  58121. return LensFlare;
  58122. }());
  58123. BABYLON.LensFlare = LensFlare;
  58124. })(BABYLON || (BABYLON = {}));
  58125. //# sourceMappingURL=babylon.lensFlare.js.map
  58126. var BABYLON;
  58127. (function (BABYLON) {
  58128. var LensFlareSystem = (function () {
  58129. function LensFlareSystem(name, emitter, scene) {
  58130. this.name = name;
  58131. this.lensFlares = new Array();
  58132. this.borderLimit = 300;
  58133. this.viewportBorder = 0;
  58134. this.layerMask = 0x0FFFFFFF;
  58135. this._vertexBuffers = {};
  58136. this._isEnabled = true;
  58137. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58138. this._emitter = emitter;
  58139. this.id = name;
  58140. scene.lensFlareSystems.push(this);
  58141. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  58142. var engine = scene.getEngine();
  58143. // VBO
  58144. var vertices = [];
  58145. vertices.push(1, 1);
  58146. vertices.push(-1, 1);
  58147. vertices.push(-1, -1);
  58148. vertices.push(1, -1);
  58149. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  58150. // Indices
  58151. var indices = [];
  58152. indices.push(0);
  58153. indices.push(1);
  58154. indices.push(2);
  58155. indices.push(0);
  58156. indices.push(2);
  58157. indices.push(3);
  58158. this._indexBuffer = engine.createIndexBuffer(indices);
  58159. // Effects
  58160. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  58161. }
  58162. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  58163. get: function () {
  58164. return this._isEnabled;
  58165. },
  58166. set: function (value) {
  58167. this._isEnabled = value;
  58168. },
  58169. enumerable: true,
  58170. configurable: true
  58171. });
  58172. LensFlareSystem.prototype.getScene = function () {
  58173. return this._scene;
  58174. };
  58175. LensFlareSystem.prototype.getEmitter = function () {
  58176. return this._emitter;
  58177. };
  58178. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  58179. this._emitter = newEmitter;
  58180. };
  58181. LensFlareSystem.prototype.getEmitterPosition = function () {
  58182. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  58183. };
  58184. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  58185. var position = this.getEmitterPosition();
  58186. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  58187. this._positionX = position.x;
  58188. this._positionY = position.y;
  58189. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  58190. if (this.viewportBorder > 0) {
  58191. globalViewport.x -= this.viewportBorder;
  58192. globalViewport.y -= this.viewportBorder;
  58193. globalViewport.width += this.viewportBorder * 2;
  58194. globalViewport.height += this.viewportBorder * 2;
  58195. position.x += this.viewportBorder;
  58196. position.y += this.viewportBorder;
  58197. this._positionX += this.viewportBorder;
  58198. this._positionY += this.viewportBorder;
  58199. }
  58200. if (position.z > 0) {
  58201. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  58202. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  58203. return true;
  58204. }
  58205. return true;
  58206. }
  58207. return false;
  58208. };
  58209. LensFlareSystem.prototype._isVisible = function () {
  58210. if (!this._isEnabled) {
  58211. return false;
  58212. }
  58213. var emitterPosition = this.getEmitterPosition();
  58214. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  58215. var distance = direction.length();
  58216. direction.normalize();
  58217. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  58218. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  58219. return !pickInfo.hit || pickInfo.distance > distance;
  58220. };
  58221. LensFlareSystem.prototype.render = function () {
  58222. if (!this._effect.isReady())
  58223. return false;
  58224. var engine = this._scene.getEngine();
  58225. var viewport = this._scene.activeCamera.viewport;
  58226. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  58227. // Position
  58228. if (!this.computeEffectivePosition(globalViewport)) {
  58229. return false;
  58230. }
  58231. // Visibility
  58232. if (!this._isVisible()) {
  58233. return false;
  58234. }
  58235. // Intensity
  58236. var awayX;
  58237. var awayY;
  58238. if (this._positionX < this.borderLimit + globalViewport.x) {
  58239. awayX = this.borderLimit + globalViewport.x - this._positionX;
  58240. }
  58241. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  58242. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  58243. }
  58244. else {
  58245. awayX = 0;
  58246. }
  58247. if (this._positionY < this.borderLimit + globalViewport.y) {
  58248. awayY = this.borderLimit + globalViewport.y - this._positionY;
  58249. }
  58250. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  58251. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  58252. }
  58253. else {
  58254. awayY = 0;
  58255. }
  58256. var away = (awayX > awayY) ? awayX : awayY;
  58257. away -= this.viewportBorder;
  58258. if (away > this.borderLimit) {
  58259. away = this.borderLimit;
  58260. }
  58261. var intensity = 1.0 - (away / this.borderLimit);
  58262. if (intensity < 0) {
  58263. return false;
  58264. }
  58265. if (intensity > 1.0) {
  58266. intensity = 1.0;
  58267. }
  58268. if (this.viewportBorder > 0) {
  58269. globalViewport.x += this.viewportBorder;
  58270. globalViewport.y += this.viewportBorder;
  58271. globalViewport.width -= this.viewportBorder * 2;
  58272. globalViewport.height -= this.viewportBorder * 2;
  58273. this._positionX -= this.viewportBorder;
  58274. this._positionY -= this.viewportBorder;
  58275. }
  58276. // Position
  58277. var centerX = globalViewport.x + globalViewport.width / 2;
  58278. var centerY = globalViewport.y + globalViewport.height / 2;
  58279. var distX = centerX - this._positionX;
  58280. var distY = centerY - this._positionY;
  58281. // Effects
  58282. engine.enableEffect(this._effect);
  58283. engine.setState(false);
  58284. engine.setDepthBuffer(false);
  58285. // VBOs
  58286. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58287. // Flares
  58288. for (var index = 0; index < this.lensFlares.length; index++) {
  58289. var flare = this.lensFlares[index];
  58290. engine.setAlphaMode(flare.alphaMode);
  58291. var x = centerX - (distX * flare.position);
  58292. var y = centerY - (distY * flare.position);
  58293. var cw = flare.size;
  58294. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  58295. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  58296. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  58297. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  58298. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  58299. // Texture
  58300. this._effect.setTexture("textureSampler", flare.texture);
  58301. // Color
  58302. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  58303. // Draw order
  58304. engine.draw(true, 0, 6);
  58305. }
  58306. engine.setDepthBuffer(true);
  58307. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58308. return true;
  58309. };
  58310. LensFlareSystem.prototype.dispose = function () {
  58311. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58312. if (vertexBuffer) {
  58313. vertexBuffer.dispose();
  58314. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  58315. }
  58316. if (this._indexBuffer) {
  58317. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58318. this._indexBuffer = null;
  58319. }
  58320. while (this.lensFlares.length) {
  58321. this.lensFlares[0].dispose();
  58322. }
  58323. // Remove from scene
  58324. var index = this._scene.lensFlareSystems.indexOf(this);
  58325. this._scene.lensFlareSystems.splice(index, 1);
  58326. };
  58327. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  58328. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  58329. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  58330. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  58331. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  58332. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  58333. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  58334. var parsedFlare = parsedLensFlareSystem.flares[index];
  58335. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  58336. }
  58337. return lensFlareSystem;
  58338. };
  58339. LensFlareSystem.prototype.serialize = function () {
  58340. var serializationObject = {};
  58341. serializationObject.id = this.id;
  58342. serializationObject.name = this.name;
  58343. serializationObject.emitterId = this.getEmitter().id;
  58344. serializationObject.borderLimit = this.borderLimit;
  58345. serializationObject.flares = [];
  58346. for (var index = 0; index < this.lensFlares.length; index++) {
  58347. var flare = this.lensFlares[index];
  58348. serializationObject.flares.push({
  58349. size: flare.size,
  58350. position: flare.position,
  58351. color: flare.color.asArray(),
  58352. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  58353. });
  58354. }
  58355. return serializationObject;
  58356. };
  58357. return LensFlareSystem;
  58358. }());
  58359. BABYLON.LensFlareSystem = LensFlareSystem;
  58360. })(BABYLON || (BABYLON = {}));
  58361. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  58362. var BABYLON;
  58363. (function (BABYLON) {
  58364. /**
  58365. * This is a holder class for the physics joint created by the physics plugin.
  58366. * It holds a set of functions to control the underlying joint.
  58367. */
  58368. var PhysicsJoint = (function () {
  58369. function PhysicsJoint(type, jointData) {
  58370. this.type = type;
  58371. this.jointData = jointData;
  58372. jointData.nativeParams = jointData.nativeParams || {};
  58373. }
  58374. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  58375. get: function () {
  58376. return this._physicsJoint;
  58377. },
  58378. set: function (newJoint) {
  58379. if (this._physicsJoint) {
  58380. //remove from the wolrd
  58381. }
  58382. this._physicsJoint = newJoint;
  58383. },
  58384. enumerable: true,
  58385. configurable: true
  58386. });
  58387. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  58388. set: function (physicsPlugin) {
  58389. this._physicsPlugin = physicsPlugin;
  58390. },
  58391. enumerable: true,
  58392. configurable: true
  58393. });
  58394. /**
  58395. * Execute a function that is physics-plugin specific.
  58396. * @param {Function} func the function that will be executed.
  58397. * It accepts two parameters: the physics world and the physics joint.
  58398. */
  58399. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  58400. func(this._physicsPlugin.world, this._physicsJoint);
  58401. };
  58402. return PhysicsJoint;
  58403. }());
  58404. //TODO check if the native joints are the same
  58405. //Joint Types
  58406. PhysicsJoint.DistanceJoint = 0;
  58407. PhysicsJoint.HingeJoint = 1;
  58408. PhysicsJoint.BallAndSocketJoint = 2;
  58409. PhysicsJoint.WheelJoint = 3;
  58410. PhysicsJoint.SliderJoint = 4;
  58411. //OIMO
  58412. PhysicsJoint.PrismaticJoint = 5;
  58413. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  58414. PhysicsJoint.UniversalJoint = 6;
  58415. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  58416. //Cannon
  58417. //Similar to a Ball-Joint. Different in params
  58418. PhysicsJoint.PointToPointJoint = 8;
  58419. //Cannon only at the moment
  58420. PhysicsJoint.SpringJoint = 9;
  58421. PhysicsJoint.LockJoint = 10;
  58422. BABYLON.PhysicsJoint = PhysicsJoint;
  58423. /**
  58424. * A class representing a physics distance joint.
  58425. */
  58426. var DistanceJoint = (function (_super) {
  58427. __extends(DistanceJoint, _super);
  58428. function DistanceJoint(jointData) {
  58429. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  58430. }
  58431. /**
  58432. * Update the predefined distance.
  58433. */
  58434. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  58435. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  58436. };
  58437. return DistanceJoint;
  58438. }(PhysicsJoint));
  58439. BABYLON.DistanceJoint = DistanceJoint;
  58440. var MotorEnabledJoint = (function (_super) {
  58441. __extends(MotorEnabledJoint, _super);
  58442. function MotorEnabledJoint(type, jointData) {
  58443. return _super.call(this, type, jointData) || this;
  58444. }
  58445. /**
  58446. * Set the motor values.
  58447. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58448. * @param {number} force the force to apply
  58449. * @param {number} maxForce max force for this motor.
  58450. */
  58451. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  58452. this._physicsPlugin.setMotor(this, force, maxForce);
  58453. };
  58454. /**
  58455. * Set the motor's limits.
  58456. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58457. */
  58458. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  58459. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  58460. };
  58461. return MotorEnabledJoint;
  58462. }(PhysicsJoint));
  58463. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  58464. /**
  58465. * This class represents a single hinge physics joint
  58466. */
  58467. var HingeJoint = (function (_super) {
  58468. __extends(HingeJoint, _super);
  58469. function HingeJoint(jointData) {
  58470. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  58471. }
  58472. /**
  58473. * Set the motor values.
  58474. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58475. * @param {number} force the force to apply
  58476. * @param {number} maxForce max force for this motor.
  58477. */
  58478. HingeJoint.prototype.setMotor = function (force, maxForce) {
  58479. this._physicsPlugin.setMotor(this, force, maxForce);
  58480. };
  58481. /**
  58482. * Set the motor's limits.
  58483. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58484. */
  58485. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  58486. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  58487. };
  58488. return HingeJoint;
  58489. }(MotorEnabledJoint));
  58490. BABYLON.HingeJoint = HingeJoint;
  58491. /**
  58492. * This class represents a dual hinge physics joint (same as wheel joint)
  58493. */
  58494. var Hinge2Joint = (function (_super) {
  58495. __extends(Hinge2Joint, _super);
  58496. function Hinge2Joint(jointData) {
  58497. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  58498. }
  58499. /**
  58500. * Set the motor values.
  58501. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58502. * @param {number} force the force to apply
  58503. * @param {number} maxForce max force for this motor.
  58504. * @param {motorIndex} the motor's index, 0 or 1.
  58505. */
  58506. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  58507. if (motorIndex === void 0) { motorIndex = 0; }
  58508. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  58509. };
  58510. /**
  58511. * Set the motor limits.
  58512. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58513. * @param {number} upperLimit the upper limit
  58514. * @param {number} lowerLimit lower limit
  58515. * @param {motorIndex} the motor's index, 0 or 1.
  58516. */
  58517. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  58518. if (motorIndex === void 0) { motorIndex = 0; }
  58519. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  58520. };
  58521. return Hinge2Joint;
  58522. }(MotorEnabledJoint));
  58523. BABYLON.Hinge2Joint = Hinge2Joint;
  58524. })(BABYLON || (BABYLON = {}));
  58525. //# sourceMappingURL=babylon.physicsJoint.js.map
  58526. var BABYLON;
  58527. (function (BABYLON) {
  58528. var PhysicsImpostor = (function () {
  58529. function PhysicsImpostor(object, type, _options, _scene) {
  58530. if (_options === void 0) { _options = { mass: 0 }; }
  58531. var _this = this;
  58532. this.object = object;
  58533. this.type = type;
  58534. this._options = _options;
  58535. this._scene = _scene;
  58536. this._bodyUpdateRequired = false;
  58537. this._onBeforePhysicsStepCallbacks = new Array();
  58538. this._onAfterPhysicsStepCallbacks = new Array();
  58539. this._onPhysicsCollideCallbacks = [];
  58540. this._deltaPosition = BABYLON.Vector3.Zero();
  58541. this._isDisposed = false;
  58542. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  58543. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  58544. /**
  58545. * this function is executed by the physics engine.
  58546. */
  58547. this.beforeStep = function () {
  58548. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  58549. //conjugate deltaRotation
  58550. if (_this._deltaRotationConjugated) {
  58551. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  58552. }
  58553. else {
  58554. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  58555. }
  58556. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  58557. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  58558. func(_this);
  58559. });
  58560. };
  58561. /**
  58562. * this function is executed by the physics engine.
  58563. */
  58564. this.afterStep = function () {
  58565. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  58566. func(_this);
  58567. });
  58568. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  58569. _this.object.position.addInPlace(_this._deltaPosition);
  58570. if (_this._deltaRotation) {
  58571. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  58572. }
  58573. };
  58574. /**
  58575. * Legacy collision detection event support
  58576. */
  58577. this.onCollideEvent = null;
  58578. //event and body object due to cannon's event-based architecture.
  58579. this.onCollide = function (e) {
  58580. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  58581. return;
  58582. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  58583. if (otherImpostor) {
  58584. // Legacy collision detection event support
  58585. if (_this.onCollideEvent) {
  58586. _this.onCollideEvent(_this, otherImpostor);
  58587. }
  58588. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  58589. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  58590. }).forEach(function (obj) {
  58591. obj.callback(_this, otherImpostor);
  58592. });
  58593. }
  58594. };
  58595. //sanity check!
  58596. if (!this.object) {
  58597. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  58598. return;
  58599. }
  58600. //legacy support for old syntax.
  58601. if (!this._scene && object.getScene) {
  58602. this._scene = object.getScene();
  58603. }
  58604. this._physicsEngine = this._scene.getPhysicsEngine();
  58605. if (!this._physicsEngine) {
  58606. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  58607. }
  58608. else {
  58609. //set the object's quaternion, if not set
  58610. if (!this.object.rotationQuaternion) {
  58611. if (this.object.rotation) {
  58612. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  58613. }
  58614. else {
  58615. this.object.rotationQuaternion = new BABYLON.Quaternion();
  58616. }
  58617. }
  58618. //default options params
  58619. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  58620. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  58621. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  58622. this._joints = [];
  58623. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  58624. if (!this.object.parent) {
  58625. this._init();
  58626. }
  58627. else if (this.object.parent.physicsImpostor) {
  58628. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  58629. }
  58630. }
  58631. }
  58632. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  58633. get: function () {
  58634. return this._isDisposed;
  58635. },
  58636. enumerable: true,
  58637. configurable: true
  58638. });
  58639. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  58640. get: function () {
  58641. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  58642. },
  58643. set: function (value) {
  58644. this.setMass(value);
  58645. },
  58646. enumerable: true,
  58647. configurable: true
  58648. });
  58649. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  58650. get: function () {
  58651. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  58652. },
  58653. set: function (value) {
  58654. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  58655. },
  58656. enumerable: true,
  58657. configurable: true
  58658. });
  58659. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  58660. get: function () {
  58661. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  58662. },
  58663. set: function (value) {
  58664. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  58665. },
  58666. enumerable: true,
  58667. configurable: true
  58668. });
  58669. /**
  58670. * This function will completly initialize this impostor.
  58671. * It will create a new body - but only if this mesh has no parent.
  58672. * If it has, this impostor will not be used other than to define the impostor
  58673. * of the child mesh.
  58674. */
  58675. PhysicsImpostor.prototype._init = function () {
  58676. this._physicsEngine.removeImpostor(this);
  58677. this.physicsBody = null;
  58678. this._parent = this._parent || this._getPhysicsParent();
  58679. if (!this.parent) {
  58680. this._physicsEngine.addImpostor(this);
  58681. }
  58682. };
  58683. PhysicsImpostor.prototype._getPhysicsParent = function () {
  58684. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  58685. var parentMesh = this.object.parent;
  58686. return parentMesh.physicsImpostor;
  58687. }
  58688. return;
  58689. };
  58690. /**
  58691. * Should a new body be generated.
  58692. */
  58693. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  58694. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  58695. };
  58696. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  58697. this.forceUpdate();
  58698. };
  58699. /**
  58700. * Force a regeneration of this or the parent's impostor's body.
  58701. * Use under cautious - This will remove all joints already implemented.
  58702. */
  58703. PhysicsImpostor.prototype.forceUpdate = function () {
  58704. this._init();
  58705. if (this.parent) {
  58706. this.parent.forceUpdate();
  58707. }
  58708. };
  58709. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  58710. /*public get mesh(): AbstractMesh {
  58711. return this._mesh;
  58712. }*/
  58713. /**
  58714. * Gets the body that holds this impostor. Either its own, or its parent.
  58715. */
  58716. get: function () {
  58717. return this._parent ? this._parent.physicsBody : this._physicsBody;
  58718. },
  58719. /**
  58720. * Set the physics body. Used mainly by the physics engine/plugin
  58721. */
  58722. set: function (physicsBody) {
  58723. if (this._physicsBody) {
  58724. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  58725. }
  58726. this._physicsBody = physicsBody;
  58727. this.resetUpdateFlags();
  58728. },
  58729. enumerable: true,
  58730. configurable: true
  58731. });
  58732. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  58733. get: function () {
  58734. return this._parent;
  58735. },
  58736. set: function (value) {
  58737. this._parent = value;
  58738. },
  58739. enumerable: true,
  58740. configurable: true
  58741. });
  58742. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  58743. this._bodyUpdateRequired = false;
  58744. };
  58745. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  58746. if (this.object.getBoundingInfo) {
  58747. var q = this.object.rotationQuaternion;
  58748. //reset rotation
  58749. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  58750. //calculate the world matrix with no rotation
  58751. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  58752. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  58753. //bring back the rotation
  58754. this.object.rotationQuaternion = q;
  58755. //calculate the world matrix with the new rotation
  58756. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  58757. return size;
  58758. }
  58759. else {
  58760. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  58761. }
  58762. };
  58763. PhysicsImpostor.prototype.getObjectCenter = function () {
  58764. if (this.object.getBoundingInfo) {
  58765. return this.object.getBoundingInfo().boundingBox.centerWorld;
  58766. }
  58767. else {
  58768. return this.object.position;
  58769. }
  58770. };
  58771. /**
  58772. * Get a specific parametes from the options parameter.
  58773. */
  58774. PhysicsImpostor.prototype.getParam = function (paramName) {
  58775. return this._options[paramName];
  58776. };
  58777. /**
  58778. * Sets a specific parameter in the options given to the physics plugin
  58779. */
  58780. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  58781. this._options[paramName] = value;
  58782. this._bodyUpdateRequired = true;
  58783. };
  58784. /**
  58785. * Specifically change the body's mass option. Won't recreate the physics body object
  58786. */
  58787. PhysicsImpostor.prototype.setMass = function (mass) {
  58788. if (this.getParam("mass") !== mass) {
  58789. this.setParam("mass", mass);
  58790. }
  58791. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  58792. };
  58793. PhysicsImpostor.prototype.getLinearVelocity = function () {
  58794. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  58795. };
  58796. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  58797. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  58798. };
  58799. PhysicsImpostor.prototype.getAngularVelocity = function () {
  58800. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  58801. };
  58802. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  58803. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  58804. };
  58805. /**
  58806. * Execute a function with the physics plugin native code.
  58807. * Provide a function the will have two variables - the world object and the physics body object.
  58808. */
  58809. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  58810. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  58811. };
  58812. /**
  58813. * Register a function that will be executed before the physics world is stepping forward.
  58814. */
  58815. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  58816. this._onBeforePhysicsStepCallbacks.push(func);
  58817. };
  58818. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  58819. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  58820. if (index > -1) {
  58821. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  58822. }
  58823. else {
  58824. BABYLON.Tools.Warn("Function to remove was not found");
  58825. }
  58826. };
  58827. /**
  58828. * Register a function that will be executed after the physics step
  58829. */
  58830. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  58831. this._onAfterPhysicsStepCallbacks.push(func);
  58832. };
  58833. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  58834. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  58835. if (index > -1) {
  58836. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  58837. }
  58838. else {
  58839. BABYLON.Tools.Warn("Function to remove was not found");
  58840. }
  58841. };
  58842. /**
  58843. * register a function that will be executed when this impostor collides against a different body.
  58844. */
  58845. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  58846. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  58847. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  58848. };
  58849. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  58850. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  58851. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  58852. if (index > -1) {
  58853. this._onPhysicsCollideCallbacks.splice(index, 1);
  58854. }
  58855. else {
  58856. BABYLON.Tools.Warn("Function to remove was not found");
  58857. }
  58858. };
  58859. /**
  58860. * Apply a force
  58861. */
  58862. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  58863. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  58864. };
  58865. /**
  58866. * Apply an impulse
  58867. */
  58868. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  58869. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  58870. };
  58871. /**
  58872. * A help function to create a joint.
  58873. */
  58874. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  58875. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  58876. this.addJoint(otherImpostor, joint);
  58877. };
  58878. /**
  58879. * Add a joint to this impostor with a different impostor.
  58880. */
  58881. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  58882. this._joints.push({
  58883. otherImpostor: otherImpostor,
  58884. joint: joint
  58885. });
  58886. this._physicsEngine.addJoint(this, otherImpostor, joint);
  58887. };
  58888. /**
  58889. * Will keep this body still, in a sleep mode.
  58890. */
  58891. PhysicsImpostor.prototype.sleep = function () {
  58892. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  58893. };
  58894. /**
  58895. * Wake the body up.
  58896. */
  58897. PhysicsImpostor.prototype.wakeUp = function () {
  58898. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  58899. };
  58900. PhysicsImpostor.prototype.clone = function (newObject) {
  58901. if (!newObject)
  58902. return null;
  58903. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  58904. };
  58905. PhysicsImpostor.prototype.dispose = function () {
  58906. var _this = this;
  58907. //no dispose if no physics engine is available.
  58908. if (!this._physicsEngine) {
  58909. return;
  58910. }
  58911. this._joints.forEach(function (j) {
  58912. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  58913. });
  58914. //dispose the physics body
  58915. this._physicsEngine.removeImpostor(this);
  58916. if (this.parent) {
  58917. this.parent.forceUpdate();
  58918. }
  58919. else {
  58920. /*this._object.getChildMeshes().forEach(function(mesh) {
  58921. if (mesh.physicsImpostor) {
  58922. if (disposeChildren) {
  58923. mesh.physicsImpostor.dispose();
  58924. mesh.physicsImpostor = null;
  58925. }
  58926. }
  58927. })*/
  58928. }
  58929. this._isDisposed = true;
  58930. };
  58931. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  58932. this._deltaPosition.copyFrom(position);
  58933. };
  58934. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  58935. if (!this._deltaRotation) {
  58936. this._deltaRotation = new BABYLON.Quaternion();
  58937. }
  58938. this._deltaRotation.copyFrom(rotation);
  58939. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  58940. };
  58941. return PhysicsImpostor;
  58942. }());
  58943. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  58944. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  58945. //Impostor types
  58946. PhysicsImpostor.NoImpostor = 0;
  58947. PhysicsImpostor.SphereImpostor = 1;
  58948. PhysicsImpostor.BoxImpostor = 2;
  58949. PhysicsImpostor.PlaneImpostor = 3;
  58950. PhysicsImpostor.MeshImpostor = 4;
  58951. PhysicsImpostor.CylinderImpostor = 7;
  58952. PhysicsImpostor.ParticleImpostor = 8;
  58953. PhysicsImpostor.HeightmapImpostor = 9;
  58954. BABYLON.PhysicsImpostor = PhysicsImpostor;
  58955. })(BABYLON || (BABYLON = {}));
  58956. //# sourceMappingURL=babylon.physicsImpostor.js.map
  58957. var BABYLON;
  58958. (function (BABYLON) {
  58959. var PhysicsEngine = (function () {
  58960. function PhysicsEngine(gravity, _physicsPlugin) {
  58961. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  58962. this._physicsPlugin = _physicsPlugin;
  58963. //new methods and parameters
  58964. this._impostors = [];
  58965. this._joints = [];
  58966. if (!this._physicsPlugin.isSupported()) {
  58967. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  58968. + "Please make sure it is included.");
  58969. }
  58970. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  58971. this.setGravity(gravity);
  58972. this.setTimeStep();
  58973. }
  58974. PhysicsEngine.prototype.setGravity = function (gravity) {
  58975. this.gravity = gravity;
  58976. this._physicsPlugin.setGravity(this.gravity);
  58977. };
  58978. /**
  58979. * Set the time step of the physics engine.
  58980. * default is 1/60.
  58981. * To slow it down, enter 1/600 for example.
  58982. * To speed it up, 1/30
  58983. * @param {number} newTimeStep the new timestep to apply to this world.
  58984. */
  58985. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  58986. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  58987. this._physicsPlugin.setTimeStep(newTimeStep);
  58988. };
  58989. PhysicsEngine.prototype.dispose = function () {
  58990. this._impostors.forEach(function (impostor) {
  58991. impostor.dispose();
  58992. });
  58993. this._physicsPlugin.dispose();
  58994. };
  58995. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  58996. return this._physicsPlugin.name;
  58997. };
  58998. /**
  58999. * Adding a new impostor for the impostor tracking.
  59000. * This will be done by the impostor itself.
  59001. * @param {PhysicsImpostor} impostor the impostor to add
  59002. */
  59003. PhysicsEngine.prototype.addImpostor = function (impostor) {
  59004. impostor.uniqueId = this._impostors.push(impostor);
  59005. //if no parent, generate the body
  59006. if (!impostor.parent) {
  59007. this._physicsPlugin.generatePhysicsBody(impostor);
  59008. }
  59009. };
  59010. /**
  59011. * Remove an impostor from the engine.
  59012. * This impostor and its mesh will not longer be updated by the physics engine.
  59013. * @param {PhysicsImpostor} impostor the impostor to remove
  59014. */
  59015. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  59016. var index = this._impostors.indexOf(impostor);
  59017. if (index > -1) {
  59018. var removed = this._impostors.splice(index, 1);
  59019. //Is it needed?
  59020. if (removed.length) {
  59021. //this will also remove it from the world.
  59022. removed[0].physicsBody = null;
  59023. }
  59024. }
  59025. };
  59026. /**
  59027. * Add a joint to the physics engine
  59028. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  59029. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  59030. * @param {PhysicsJoint} the joint that will connect both impostors.
  59031. */
  59032. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  59033. var impostorJoint = {
  59034. mainImpostor: mainImpostor,
  59035. connectedImpostor: connectedImpostor,
  59036. joint: joint
  59037. };
  59038. joint.physicsPlugin = this._physicsPlugin;
  59039. this._joints.push(impostorJoint);
  59040. this._physicsPlugin.generateJoint(impostorJoint);
  59041. };
  59042. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  59043. var matchingJoints = this._joints.filter(function (impostorJoint) {
  59044. return (impostorJoint.connectedImpostor === connectedImpostor
  59045. && impostorJoint.joint === joint
  59046. && impostorJoint.mainImpostor === mainImpostor);
  59047. });
  59048. if (matchingJoints.length) {
  59049. this._physicsPlugin.removeJoint(matchingJoints[0]);
  59050. //TODO remove it from the list as well
  59051. }
  59052. };
  59053. /**
  59054. * Called by the scene. no need to call it.
  59055. */
  59056. PhysicsEngine.prototype._step = function (delta) {
  59057. var _this = this;
  59058. //check if any mesh has no body / requires an update
  59059. this._impostors.forEach(function (impostor) {
  59060. if (impostor.isBodyInitRequired()) {
  59061. _this._physicsPlugin.generatePhysicsBody(impostor);
  59062. }
  59063. });
  59064. if (delta > 0.1) {
  59065. delta = 0.1;
  59066. }
  59067. else if (delta <= 0) {
  59068. delta = 1.0 / 60.0;
  59069. }
  59070. this._physicsPlugin.executeStep(delta, this._impostors);
  59071. };
  59072. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  59073. return this._physicsPlugin;
  59074. };
  59075. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  59076. for (var i = 0; i < this._impostors.length; ++i) {
  59077. if (this._impostors[i].object === object) {
  59078. return this._impostors[i];
  59079. }
  59080. }
  59081. };
  59082. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  59083. for (var i = 0; i < this._impostors.length; ++i) {
  59084. if (this._impostors[i].physicsBody === body) {
  59085. return this._impostors[i];
  59086. }
  59087. }
  59088. };
  59089. return PhysicsEngine;
  59090. }());
  59091. // Statics
  59092. PhysicsEngine.Epsilon = 0.001;
  59093. BABYLON.PhysicsEngine = PhysicsEngine;
  59094. })(BABYLON || (BABYLON = {}));
  59095. //# sourceMappingURL=babylon.physicsEngine.js.map
  59096. var BABYLON;
  59097. (function (BABYLON) {
  59098. var CannonJSPlugin = (function () {
  59099. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  59100. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  59101. if (iterations === void 0) { iterations = 10; }
  59102. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  59103. this.name = "CannonJSPlugin";
  59104. this._physicsMaterials = [];
  59105. this._fixedTimeStep = 1 / 60;
  59106. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59107. this._currentCollisionGroup = 2;
  59108. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  59109. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  59110. this._tmpPosition = BABYLON.Vector3.Zero();
  59111. this._tmpQuaternion = new BABYLON.Quaternion();
  59112. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  59113. this._tmpDeltaRotation = new BABYLON.Quaternion();
  59114. this._tmpUnityRotation = new BABYLON.Quaternion();
  59115. if (!this.isSupported()) {
  59116. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  59117. return;
  59118. }
  59119. this.world = new CANNON.World();
  59120. this.world.broadphase = new CANNON.NaiveBroadphase();
  59121. this.world.solver.iterations = iterations;
  59122. }
  59123. CannonJSPlugin.prototype.setGravity = function (gravity) {
  59124. this.world.gravity.copy(gravity);
  59125. };
  59126. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  59127. this._fixedTimeStep = timeStep;
  59128. };
  59129. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  59130. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  59131. };
  59132. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  59133. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59134. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59135. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  59136. };
  59137. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  59138. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59139. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59140. impostor.physicsBody.applyForce(impulse, worldPoint);
  59141. };
  59142. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  59143. //parent-child relationship. Does this impostor has a parent impostor?
  59144. if (impostor.parent) {
  59145. if (impostor.physicsBody) {
  59146. this.removePhysicsBody(impostor);
  59147. //TODO is that needed?
  59148. impostor.forceUpdate();
  59149. }
  59150. return;
  59151. }
  59152. //should a new body be created for this impostor?
  59153. if (impostor.isBodyInitRequired()) {
  59154. var shape = this._createShape(impostor);
  59155. //unregister events, if body is being changed
  59156. var oldBody = impostor.physicsBody;
  59157. if (oldBody) {
  59158. this.removePhysicsBody(impostor);
  59159. }
  59160. //create the body and material
  59161. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  59162. var bodyCreationObject = {
  59163. mass: impostor.getParam("mass"),
  59164. material: material
  59165. };
  59166. // A simple extend, in case native options were used.
  59167. var nativeOptions = impostor.getParam("nativeOptions");
  59168. for (var key in nativeOptions) {
  59169. if (nativeOptions.hasOwnProperty(key)) {
  59170. bodyCreationObject[key] = nativeOptions[key];
  59171. }
  59172. }
  59173. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  59174. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  59175. this.world.addEventListener("preStep", impostor.beforeStep);
  59176. this.world.addEventListener("postStep", impostor.afterStep);
  59177. impostor.physicsBody.addShape(shape);
  59178. this.world.add(impostor.physicsBody);
  59179. //try to keep the body moving in the right direction by taking old properties.
  59180. //Should be tested!
  59181. if (oldBody) {
  59182. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  59183. impostor.physicsBody[param].copy(oldBody[param]);
  59184. });
  59185. }
  59186. this._processChildMeshes(impostor);
  59187. }
  59188. //now update the body's transformation
  59189. this._updatePhysicsBodyTransformation(impostor);
  59190. };
  59191. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  59192. var _this = this;
  59193. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  59194. if (meshChildren.length) {
  59195. var processMesh = function (localPosition, mesh) {
  59196. var childImpostor = mesh.getPhysicsImpostor();
  59197. if (childImpostor) {
  59198. var parent = childImpostor.parent;
  59199. if (parent !== mainImpostor) {
  59200. var localPosition = mesh.position;
  59201. if (childImpostor.physicsBody) {
  59202. _this.removePhysicsBody(childImpostor);
  59203. childImpostor.physicsBody = null;
  59204. }
  59205. childImpostor.parent = mainImpostor;
  59206. childImpostor.resetUpdateFlags();
  59207. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  59208. //Add the mass of the children.
  59209. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  59210. }
  59211. }
  59212. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  59213. };
  59214. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  59215. }
  59216. };
  59217. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  59218. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  59219. this.world.removeEventListener("preStep", impostor.beforeStep);
  59220. this.world.removeEventListener("postStep", impostor.afterStep);
  59221. this.world.remove(impostor.physicsBody);
  59222. };
  59223. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  59224. var mainBody = impostorJoint.mainImpostor.physicsBody;
  59225. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  59226. if (!mainBody || !connectedBody) {
  59227. return;
  59228. }
  59229. var constraint;
  59230. var jointData = impostorJoint.joint.jointData;
  59231. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59232. var constraintData = {
  59233. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  59234. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  59235. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  59236. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  59237. maxForce: jointData.nativeParams.maxForce,
  59238. collideConnected: !!jointData.collision
  59239. };
  59240. switch (impostorJoint.joint.type) {
  59241. case BABYLON.PhysicsJoint.HingeJoint:
  59242. case BABYLON.PhysicsJoint.Hinge2Joint:
  59243. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  59244. break;
  59245. case BABYLON.PhysicsJoint.DistanceJoint:
  59246. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  59247. break;
  59248. case BABYLON.PhysicsJoint.SpringJoint:
  59249. var springData = jointData;
  59250. constraint = new CANNON.Spring(mainBody, connectedBody, {
  59251. restLength: springData.length,
  59252. stiffness: springData.stiffness,
  59253. damping: springData.damping,
  59254. localAnchorA: constraintData.pivotA,
  59255. localAnchorB: constraintData.pivotB
  59256. });
  59257. break;
  59258. case BABYLON.PhysicsJoint.LockJoint:
  59259. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  59260. break;
  59261. case BABYLON.PhysicsJoint.PointToPointJoint:
  59262. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  59263. default:
  59264. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  59265. break;
  59266. }
  59267. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  59268. constraint.collideConnected = !!jointData.collision;
  59269. impostorJoint.joint.physicsJoint = constraint;
  59270. //don't add spring as constraint, as it is not one.
  59271. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  59272. this.world.addConstraint(constraint);
  59273. }
  59274. else {
  59275. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  59276. constraint.applyForce();
  59277. });
  59278. }
  59279. };
  59280. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  59281. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  59282. };
  59283. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  59284. var index;
  59285. var mat;
  59286. for (index = 0; index < this._physicsMaterials.length; index++) {
  59287. mat = this._physicsMaterials[index];
  59288. if (mat.friction === friction && mat.restitution === restitution) {
  59289. return mat;
  59290. }
  59291. }
  59292. var currentMat = new CANNON.Material(name);
  59293. currentMat.friction = friction;
  59294. currentMat.restitution = restitution;
  59295. this._physicsMaterials.push(currentMat);
  59296. return currentMat;
  59297. };
  59298. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  59299. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  59300. };
  59301. CannonJSPlugin.prototype._createShape = function (impostor) {
  59302. var object = impostor.object;
  59303. var returnValue;
  59304. var extendSize = impostor.getObjectExtendSize();
  59305. switch (impostor.type) {
  59306. case BABYLON.PhysicsImpostor.SphereImpostor:
  59307. var radiusX = extendSize.x;
  59308. var radiusY = extendSize.y;
  59309. var radiusZ = extendSize.z;
  59310. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  59311. break;
  59312. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  59313. case BABYLON.PhysicsImpostor.CylinderImpostor:
  59314. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  59315. break;
  59316. case BABYLON.PhysicsImpostor.BoxImpostor:
  59317. var box = extendSize.scale(0.5);
  59318. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  59319. break;
  59320. case BABYLON.PhysicsImpostor.PlaneImpostor:
  59321. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  59322. returnValue = new CANNON.Plane();
  59323. break;
  59324. case BABYLON.PhysicsImpostor.MeshImpostor:
  59325. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  59326. var rawFaces = object.getIndices ? object.getIndices() : [];
  59327. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  59328. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  59329. break;
  59330. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  59331. returnValue = this._createHeightmap(object);
  59332. break;
  59333. case BABYLON.PhysicsImpostor.ParticleImpostor:
  59334. returnValue = new CANNON.Particle();
  59335. break;
  59336. }
  59337. return returnValue;
  59338. };
  59339. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  59340. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59341. var matrix = [];
  59342. //For now pointDepth will not be used and will be automatically calculated.
  59343. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  59344. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  59345. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  59346. var elementSize = dim * 2 / arraySize;
  59347. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  59348. for (var i = 0; i < pos.length; i = i + 3) {
  59349. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  59350. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  59351. var y = pos[i + 1] + minY;
  59352. if (!matrix[x]) {
  59353. matrix[x] = [];
  59354. }
  59355. if (!matrix[x][z]) {
  59356. matrix[x][z] = y;
  59357. }
  59358. matrix[x][z] = Math.max(y, matrix[x][z]);
  59359. }
  59360. for (var x = 0; x <= arraySize; ++x) {
  59361. if (!matrix[x]) {
  59362. var loc = 1;
  59363. while (!matrix[(x + loc) % arraySize]) {
  59364. loc++;
  59365. }
  59366. matrix[x] = matrix[(x + loc) % arraySize].slice();
  59367. //console.log("missing x", x);
  59368. }
  59369. for (var z = 0; z <= arraySize; ++z) {
  59370. if (!matrix[x][z]) {
  59371. var loc = 1;
  59372. var newValue;
  59373. while (newValue === undefined) {
  59374. newValue = matrix[x][(z + loc++) % arraySize];
  59375. }
  59376. matrix[x][z] = newValue;
  59377. }
  59378. }
  59379. }
  59380. var shape = new CANNON.Heightfield(matrix, {
  59381. elementSize: elementSize
  59382. });
  59383. //For future reference, needed for body transformation
  59384. shape.minY = minY;
  59385. return shape;
  59386. };
  59387. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  59388. var object = impostor.object;
  59389. //make sure it is updated...
  59390. object.computeWorldMatrix && object.computeWorldMatrix(true);
  59391. // The delta between the mesh position and the mesh bounding box center
  59392. var center = impostor.getObjectCenter();
  59393. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  59394. this._tmpPosition.copyFrom(center);
  59395. var quaternion = object.rotationQuaternion;
  59396. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  59397. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  59398. //-90 DEG in X, precalculated
  59399. quaternion = quaternion.multiply(this._minus90X);
  59400. //Invert! (Precalculated, 90 deg in X)
  59401. //No need to clone. this will never change.
  59402. impostor.setDeltaRotation(this._plus90X);
  59403. }
  59404. //If it is a heightfield, if should be centered.
  59405. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  59406. var mesh = object;
  59407. //calculate the correct body position:
  59408. var rotationQuaternion = mesh.rotationQuaternion;
  59409. mesh.rotationQuaternion = this._tmpUnityRotation;
  59410. mesh.computeWorldMatrix(true);
  59411. //get original center with no rotation
  59412. var c = center.clone();
  59413. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  59414. //rotation is back
  59415. mesh.rotationQuaternion = rotationQuaternion;
  59416. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  59417. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  59418. mesh.setPivotMatrix(p);
  59419. mesh.computeWorldMatrix(true);
  59420. //calculate the translation
  59421. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  59422. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  59423. //add it inverted to the delta
  59424. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  59425. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  59426. mesh.setPivotMatrix(oldPivot);
  59427. mesh.computeWorldMatrix(true);
  59428. }
  59429. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  59430. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  59431. this._tmpPosition.copyFrom(object.position);
  59432. }
  59433. impostor.setDeltaPosition(this._tmpDeltaPosition);
  59434. //Now update the impostor object
  59435. impostor.physicsBody.position.copy(this._tmpPosition);
  59436. impostor.physicsBody.quaternion.copy(quaternion);
  59437. };
  59438. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  59439. impostor.object.position.copyFrom(impostor.physicsBody.position);
  59440. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  59441. };
  59442. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  59443. impostor.physicsBody.position.copy(newPosition);
  59444. impostor.physicsBody.quaternion.copy(newRotation);
  59445. };
  59446. CannonJSPlugin.prototype.isSupported = function () {
  59447. return window.CANNON !== undefined;
  59448. };
  59449. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  59450. impostor.physicsBody.velocity.copy(velocity);
  59451. };
  59452. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  59453. impostor.physicsBody.angularVelocity.copy(velocity);
  59454. };
  59455. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  59456. var v = impostor.physicsBody.velocity;
  59457. if (!v)
  59458. return null;
  59459. return new BABYLON.Vector3(v.x, v.y, v.z);
  59460. };
  59461. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  59462. var v = impostor.physicsBody.angularVelocity;
  59463. if (!v)
  59464. return null;
  59465. return new BABYLON.Vector3(v.x, v.y, v.z);
  59466. };
  59467. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  59468. impostor.physicsBody.mass = mass;
  59469. impostor.physicsBody.updateMassProperties();
  59470. };
  59471. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  59472. return impostor.physicsBody.mass;
  59473. };
  59474. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  59475. return impostor.physicsBody.material.friction;
  59476. };
  59477. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  59478. impostor.physicsBody.material.friction = friction;
  59479. };
  59480. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  59481. return impostor.physicsBody.material.restitution;
  59482. };
  59483. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  59484. impostor.physicsBody.material.restitution = restitution;
  59485. };
  59486. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  59487. impostor.physicsBody.sleep();
  59488. };
  59489. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  59490. impostor.physicsBody.wakeUp();
  59491. };
  59492. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  59493. joint.physicsJoint.distance = maxDistance;
  59494. };
  59495. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  59496. if (!motorIndex) {
  59497. joint.physicsJoint.enableMotor();
  59498. }
  59499. };
  59500. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  59501. if (!motorIndex) {
  59502. joint.physicsJoint.disableMotor();
  59503. }
  59504. };
  59505. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  59506. if (!motorIndex) {
  59507. joint.physicsJoint.enableMotor();
  59508. joint.physicsJoint.setMotorSpeed(speed);
  59509. if (maxForce) {
  59510. this.setLimit(joint, maxForce);
  59511. }
  59512. }
  59513. };
  59514. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  59515. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  59516. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  59517. };
  59518. CannonJSPlugin.prototype._getDebugMaterial = function (scene) {
  59519. if (!this._debugMaterial) {
  59520. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59521. this._debugMaterial.wireframe = true;
  59522. }
  59523. return this._debugMaterial;
  59524. };
  59525. CannonJSPlugin.prototype._getDebugBoxMesh = function (scene) {
  59526. if (!this._debugBoxMesh) {
  59527. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59528. this._debugBoxMesh.renderingGroupId = 1;
  59529. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59530. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59531. scene.removeMesh(this._debugBoxMesh);
  59532. }
  59533. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59534. };
  59535. CannonJSPlugin.prototype._getDebugSphereMesh = function (scene) {
  59536. if (!this._debugSphereMesh) {
  59537. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59538. this._debugSphereMesh.renderingGroupId = 1;
  59539. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59540. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59541. scene.removeMesh(this._debugSphereMesh);
  59542. }
  59543. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59544. };
  59545. CannonJSPlugin.prototype.getDebugMesh = function (impostor, scene) {
  59546. var body = impostor.physicsBody;
  59547. var shape = body.shapes[0];
  59548. var mesh;
  59549. if (shape.halfExtents) {
  59550. mesh = this._getDebugBoxMesh(scene);
  59551. mesh.scaling.x = shape.halfExtents.x * 2;
  59552. mesh.scaling.y = shape.halfExtents.y * 2;
  59553. mesh.scaling.z = shape.halfExtents.z * 2;
  59554. }
  59555. else if (shape.boundingSphereRadius) {
  59556. mesh = this._getDebugSphereMesh(scene);
  59557. mesh.scaling.x = shape.boundingSphereRadius * 2;
  59558. mesh.scaling.y = shape.boundingSphereRadius * 2;
  59559. mesh.scaling.z = shape.boundingSphereRadius * 2;
  59560. }
  59561. return mesh;
  59562. };
  59563. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  59564. var body = impostor.physicsBody;
  59565. mesh.position.x = body.position.x;
  59566. mesh.position.y = body.position.y;
  59567. mesh.position.z = body.position.z;
  59568. mesh.rotationQuaternion.x = body.quaternion.x;
  59569. mesh.rotationQuaternion.y = body.quaternion.y;
  59570. mesh.rotationQuaternion.z = body.quaternion.z;
  59571. mesh.rotationQuaternion.w = body.quaternion.w;
  59572. };
  59573. CannonJSPlugin.prototype.dispose = function () {
  59574. if (this._debugBoxMesh) {
  59575. this._debugBoxMesh.dispose();
  59576. }
  59577. if (this._debugSphereMesh) {
  59578. this._debugSphereMesh.dispose();
  59579. }
  59580. if (this._debugMaterial) {
  59581. this._debugMaterial.dispose();
  59582. }
  59583. };
  59584. return CannonJSPlugin;
  59585. }());
  59586. BABYLON.CannonJSPlugin = CannonJSPlugin;
  59587. })(BABYLON || (BABYLON = {}));
  59588. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  59589. var BABYLON;
  59590. (function (BABYLON) {
  59591. var OimoJSPlugin = (function () {
  59592. function OimoJSPlugin(iterations) {
  59593. this.name = "OimoJSPlugin";
  59594. this._tmpImpostorsArray = [];
  59595. this._tmpPositionVector = BABYLON.Vector3.Zero();
  59596. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  59597. this.world.worldscale(1);
  59598. this.world.clear();
  59599. //making sure no stats are calculated
  59600. this.world.isNoStat = true;
  59601. }
  59602. OimoJSPlugin.prototype.setGravity = function (gravity) {
  59603. this.world.gravity.copy(gravity);
  59604. };
  59605. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  59606. this.world.timeStep = timeStep;
  59607. };
  59608. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  59609. var _this = this;
  59610. impostors.forEach(function (impostor) {
  59611. impostor.beforeStep();
  59612. });
  59613. this.world.step();
  59614. impostors.forEach(function (impostor) {
  59615. impostor.afterStep();
  59616. //update the ordered impostors array
  59617. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  59618. });
  59619. //check for collisions
  59620. var contact = this.world.contacts;
  59621. while (contact !== null) {
  59622. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  59623. contact = contact.next;
  59624. continue;
  59625. }
  59626. //is this body colliding with any other? get the impostor
  59627. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  59628. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  59629. if (!mainImpostor || !collidingImpostor) {
  59630. contact = contact.next;
  59631. continue;
  59632. }
  59633. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  59634. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  59635. contact = contact.next;
  59636. }
  59637. };
  59638. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  59639. var mass = impostor.physicsBody.massInfo.mass;
  59640. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  59641. };
  59642. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  59643. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  59644. this.applyImpulse(impostor, force, contactPoint);
  59645. };
  59646. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  59647. var _this = this;
  59648. //parent-child relationship. Does this impostor has a parent impostor?
  59649. if (impostor.parent) {
  59650. if (impostor.physicsBody) {
  59651. this.removePhysicsBody(impostor);
  59652. //TODO is that needed?
  59653. impostor.forceUpdate();
  59654. }
  59655. return;
  59656. }
  59657. if (impostor.isBodyInitRequired()) {
  59658. var bodyConfig = {
  59659. name: impostor.uniqueId,
  59660. //Oimo must have mass, also for static objects.
  59661. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  59662. size: [],
  59663. type: [],
  59664. pos: [],
  59665. rot: [],
  59666. move: impostor.getParam("mass") !== 0,
  59667. //Supporting older versions of Oimo
  59668. world: this.world
  59669. };
  59670. var impostors = [impostor];
  59671. var addToArray = function (parent) {
  59672. if (!parent.getChildMeshes)
  59673. return;
  59674. parent.getChildMeshes().forEach(function (m) {
  59675. if (m.physicsImpostor) {
  59676. impostors.push(m.physicsImpostor);
  59677. m.physicsImpostor._init();
  59678. }
  59679. });
  59680. };
  59681. addToArray(impostor.object);
  59682. var checkWithEpsilon_1 = function (value) {
  59683. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  59684. };
  59685. impostors.forEach(function (i) {
  59686. //get the correct bounding box
  59687. var oldQuaternion = i.object.rotationQuaternion;
  59688. var rot = new OIMO.Euler().setFromQuaternion({
  59689. x: impostor.object.rotationQuaternion.x,
  59690. y: impostor.object.rotationQuaternion.y,
  59691. z: impostor.object.rotationQuaternion.z,
  59692. s: impostor.object.rotationQuaternion.w
  59693. });
  59694. var extendSize = i.getObjectExtendSize();
  59695. if (i === impostor) {
  59696. var center = impostor.getObjectCenter();
  59697. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  59698. //Can also use Array.prototype.push.apply
  59699. bodyConfig.pos.push(center.x);
  59700. bodyConfig.pos.push(center.y);
  59701. bodyConfig.pos.push(center.z);
  59702. //tmp solution
  59703. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  59704. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  59705. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  59706. }
  59707. else {
  59708. bodyConfig.pos.push(i.object.position.x);
  59709. bodyConfig.pos.push(i.object.position.y);
  59710. bodyConfig.pos.push(i.object.position.z);
  59711. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  59712. bodyConfig.rot.push(0);
  59713. bodyConfig.rot.push(0);
  59714. bodyConfig.rot.push(0);
  59715. }
  59716. // register mesh
  59717. switch (i.type) {
  59718. case BABYLON.PhysicsImpostor.ParticleImpostor:
  59719. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  59720. case BABYLON.PhysicsImpostor.SphereImpostor:
  59721. var radiusX = extendSize.x;
  59722. var radiusY = extendSize.y;
  59723. var radiusZ = extendSize.z;
  59724. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  59725. bodyConfig.type.push('sphere');
  59726. //due to the way oimo works with compounds, add 3 times
  59727. bodyConfig.size.push(size);
  59728. bodyConfig.size.push(size);
  59729. bodyConfig.size.push(size);
  59730. break;
  59731. case BABYLON.PhysicsImpostor.CylinderImpostor:
  59732. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  59733. var sizeY = checkWithEpsilon_1(extendSize.y);
  59734. bodyConfig.type.push('cylinder');
  59735. bodyConfig.size.push(sizeX);
  59736. bodyConfig.size.push(sizeY);
  59737. //due to the way oimo works with compounds, add one more value.
  59738. bodyConfig.size.push(sizeY);
  59739. break;
  59740. case BABYLON.PhysicsImpostor.PlaneImpostor:
  59741. case BABYLON.PhysicsImpostor.BoxImpostor:
  59742. default:
  59743. var sizeX = checkWithEpsilon_1(extendSize.x);
  59744. var sizeY = checkWithEpsilon_1(extendSize.y);
  59745. var sizeZ = checkWithEpsilon_1(extendSize.z);
  59746. bodyConfig.type.push('box');
  59747. bodyConfig.size.push(sizeX);
  59748. bodyConfig.size.push(sizeY);
  59749. bodyConfig.size.push(sizeZ);
  59750. break;
  59751. }
  59752. //actually not needed, but hey...
  59753. i.object.rotationQuaternion = oldQuaternion;
  59754. });
  59755. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  59756. }
  59757. else {
  59758. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  59759. }
  59760. impostor.setDeltaPosition(this._tmpPositionVector);
  59761. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  59762. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  59763. };
  59764. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  59765. //impostor.physicsBody.dispose();
  59766. //Same as : (older oimo versions)
  59767. this.world.removeRigidBody(impostor.physicsBody);
  59768. };
  59769. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  59770. var mainBody = impostorJoint.mainImpostor.physicsBody;
  59771. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  59772. if (!mainBody || !connectedBody) {
  59773. return;
  59774. }
  59775. var jointData = impostorJoint.joint.jointData;
  59776. var options = jointData.nativeParams || {};
  59777. var type;
  59778. var nativeJointData = {
  59779. body1: mainBody,
  59780. body2: connectedBody,
  59781. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  59782. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  59783. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  59784. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  59785. min: options.min,
  59786. max: options.max,
  59787. collision: options.collision || jointData.collision,
  59788. spring: options.spring,
  59789. //supporting older version of Oimo
  59790. world: this.world
  59791. };
  59792. switch (impostorJoint.joint.type) {
  59793. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  59794. type = "jointBall";
  59795. break;
  59796. case BABYLON.PhysicsJoint.SpringJoint:
  59797. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  59798. var springData = jointData;
  59799. nativeJointData.min = springData.length || nativeJointData.min;
  59800. //Max should also be set, just make sure it is at least min
  59801. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  59802. case BABYLON.PhysicsJoint.DistanceJoint:
  59803. type = "jointDistance";
  59804. nativeJointData.max = jointData.maxDistance;
  59805. break;
  59806. case BABYLON.PhysicsJoint.PrismaticJoint:
  59807. type = "jointPrisme";
  59808. break;
  59809. case BABYLON.PhysicsJoint.SliderJoint:
  59810. type = "jointSlide";
  59811. break;
  59812. case BABYLON.PhysicsJoint.WheelJoint:
  59813. type = "jointWheel";
  59814. break;
  59815. case BABYLON.PhysicsJoint.HingeJoint:
  59816. default:
  59817. type = "jointHinge";
  59818. break;
  59819. }
  59820. nativeJointData.type = type;
  59821. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  59822. };
  59823. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  59824. //Bug in Oimo prevents us from disposing a joint in the playground
  59825. //joint.joint.physicsJoint.dispose();
  59826. //So we will bruteforce it!
  59827. try {
  59828. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  59829. }
  59830. catch (e) {
  59831. BABYLON.Tools.Warn(e);
  59832. }
  59833. };
  59834. OimoJSPlugin.prototype.isSupported = function () {
  59835. return OIMO !== undefined;
  59836. };
  59837. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  59838. if (!impostor.physicsBody.sleeping) {
  59839. //TODO check that
  59840. if (impostor.physicsBody.shapes.next) {
  59841. var parentShape = this._getLastShape(impostor.physicsBody);
  59842. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  59843. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  59844. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  59845. }
  59846. else {
  59847. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  59848. }
  59849. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  59850. impostor.object.rotationQuaternion.normalize();
  59851. }
  59852. };
  59853. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  59854. var body = impostor.physicsBody;
  59855. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  59856. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  59857. body.syncShapes();
  59858. body.awake();
  59859. };
  59860. OimoJSPlugin.prototype._getLastShape = function (body) {
  59861. var lastShape = body.shapes;
  59862. while (lastShape.next) {
  59863. lastShape = lastShape.next;
  59864. }
  59865. return lastShape;
  59866. };
  59867. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  59868. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  59869. };
  59870. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  59871. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  59872. };
  59873. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  59874. var v = impostor.physicsBody.linearVelocity;
  59875. if (!v)
  59876. return null;
  59877. return new BABYLON.Vector3(v.x, v.y, v.z);
  59878. };
  59879. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  59880. var v = impostor.physicsBody.angularVelocity;
  59881. if (!v)
  59882. return null;
  59883. return new BABYLON.Vector3(v.x, v.y, v.z);
  59884. };
  59885. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  59886. var staticBody = mass === 0;
  59887. //this will actually set the body's density and not its mass.
  59888. //But this is how oimo treats the mass variable.
  59889. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  59890. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  59891. };
  59892. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  59893. return impostor.physicsBody.shapes.density;
  59894. };
  59895. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  59896. return impostor.physicsBody.shapes.friction;
  59897. };
  59898. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  59899. impostor.physicsBody.shapes.friction = friction;
  59900. };
  59901. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  59902. return impostor.physicsBody.shapes.restitution;
  59903. };
  59904. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  59905. impostor.physicsBody.shapes.restitution = restitution;
  59906. };
  59907. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  59908. impostor.physicsBody.sleep();
  59909. };
  59910. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  59911. impostor.physicsBody.awake();
  59912. };
  59913. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  59914. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  59915. if (minDistance !== void 0) {
  59916. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  59917. }
  59918. };
  59919. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  59920. //TODO separate rotational and transational motors.
  59921. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  59922. if (motor) {
  59923. motor.setMotor(speed, maxForce);
  59924. }
  59925. };
  59926. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  59927. //TODO separate rotational and transational motors.
  59928. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  59929. if (motor) {
  59930. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  59931. }
  59932. };
  59933. OimoJSPlugin.prototype._getDebugMaterial = function (scene) {
  59934. if (!this._debugMaterial) {
  59935. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59936. this._debugMaterial.wireframe = true;
  59937. }
  59938. return this._debugMaterial;
  59939. };
  59940. OimoJSPlugin.prototype._getDebugBoxMesh = function (scene) {
  59941. if (!this._debugBoxMesh) {
  59942. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59943. this._debugBoxMesh.renderingGroupId = 1;
  59944. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59945. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59946. scene.removeMesh(this._debugBoxMesh);
  59947. }
  59948. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59949. };
  59950. OimoJSPlugin.prototype._getDebugSphereMesh = function (scene) {
  59951. if (!this._debugSphereMesh) {
  59952. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59953. this._debugSphereMesh.renderingGroupId = 1;
  59954. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59955. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59956. scene.removeMesh(this._debugSphereMesh);
  59957. }
  59958. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59959. };
  59960. OimoJSPlugin.prototype.getDebugMesh = function (impostor, scene) {
  59961. var body = impostor.physicsBody;
  59962. var shape = body.shapes;
  59963. var mesh;
  59964. if (shape.halfWidth) {
  59965. mesh = this._getDebugBoxMesh(scene);
  59966. mesh.scaling.x = shape.halfWidth * 2;
  59967. mesh.scaling.y = shape.halfHeight * 2;
  59968. mesh.scaling.z = shape.halfDepth * 2;
  59969. }
  59970. else if (shape.radius) {
  59971. mesh = this._getDebugSphereMesh(scene);
  59972. mesh.scaling.x = shape.radius * 2;
  59973. mesh.scaling.y = shape.radius * 2;
  59974. mesh.scaling.z = shape.radius * 2;
  59975. }
  59976. return mesh;
  59977. };
  59978. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  59979. var body = impostor.physicsBody;
  59980. mesh.position.x = body.position.x;
  59981. mesh.position.y = body.position.y;
  59982. mesh.position.z = body.position.z;
  59983. mesh.rotationQuaternion.x = body.orientation.x;
  59984. mesh.rotationQuaternion.y = body.orientation.y;
  59985. mesh.rotationQuaternion.z = body.orientation.z;
  59986. mesh.rotationQuaternion.w = body.orientation.s;
  59987. };
  59988. OimoJSPlugin.prototype.dispose = function () {
  59989. if (this._debugBoxMesh) {
  59990. this._debugBoxMesh.dispose();
  59991. }
  59992. if (this._debugSphereMesh) {
  59993. this._debugSphereMesh.dispose();
  59994. }
  59995. if (this._debugMaterial) {
  59996. this._debugMaterial.dispose();
  59997. }
  59998. this.world.clear();
  59999. };
  60000. return OimoJSPlugin;
  60001. }());
  60002. BABYLON.OimoJSPlugin = OimoJSPlugin;
  60003. })(BABYLON || (BABYLON = {}));
  60004. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  60005. var BABYLON;
  60006. (function (BABYLON) {
  60007. var Internals;
  60008. (function (Internals) {
  60009. /*
  60010. * Based on jsTGALoader - Javascript loader for TGA file
  60011. * By Vincent Thibault
  60012. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  60013. */
  60014. var TGATools = (function () {
  60015. function TGATools() {
  60016. }
  60017. TGATools.GetTGAHeader = function (data) {
  60018. var offset = 0;
  60019. var header = {
  60020. id_length: data[offset++],
  60021. colormap_type: data[offset++],
  60022. image_type: data[offset++],
  60023. colormap_index: data[offset++] | data[offset++] << 8,
  60024. colormap_length: data[offset++] | data[offset++] << 8,
  60025. colormap_size: data[offset++],
  60026. origin: [
  60027. data[offset++] | data[offset++] << 8,
  60028. data[offset++] | data[offset++] << 8
  60029. ],
  60030. width: data[offset++] | data[offset++] << 8,
  60031. height: data[offset++] | data[offset++] << 8,
  60032. pixel_size: data[offset++],
  60033. flags: data[offset++]
  60034. };
  60035. return header;
  60036. };
  60037. TGATools.UploadContent = function (gl, data) {
  60038. // Not enough data to contain header ?
  60039. if (data.length < 19) {
  60040. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  60041. return;
  60042. }
  60043. // Read Header
  60044. var offset = 18;
  60045. var header = TGATools.GetTGAHeader(data);
  60046. // Assume it's a valid Targa file.
  60047. if (header.id_length + offset > data.length) {
  60048. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  60049. return;
  60050. }
  60051. // Skip not needed data
  60052. offset += header.id_length;
  60053. var use_rle = false;
  60054. var use_pal = false;
  60055. var use_rgb = false;
  60056. var use_grey = false;
  60057. // Get some informations.
  60058. switch (header.image_type) {
  60059. case TGATools._TYPE_RLE_INDEXED:
  60060. use_rle = true;
  60061. case TGATools._TYPE_INDEXED:
  60062. use_pal = true;
  60063. break;
  60064. case TGATools._TYPE_RLE_RGB:
  60065. use_rle = true;
  60066. case TGATools._TYPE_RGB:
  60067. use_rgb = true;
  60068. break;
  60069. case TGATools._TYPE_RLE_GREY:
  60070. use_rle = true;
  60071. case TGATools._TYPE_GREY:
  60072. use_grey = true;
  60073. break;
  60074. }
  60075. var pixel_data;
  60076. var numAlphaBits = header.flags & 0xf;
  60077. var pixel_size = header.pixel_size >> 3;
  60078. var pixel_total = header.width * header.height * pixel_size;
  60079. // Read palettes
  60080. var palettes;
  60081. if (use_pal) {
  60082. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  60083. }
  60084. // Read LRE
  60085. if (use_rle) {
  60086. pixel_data = new Uint8Array(pixel_total);
  60087. var c, count, i;
  60088. var localOffset = 0;
  60089. var pixels = new Uint8Array(pixel_size);
  60090. while (offset < pixel_total && localOffset < pixel_total) {
  60091. c = data[offset++];
  60092. count = (c & 0x7f) + 1;
  60093. // RLE pixels
  60094. if (c & 0x80) {
  60095. // Bind pixel tmp array
  60096. for (i = 0; i < pixel_size; ++i) {
  60097. pixels[i] = data[offset++];
  60098. }
  60099. // Copy pixel array
  60100. for (i = 0; i < count; ++i) {
  60101. pixel_data.set(pixels, localOffset + i * pixel_size);
  60102. }
  60103. localOffset += pixel_size * count;
  60104. }
  60105. else {
  60106. count *= pixel_size;
  60107. for (i = 0; i < count; ++i) {
  60108. pixel_data[localOffset + i] = data[offset++];
  60109. }
  60110. localOffset += count;
  60111. }
  60112. }
  60113. }
  60114. else {
  60115. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  60116. }
  60117. // Load to texture
  60118. var x_start, y_start, x_step, y_step, y_end, x_end;
  60119. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  60120. default:
  60121. case TGATools._ORIGIN_UL:
  60122. x_start = 0;
  60123. x_step = 1;
  60124. x_end = header.width;
  60125. y_start = 0;
  60126. y_step = 1;
  60127. y_end = header.height;
  60128. break;
  60129. case TGATools._ORIGIN_BL:
  60130. x_start = 0;
  60131. x_step = 1;
  60132. x_end = header.width;
  60133. y_start = header.height - 1;
  60134. y_step = -1;
  60135. y_end = -1;
  60136. break;
  60137. case TGATools._ORIGIN_UR:
  60138. x_start = header.width - 1;
  60139. x_step = -1;
  60140. x_end = -1;
  60141. y_start = 0;
  60142. y_step = 1;
  60143. y_end = header.height;
  60144. break;
  60145. case TGATools._ORIGIN_BR:
  60146. x_start = header.width - 1;
  60147. x_step = -1;
  60148. x_end = -1;
  60149. y_start = header.height - 1;
  60150. y_step = -1;
  60151. y_end = -1;
  60152. break;
  60153. }
  60154. // Load the specify method
  60155. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  60156. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  60157. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  60158. };
  60159. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60160. var image = pixel_data, colormap = palettes;
  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 + 3] = 255;
  60168. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  60169. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  60170. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  60171. }
  60172. }
  60173. return imageData;
  60174. };
  60175. TGATools._getImageData16bits = 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 color, 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. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  60183. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  60184. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  60185. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  60186. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  60187. }
  60188. }
  60189. return imageData;
  60190. };
  60191. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60192. var image = pixel_data;
  60193. var width = header.width, height = header.height;
  60194. var i = 0, x, y;
  60195. var imageData = new Uint8Array(width * height * 4);
  60196. for (y = y_start; y !== y_end; y += y_step) {
  60197. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  60198. imageData[(x + width * y) * 4 + 3] = 255;
  60199. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60200. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60201. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60202. }
  60203. }
  60204. return imageData;
  60205. };
  60206. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60207. var image = pixel_data;
  60208. var width = header.width, height = header.height;
  60209. var i = 0, x, y;
  60210. var imageData = new Uint8Array(width * height * 4);
  60211. for (y = y_start; y !== y_end; y += y_step) {
  60212. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  60213. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60214. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60215. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60216. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  60217. }
  60218. }
  60219. return imageData;
  60220. };
  60221. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60222. var image = pixel_data;
  60223. var width = header.width, height = header.height;
  60224. var color, i = 0, x, y;
  60225. var imageData = new Uint8Array(width * height * 4);
  60226. for (y = y_start; y !== y_end; y += y_step) {
  60227. for (x = x_start; x !== x_end; x += x_step, i++) {
  60228. color = image[i];
  60229. imageData[(x + width * y) * 4 + 0] = color;
  60230. imageData[(x + width * y) * 4 + 1] = color;
  60231. imageData[(x + width * y) * 4 + 2] = color;
  60232. imageData[(x + width * y) * 4 + 3] = 255;
  60233. }
  60234. }
  60235. return imageData;
  60236. };
  60237. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60238. var image = pixel_data;
  60239. var width = header.width, height = header.height;
  60240. var i = 0, x, y;
  60241. var imageData = new Uint8Array(width * height * 4);
  60242. for (y = y_start; y !== y_end; y += y_step) {
  60243. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60244. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  60245. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  60246. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60247. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  60248. }
  60249. }
  60250. return imageData;
  60251. };
  60252. return TGATools;
  60253. }());
  60254. TGATools._TYPE_NO_DATA = 0;
  60255. TGATools._TYPE_INDEXED = 1;
  60256. TGATools._TYPE_RGB = 2;
  60257. TGATools._TYPE_GREY = 3;
  60258. TGATools._TYPE_RLE_INDEXED = 9;
  60259. TGATools._TYPE_RLE_RGB = 10;
  60260. TGATools._TYPE_RLE_GREY = 11;
  60261. TGATools._ORIGIN_MASK = 0x30;
  60262. TGATools._ORIGIN_SHIFT = 0x04;
  60263. TGATools._ORIGIN_BL = 0x00;
  60264. TGATools._ORIGIN_BR = 0x01;
  60265. TGATools._ORIGIN_UL = 0x02;
  60266. TGATools._ORIGIN_UR = 0x03;
  60267. Internals.TGATools = TGATools;
  60268. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60269. })(BABYLON || (BABYLON = {}));
  60270. //# sourceMappingURL=babylon.tga.js.map
  60271. var BABYLON;
  60272. (function (BABYLON) {
  60273. var Internals;
  60274. (function (Internals) {
  60275. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  60276. // All values and structures referenced from:
  60277. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  60278. var DDS_MAGIC = 0x20534444;
  60279. 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;
  60280. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  60281. 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;
  60282. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  60283. function FourCCToInt32(value) {
  60284. return value.charCodeAt(0) +
  60285. (value.charCodeAt(1) << 8) +
  60286. (value.charCodeAt(2) << 16) +
  60287. (value.charCodeAt(3) << 24);
  60288. }
  60289. function Int32ToFourCC(value) {
  60290. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  60291. }
  60292. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  60293. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  60294. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  60295. var FOURCC_DX10 = FourCCToInt32("DX10");
  60296. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  60297. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  60298. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  60299. var headerLengthInt = 31; // The header length in 32 bit ints
  60300. // Offsets into the header array
  60301. var off_magic = 0;
  60302. var off_size = 1;
  60303. var off_flags = 2;
  60304. var off_height = 3;
  60305. var off_width = 4;
  60306. var off_mipmapCount = 7;
  60307. var off_pfFlags = 20;
  60308. var off_pfFourCC = 21;
  60309. var off_RGBbpp = 22;
  60310. var off_RMask = 23;
  60311. var off_GMask = 24;
  60312. var off_BMask = 25;
  60313. var off_AMask = 26;
  60314. var off_caps1 = 27;
  60315. var off_caps2 = 28;
  60316. var off_caps3 = 29;
  60317. var off_caps4 = 30;
  60318. var off_dxgiFormat = 32;
  60319. ;
  60320. var DDSTools = (function () {
  60321. function DDSTools() {
  60322. }
  60323. DDSTools.GetDDSInfo = function (arrayBuffer) {
  60324. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  60325. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  60326. var mipmapCount = 1;
  60327. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  60328. mipmapCount = Math.max(1, header[off_mipmapCount]);
  60329. }
  60330. var fourCC = header[off_pfFourCC];
  60331. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  60332. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60333. switch (fourCC) {
  60334. case FOURCC_D3DFMT_R16G16B16A16F:
  60335. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60336. break;
  60337. case FOURCC_D3DFMT_R32G32B32A32F:
  60338. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60339. break;
  60340. case FOURCC_DX10:
  60341. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  60342. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60343. break;
  60344. }
  60345. }
  60346. return {
  60347. width: header[off_width],
  60348. height: header[off_height],
  60349. mipmapCount: mipmapCount,
  60350. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  60351. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  60352. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  60353. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  60354. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  60355. dxgiFormat: dxgiFormat,
  60356. textureType: textureType
  60357. };
  60358. };
  60359. DDSTools._ToHalfFloat = function (value) {
  60360. if (!DDSTools._FloatView) {
  60361. DDSTools._FloatView = new Float32Array(1);
  60362. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  60363. }
  60364. DDSTools._FloatView[0] = value;
  60365. var x = DDSTools._Int32View[0];
  60366. var bits = (x >> 16) & 0x8000; /* Get the sign */
  60367. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  60368. var e = (x >> 23) & 0xff; /* Using int is faster here */
  60369. /* If zero, or denormal, or exponent underflows too much for a denormal
  60370. * half, return signed zero. */
  60371. if (e < 103) {
  60372. return bits;
  60373. }
  60374. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  60375. if (e > 142) {
  60376. bits |= 0x7c00;
  60377. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  60378. * not Inf, so make sure we set one mantissa bit too. */
  60379. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  60380. return bits;
  60381. }
  60382. /* If exponent underflows but not too much, return a denormal */
  60383. if (e < 113) {
  60384. m |= 0x0800;
  60385. /* Extra rounding may overflow and set mantissa to 0 and exponent
  60386. * to 1, which is OK. */
  60387. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  60388. return bits;
  60389. }
  60390. bits |= ((e - 112) << 10) | (m >> 1);
  60391. bits += m & 1;
  60392. return bits;
  60393. };
  60394. DDSTools._FromHalfFloat = function (value) {
  60395. var s = (value & 0x8000) >> 15;
  60396. var e = (value & 0x7C00) >> 10;
  60397. var f = value & 0x03FF;
  60398. if (e === 0) {
  60399. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  60400. }
  60401. else if (e == 0x1F) {
  60402. return f ? NaN : ((s ? -1 : 1) * Infinity);
  60403. }
  60404. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  60405. };
  60406. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60407. var destArray = new Float32Array(dataLength);
  60408. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  60409. var index = 0;
  60410. for (var y = 0; y < height; y++) {
  60411. for (var x = 0; x < width; x++) {
  60412. var srcPos = (x + y * width) * 4;
  60413. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  60414. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  60415. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  60416. if (DDSTools.StoreLODInAlphaChannel) {
  60417. destArray[index + 3] = lod;
  60418. }
  60419. else {
  60420. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  60421. }
  60422. index += 4;
  60423. }
  60424. }
  60425. return destArray;
  60426. };
  60427. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60428. if (DDSTools.StoreLODInAlphaChannel) {
  60429. var destArray = new Uint16Array(dataLength);
  60430. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  60431. var index = 0;
  60432. for (var y = 0; y < height; y++) {
  60433. for (var x = 0; x < width; x++) {
  60434. var srcPos = (x + y * width) * 4;
  60435. destArray[index] = srcData[srcPos];
  60436. destArray[index + 1] = srcData[srcPos + 1];
  60437. destArray[index + 2] = srcData[srcPos + 2];
  60438. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  60439. index += 4;
  60440. }
  60441. }
  60442. return destArray;
  60443. }
  60444. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  60445. };
  60446. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60447. if (DDSTools.StoreLODInAlphaChannel) {
  60448. var destArray = new Float32Array(dataLength);
  60449. var srcData = new Float32Array(arrayBuffer, dataOffset);
  60450. var index = 0;
  60451. for (var y = 0; y < height; y++) {
  60452. for (var x = 0; x < width; x++) {
  60453. var srcPos = (x + y * width) * 4;
  60454. destArray[index] = srcData[srcPos];
  60455. destArray[index + 1] = srcData[srcPos + 1];
  60456. destArray[index + 2] = srcData[srcPos + 2];
  60457. destArray[index + 3] = lod;
  60458. index += 4;
  60459. }
  60460. }
  60461. return destArray;
  60462. }
  60463. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  60464. };
  60465. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60466. var byteArray = new Uint8Array(dataLength);
  60467. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  60468. var index = 0;
  60469. for (var y = 0; y < height; y++) {
  60470. for (var x = 0; x < width; x++) {
  60471. var srcPos = (x + y * width) * 4;
  60472. byteArray[index] = srcData[srcPos + 2];
  60473. byteArray[index + 1] = srcData[srcPos + 1];
  60474. byteArray[index + 2] = srcData[srcPos];
  60475. byteArray[index + 3] = srcData[srcPos + 3];
  60476. index += 4;
  60477. }
  60478. }
  60479. return byteArray;
  60480. };
  60481. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60482. var byteArray = new Uint8Array(dataLength);
  60483. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  60484. var index = 0;
  60485. for (var y = 0; y < height; y++) {
  60486. for (var x = 0; x < width; x++) {
  60487. var srcPos = (x + y * width) * 3;
  60488. byteArray[index] = srcData[srcPos + 2];
  60489. byteArray[index + 1] = srcData[srcPos + 1];
  60490. byteArray[index + 2] = srcData[srcPos];
  60491. index += 3;
  60492. }
  60493. }
  60494. return byteArray;
  60495. };
  60496. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60497. var byteArray = new Uint8Array(dataLength);
  60498. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  60499. var index = 0;
  60500. for (var y = 0; y < height; y++) {
  60501. for (var x = 0; x < width; x++) {
  60502. var srcPos = (x + y * width);
  60503. byteArray[index] = srcData[srcPos];
  60504. index++;
  60505. }
  60506. }
  60507. return byteArray;
  60508. };
  60509. DDSTools.UploadDDSLevels = function (engine, arrayBuffer, info, loadMipmaps, faces) {
  60510. var gl = engine._gl;
  60511. var ext = engine.getCaps().s3tc;
  60512. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  60513. if (header[off_magic] != DDS_MAGIC) {
  60514. BABYLON.Tools.Error("Invalid magic number in DDS header");
  60515. return;
  60516. }
  60517. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  60518. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  60519. return;
  60520. }
  60521. if (info.isCompressed && !ext) {
  60522. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  60523. return;
  60524. }
  60525. var bpp = header[off_RGBbpp];
  60526. dataOffset = header[off_size] + 4;
  60527. var computeFormats = false;
  60528. if (info.isFourCC) {
  60529. fourCC = header[off_pfFourCC];
  60530. switch (fourCC) {
  60531. case FOURCC_DXT1:
  60532. blockBytes = 8;
  60533. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  60534. break;
  60535. case FOURCC_DXT3:
  60536. blockBytes = 16;
  60537. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  60538. break;
  60539. case FOURCC_DXT5:
  60540. blockBytes = 16;
  60541. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  60542. break;
  60543. case FOURCC_D3DFMT_R16G16B16A16F:
  60544. computeFormats = true;
  60545. break;
  60546. case FOURCC_D3DFMT_R32G32B32A32F:
  60547. computeFormats = true;
  60548. break;
  60549. case FOURCC_DX10:
  60550. // There is an additionnal header so dataOffset need to be changed
  60551. dataOffset += 5 * 4; // 5 uints
  60552. if (info.dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  60553. computeFormats = true;
  60554. break;
  60555. }
  60556. default:
  60557. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  60558. return;
  60559. }
  60560. }
  60561. if (computeFormats) {
  60562. format = engine._getWebGLTextureType(info.textureType);
  60563. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  60564. }
  60565. mipmapCount = 1;
  60566. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  60567. mipmapCount = Math.max(1, header[off_mipmapCount]);
  60568. }
  60569. for (var face = 0; face < faces; face++) {
  60570. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  60571. width = header[off_width];
  60572. height = header[off_height];
  60573. for (i = 0; i < mipmapCount; ++i) {
  60574. if (!info.isCompressed && info.isFourCC) {
  60575. dataLength = width * height * 4;
  60576. var floatArray;
  60577. if (bpp === 128) {
  60578. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60579. }
  60580. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  60581. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60582. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60583. format = engine._getWebGLTextureType(info.textureType);
  60584. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  60585. }
  60586. else {
  60587. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60588. }
  60589. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  60590. }
  60591. else if (info.isRGB) {
  60592. if (bpp === 24) {
  60593. dataLength = width * height * 3;
  60594. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60595. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  60596. }
  60597. else {
  60598. dataLength = width * height * 4;
  60599. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60600. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  60601. }
  60602. }
  60603. else if (info.isLuminance) {
  60604. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  60605. var unpaddedRowSize = width;
  60606. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  60607. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  60608. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60609. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  60610. }
  60611. else {
  60612. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  60613. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  60614. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  60615. }
  60616. dataOffset += width * height * (bpp / 8);
  60617. width *= 0.5;
  60618. height *= 0.5;
  60619. width = Math.max(1.0, width);
  60620. height = Math.max(1.0, height);
  60621. }
  60622. }
  60623. };
  60624. return DDSTools;
  60625. }());
  60626. DDSTools.StoreLODInAlphaChannel = false;
  60627. Internals.DDSTools = DDSTools;
  60628. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60629. })(BABYLON || (BABYLON = {}));
  60630. //# sourceMappingURL=babylon.dds.js.map
  60631. var BABYLON;
  60632. (function (BABYLON) {
  60633. var Internals;
  60634. (function (Internals) {
  60635. /**
  60636. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  60637. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  60638. */
  60639. var KhronosTextureContainer = (function () {
  60640. /**
  60641. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  60642. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  60643. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  60644. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  60645. */
  60646. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  60647. this.arrayBuffer = arrayBuffer;
  60648. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  60649. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  60650. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  60651. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  60652. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  60653. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  60654. BABYLON.Tools.Error("texture missing KTX identifier");
  60655. return;
  60656. }
  60657. // load the reset of the header in native 32 bit int
  60658. var header = new Int32Array(this.arrayBuffer, 12, 13);
  60659. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  60660. var oppositeEndianess = header[0] === 0x01020304;
  60661. // read all the header elements in order they exist in the file, without modification (sans endainness)
  60662. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  60663. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  60664. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  60665. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  60666. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  60667. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  60668. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  60669. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  60670. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  60671. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  60672. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  60673. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  60674. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  60675. if (this.glType !== 0) {
  60676. BABYLON.Tools.Error("only compressed formats currently supported");
  60677. return;
  60678. }
  60679. else {
  60680. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  60681. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  60682. }
  60683. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  60684. BABYLON.Tools.Error("only 2D textures currently supported");
  60685. return;
  60686. }
  60687. if (this.numberOfArrayElements !== 0) {
  60688. BABYLON.Tools.Error("texture arrays not currently supported");
  60689. return;
  60690. }
  60691. if (this.numberOfFaces !== facesExpected) {
  60692. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  60693. return;
  60694. }
  60695. // we now have a completely validated file, so could use existence of loadType as success
  60696. // would need to make this more elaborate & adjust checks above to support more than one load type
  60697. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  60698. }
  60699. // not as fast hardware based, but will probably never need to use
  60700. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  60701. return ((val & 0xFF) << 24)
  60702. | ((val & 0xFF00) << 8)
  60703. | ((val >> 8) & 0xFF00)
  60704. | ((val >> 24) & 0xFF);
  60705. };
  60706. /**
  60707. * It is assumed that the texture has already been created & is currently bound
  60708. */
  60709. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  60710. switch (this.loadType) {
  60711. case KhronosTextureContainer.COMPRESSED_2D:
  60712. this._upload2DCompressedLevels(gl, loadMipmaps);
  60713. break;
  60714. case KhronosTextureContainer.TEX_2D:
  60715. case KhronosTextureContainer.COMPRESSED_3D:
  60716. case KhronosTextureContainer.TEX_3D:
  60717. }
  60718. };
  60719. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  60720. // initialize width & height for level 1
  60721. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  60722. var width = this.pixelWidth;
  60723. var height = this.pixelHeight;
  60724. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  60725. for (var level = 0; level < mipmapCount; level++) {
  60726. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  60727. for (var face = 0; face < this.numberOfFaces; face++) {
  60728. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  60729. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  60730. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  60731. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  60732. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  60733. }
  60734. width = Math.max(1.0, width * 0.5);
  60735. height = Math.max(1.0, height * 0.5);
  60736. }
  60737. };
  60738. return KhronosTextureContainer;
  60739. }());
  60740. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  60741. // load types
  60742. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  60743. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  60744. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  60745. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  60746. Internals.KhronosTextureContainer = KhronosTextureContainer;
  60747. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60748. })(BABYLON || (BABYLON = {}));
  60749. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  60750. var BABYLON;
  60751. (function (BABYLON) {
  60752. var DynamicFloatArrayElementInfo = (function () {
  60753. function DynamicFloatArrayElementInfo() {
  60754. }
  60755. return DynamicFloatArrayElementInfo;
  60756. }());
  60757. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  60758. /**
  60759. * 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.
  60760. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  60761. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  60762. * 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.
  60763. * 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.
  60764. * 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".
  60765. */
  60766. var DynamicFloatArray = (function () {
  60767. /**
  60768. * Construct an instance of the dynamic float array
  60769. * @param stride size of one element in float (i.e. not bytes!)
  60770. * @param initialElementCount the number of available entries at construction
  60771. */
  60772. function DynamicFloatArray(stride, initialElementCount) {
  60773. this.compareValueOffset = null;
  60774. this.sortingAscending = true;
  60775. this._stride = stride;
  60776. this.buffer = new Float32Array(stride * initialElementCount);
  60777. this._lastUsed = 0;
  60778. this._firstFree = 0;
  60779. this._allEntries = new Array(initialElementCount);
  60780. this._freeEntries = new Array(initialElementCount);
  60781. for (var i = 0; i < initialElementCount; i++) {
  60782. var element = new DynamicFloatArrayElementInfo();
  60783. element.offset = i * stride;
  60784. this._allEntries[i] = element;
  60785. this._freeEntries[initialElementCount - i - 1] = element;
  60786. }
  60787. }
  60788. /**
  60789. * Allocate an element in the array.
  60790. * @return the element info instance that contains the offset into the main buffer of the element's location.
  60791. * Beware, this offset may change when you call pack()
  60792. */
  60793. DynamicFloatArray.prototype.allocElement = function () {
  60794. if (this._freeEntries.length === 0) {
  60795. this._growBuffer();
  60796. }
  60797. var el = this._freeEntries.pop();
  60798. this._lastUsed = Math.max(el.offset, this._lastUsed);
  60799. if (el.offset === this._firstFree) {
  60800. if (this._freeEntries.length > 0) {
  60801. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  60802. }
  60803. else {
  60804. this._firstFree += this._stride;
  60805. }
  60806. }
  60807. return el;
  60808. };
  60809. /**
  60810. * Free the element corresponding to the given element info
  60811. * @param elInfo the element that describe the allocated element
  60812. */
  60813. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  60814. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  60815. this._freeEntries.push(elInfo);
  60816. };
  60817. /**
  60818. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  60819. * 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().
  60820. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  60821. */
  60822. DynamicFloatArray.prototype.pack = function () {
  60823. // no free slot? no need to pack
  60824. if (this._freeEntries.length === 0) {
  60825. return this.buffer;
  60826. }
  60827. // If the buffer is already packed the last used will always be lower than the first free
  60828. // 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.
  60829. if (this._lastUsed < this._firstFree) {
  60830. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  60831. return elementsBuffer_1;
  60832. }
  60833. var s = this._stride;
  60834. // 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
  60835. var lastFree = new DynamicFloatArrayElementInfo();
  60836. lastFree.offset = this.totalElementCount * s;
  60837. this._freeEntries.push(lastFree);
  60838. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  60839. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  60840. var firstFreeSlotOffset = sortedFree[0].offset;
  60841. var freeZoneSize = 1;
  60842. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  60843. var prevOffset = sortedFree[0].offset;
  60844. for (var i = 1; i < sortedFree.length; i++) {
  60845. // 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
  60846. if (firstFreeSlotOffset >= occupiedZoneSize) {
  60847. break;
  60848. }
  60849. var curFree = sortedFree[i];
  60850. var curOffset = curFree.offset;
  60851. // Compute the distance between this offset and the previous
  60852. var distance = curOffset - prevOffset;
  60853. // If the distance is the stride size, they are adjacent, it good, move to the next
  60854. if (distance === s) {
  60855. // Free zone is one element bigger
  60856. ++freeZoneSize;
  60857. // as we're about to iterate to the next, the cur becomes the previous...
  60858. prevOffset = curOffset;
  60859. continue;
  60860. }
  60861. // Distance is bigger, which means there's x element between the previous free and this one
  60862. var usedRange = (distance / s) - 1;
  60863. // Two cases the free zone is smaller than the data to move or bigger
  60864. // Copy what can fit in the free zone
  60865. var curMoveOffset = curOffset - s;
  60866. var copyCount = Math.min(freeZoneSize, usedRange);
  60867. for (var j = 0; j < copyCount; j++) {
  60868. var freeI = firstFreeSlotOffset / s;
  60869. var curI = curMoveOffset / s;
  60870. var moveEl = sortedAll[curI];
  60871. this._moveElement(moveEl, firstFreeSlotOffset);
  60872. var replacedEl = sortedAll[freeI];
  60873. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  60874. replacedEl.offset = curMoveOffset;
  60875. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  60876. sortedAll[freeI] = moveEl;
  60877. sortedAll[curI] = replacedEl;
  60878. curMoveOffset -= s;
  60879. firstFreeSlotOffset += s;
  60880. }
  60881. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  60882. if (freeZoneSize <= usedRange) {
  60883. firstFreeSlotOffset = curMoveOffset + s;
  60884. freeZoneSize = 1 + copyCount;
  60885. }
  60886. else {
  60887. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  60888. }
  60889. // as we're about to iterate to the next, the cur becomes the previous...
  60890. prevOffset = curOffset;
  60891. }
  60892. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  60893. this._lastUsed = firstFreeSlotOffset - s;
  60894. this._firstFree = firstFreeSlotOffset;
  60895. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  60896. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  60897. this._allEntries = sortedAll;
  60898. return elementsBuffer;
  60899. };
  60900. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  60901. for (var i = 0; i < this._stride; i++) {
  60902. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  60903. }
  60904. element.offset = destOffset;
  60905. };
  60906. DynamicFloatArray.prototype._growBuffer = function () {
  60907. // Allocate the new buffer with 50% more entries, copy the content of the current one
  60908. var newElCount = Math.floor(this.totalElementCount * 1.5);
  60909. var newBuffer = new Float32Array(newElCount * this._stride);
  60910. newBuffer.set(this.buffer);
  60911. var curCount = this.totalElementCount;
  60912. var addedCount = newElCount - this.totalElementCount;
  60913. for (var i = 0; i < addedCount; i++) {
  60914. var element = new DynamicFloatArrayElementInfo();
  60915. element.offset = (curCount + i) * this.stride;
  60916. this._allEntries.push(element);
  60917. this._freeEntries[addedCount - i - 1] = element;
  60918. }
  60919. this._firstFree = curCount * this.stride;
  60920. this.buffer = newBuffer;
  60921. };
  60922. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  60923. /**
  60924. * Get the total count of entries that can fit in the current buffer
  60925. * @returns the elements count
  60926. */
  60927. get: function () {
  60928. return this._allEntries.length;
  60929. },
  60930. enumerable: true,
  60931. configurable: true
  60932. });
  60933. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  60934. /**
  60935. * Get the count of free entries that can still be allocated without resizing the buffer
  60936. * @returns the free elements count
  60937. */
  60938. get: function () {
  60939. return this._freeEntries.length;
  60940. },
  60941. enumerable: true,
  60942. configurable: true
  60943. });
  60944. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  60945. /**
  60946. * Get the count of allocated elements
  60947. * @returns the allocated elements count
  60948. */
  60949. get: function () {
  60950. return this._allEntries.length - this._freeEntries.length;
  60951. },
  60952. enumerable: true,
  60953. configurable: true
  60954. });
  60955. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  60956. /**
  60957. * Return the size of one element in float
  60958. * @returns the size in float
  60959. */
  60960. get: function () {
  60961. return this._stride;
  60962. },
  60963. enumerable: true,
  60964. configurable: true
  60965. });
  60966. DynamicFloatArray.prototype.sort = function () {
  60967. var _this = this;
  60968. if (!this.compareValueOffset) {
  60969. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  60970. }
  60971. var count = this.usedElementCount;
  60972. // Do we have to (re)create the sort table?
  60973. if (!this._sortTable || this._sortTable.length < count) {
  60974. // 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...
  60975. var newCount = Math.min(this.totalElementCount, count * 2);
  60976. this._sortTable = new Array(newCount);
  60977. }
  60978. if (!this._sortedTable || this._sortedTable.length !== count) {
  60979. this._sortedTable = new Array(count);
  60980. }
  60981. // Because, you know...
  60982. this.pack();
  60983. //let stride = this.stride;
  60984. //for (let i = 0; i < count; i++) {
  60985. // let si = this._sortTable[i];
  60986. // if (!si) {
  60987. // si = new SortInfo();
  60988. // this._sortTable[i] = si;
  60989. // }
  60990. // si.entry = this._allEntries[i];
  60991. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  60992. // si.swapedOffset = null;
  60993. // this._sortedTable[i] = si;
  60994. //}
  60995. var curOffset = 0;
  60996. var stride = this.stride;
  60997. for (var i = 0; i < count; i++, curOffset += stride) {
  60998. var si = this._sortTable[i];
  60999. if (!si) {
  61000. si = new SortInfo();
  61001. this._sortTable[i] = si;
  61002. }
  61003. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  61004. si.offset = curOffset;
  61005. si.swapedOffset = null;
  61006. this._sortedTable[i] = si;
  61007. }
  61008. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  61009. if (this.sortingAscending) {
  61010. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  61011. }
  61012. else {
  61013. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  61014. }
  61015. var swapElements = function (src, dst) {
  61016. for (var i = 0; i < stride; i++) {
  61017. var tps = _this.buffer[dst + i];
  61018. _this.buffer[dst + i] = _this.buffer[src + i];
  61019. _this.buffer[src + i] = tps;
  61020. }
  61021. };
  61022. // 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:
  61023. // 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),
  61024. // and I still want something with a good algorithm complexity.
  61025. // 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,
  61026. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  61027. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  61028. // 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
  61029. // until we find a SortInfo object without a swapedOffset which means we got the right location
  61030. // 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
  61031. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  61032. for (var i = 0; i < count; i++) {
  61033. // Get the element to move
  61034. var sourceSI = this._sortedTable[i];
  61035. var destSI = this._sortTable[i];
  61036. var sourceOff = sourceSI.offset;
  61037. // If the source changed location, find the new one
  61038. if (sourceSI.swapedOffset) {
  61039. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  61040. var curSI = sourceSI;
  61041. while (curSI.swapedOffset) {
  61042. curSI = this._sortTable[curSI.swapedOffset / stride];
  61043. }
  61044. // Finally get the right location
  61045. sourceOff = curSI.offset;
  61046. }
  61047. // Tag the element being replaced with its new location
  61048. destSI.swapedOffset = sourceOff;
  61049. // Swap elements (only if needed)
  61050. if (sourceOff !== destSI.offset) {
  61051. swapElements(sourceOff, destSI.offset);
  61052. }
  61053. // Update the offset in the corresponding DFAE
  61054. //sourceSI.entry.offset = destSI.entry.offset;
  61055. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  61056. }
  61057. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61058. return true;
  61059. };
  61060. return DynamicFloatArray;
  61061. }());
  61062. BABYLON.DynamicFloatArray = DynamicFloatArray;
  61063. var SortInfo = (function () {
  61064. function SortInfo() {
  61065. this.compareData = this.offset = this.swapedOffset = null;
  61066. }
  61067. return SortInfo;
  61068. }());
  61069. })(BABYLON || (BABYLON = {}));
  61070. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  61071. var BABYLON;
  61072. (function (BABYLON) {
  61073. var Debug;
  61074. (function (Debug) {
  61075. /**
  61076. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  61077. */
  61078. var SkeletonViewer = (function () {
  61079. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  61080. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  61081. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  61082. this.skeleton = skeleton;
  61083. this.mesh = mesh;
  61084. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  61085. this.renderingGroupId = renderingGroupId;
  61086. this.color = BABYLON.Color3.White();
  61087. this._debugLines = [];
  61088. this._isEnabled = false;
  61089. this._scene = scene;
  61090. this.update();
  61091. this._renderFunction = this.update.bind(this);
  61092. }
  61093. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  61094. get: function () {
  61095. return this._isEnabled;
  61096. },
  61097. set: function (value) {
  61098. if (this._isEnabled === value) {
  61099. return;
  61100. }
  61101. this._isEnabled = value;
  61102. if (value) {
  61103. this._scene.registerBeforeRender(this._renderFunction);
  61104. }
  61105. else {
  61106. this._scene.unregisterBeforeRender(this._renderFunction);
  61107. }
  61108. },
  61109. enumerable: true,
  61110. configurable: true
  61111. });
  61112. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  61113. if (x === void 0) { x = 0; }
  61114. if (y === void 0) { y = 0; }
  61115. if (z === void 0) { z = 0; }
  61116. var tmat = BABYLON.Tmp.Matrix[0];
  61117. var parentBone = bone.getParent();
  61118. tmat.copyFrom(bone.getLocalMatrix());
  61119. if (x !== 0 || y !== 0 || z !== 0) {
  61120. var tmat2 = BABYLON.Tmp.Matrix[1];
  61121. BABYLON.Matrix.IdentityToRef(tmat2);
  61122. tmat2.m[12] = x;
  61123. tmat2.m[13] = y;
  61124. tmat2.m[14] = z;
  61125. tmat2.multiplyToRef(tmat, tmat);
  61126. }
  61127. if (parentBone) {
  61128. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  61129. }
  61130. tmat.multiplyToRef(meshMat, tmat);
  61131. position.x = tmat.m[12];
  61132. position.y = tmat.m[13];
  61133. position.z = tmat.m[14];
  61134. };
  61135. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  61136. var len = bones.length;
  61137. var meshPos = this.mesh.position;
  61138. for (var i = 0; i < len; i++) {
  61139. var bone = bones[i];
  61140. var points = this._debugLines[i];
  61141. if (!points) {
  61142. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61143. this._debugLines[i] = points;
  61144. }
  61145. this._getBonePosition(points[0], bone, meshMat);
  61146. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  61147. points[0].subtractInPlace(meshPos);
  61148. points[1].subtractInPlace(meshPos);
  61149. }
  61150. };
  61151. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  61152. var len = bones.length;
  61153. var boneNum = 0;
  61154. var meshPos = this.mesh.position;
  61155. for (var i = len - 1; i >= 0; i--) {
  61156. var childBone = bones[i];
  61157. var parentBone = childBone.getParent();
  61158. if (!parentBone) {
  61159. continue;
  61160. }
  61161. var points = this._debugLines[boneNum];
  61162. if (!points) {
  61163. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61164. this._debugLines[boneNum] = points;
  61165. }
  61166. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  61167. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  61168. points[0].subtractInPlace(meshPos);
  61169. points[1].subtractInPlace(meshPos);
  61170. boneNum++;
  61171. }
  61172. };
  61173. SkeletonViewer.prototype.update = function () {
  61174. if (this.autoUpdateBonesMatrices) {
  61175. this.skeleton.computeAbsoluteTransforms();
  61176. }
  61177. if (this.skeleton.bones[0].length === undefined) {
  61178. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61179. }
  61180. else {
  61181. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61182. }
  61183. if (!this._debugMesh) {
  61184. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  61185. this._debugMesh.renderingGroupId = this.renderingGroupId;
  61186. }
  61187. else {
  61188. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  61189. }
  61190. this._debugMesh.position.copyFrom(this.mesh.position);
  61191. this._debugMesh.color = this.color;
  61192. };
  61193. SkeletonViewer.prototype.dispose = function () {
  61194. if (this._debugMesh) {
  61195. this.isEnabled = false;
  61196. this._debugMesh.dispose();
  61197. this._debugMesh = null;
  61198. }
  61199. };
  61200. return SkeletonViewer;
  61201. }());
  61202. Debug.SkeletonViewer = SkeletonViewer;
  61203. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61204. })(BABYLON || (BABYLON = {}));
  61205. //# sourceMappingURL=babylon.skeletonViewer.js.map
  61206. var BABYLON;
  61207. (function (BABYLON) {
  61208. var Debug;
  61209. (function (Debug) {
  61210. var AxesViewer = (function () {
  61211. function AxesViewer(scene, scaleLines) {
  61212. if (scaleLines === void 0) { scaleLines = 1; }
  61213. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61214. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61215. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61216. this.scaleLines = 1;
  61217. this.scaleLines = scaleLines;
  61218. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  61219. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  61220. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  61221. this._xmesh.renderingGroupId = 2;
  61222. this._ymesh.renderingGroupId = 2;
  61223. this._zmesh.renderingGroupId = 2;
  61224. this._xmesh.material.checkReadyOnlyOnce = true;
  61225. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  61226. this._ymesh.material.checkReadyOnlyOnce = true;
  61227. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  61228. this._zmesh.material.checkReadyOnlyOnce = true;
  61229. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  61230. this.scene = scene;
  61231. }
  61232. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  61233. var scaleLines = this.scaleLines;
  61234. this._xmesh.position.copyFrom(position);
  61235. this._ymesh.position.copyFrom(position);
  61236. this._zmesh.position.copyFrom(position);
  61237. var point2 = this._xline[1];
  61238. point2.x = xaxis.x * scaleLines;
  61239. point2.y = xaxis.y * scaleLines;
  61240. point2.z = xaxis.z * scaleLines;
  61241. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  61242. point2 = this._yline[1];
  61243. point2.x = yaxis.x * scaleLines;
  61244. point2.y = yaxis.y * scaleLines;
  61245. point2.z = yaxis.z * scaleLines;
  61246. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  61247. point2 = this._zline[1];
  61248. point2.x = zaxis.x * scaleLines;
  61249. point2.y = zaxis.y * scaleLines;
  61250. point2.z = zaxis.z * scaleLines;
  61251. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  61252. };
  61253. AxesViewer.prototype.dispose = function () {
  61254. if (this._xmesh) {
  61255. this._xmesh.dispose();
  61256. this._ymesh.dispose();
  61257. this._zmesh.dispose();
  61258. this._xmesh = null;
  61259. this._ymesh = null;
  61260. this._zmesh = null;
  61261. this._xline = null;
  61262. this._yline = null;
  61263. this._zline = null;
  61264. this.scene = null;
  61265. }
  61266. };
  61267. return AxesViewer;
  61268. }());
  61269. Debug.AxesViewer = AxesViewer;
  61270. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61271. })(BABYLON || (BABYLON = {}));
  61272. //# sourceMappingURL=babylon.axesViewer.js.map
  61273. var BABYLON;
  61274. (function (BABYLON) {
  61275. var Debug;
  61276. (function (Debug) {
  61277. var BoneAxesViewer = (function (_super) {
  61278. __extends(BoneAxesViewer, _super);
  61279. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  61280. if (scaleLines === void 0) { scaleLines = 1; }
  61281. var _this = _super.call(this, scene, scaleLines) || this;
  61282. _this.pos = BABYLON.Vector3.Zero();
  61283. _this.xaxis = BABYLON.Vector3.Zero();
  61284. _this.yaxis = BABYLON.Vector3.Zero();
  61285. _this.zaxis = BABYLON.Vector3.Zero();
  61286. _this.mesh = mesh;
  61287. _this.bone = bone;
  61288. return _this;
  61289. }
  61290. BoneAxesViewer.prototype.update = function () {
  61291. var bone = this.bone;
  61292. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  61293. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  61294. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  61295. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  61296. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  61297. };
  61298. BoneAxesViewer.prototype.dispose = function () {
  61299. if (this.pos) {
  61300. this.pos = null;
  61301. this.xaxis = null;
  61302. this.yaxis = null;
  61303. this.zaxis = null;
  61304. this.mesh = null;
  61305. this.bone = null;
  61306. _super.prototype.dispose.call(this);
  61307. }
  61308. };
  61309. return BoneAxesViewer;
  61310. }(Debug.AxesViewer));
  61311. Debug.BoneAxesViewer = BoneAxesViewer;
  61312. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61313. })(BABYLON || (BABYLON = {}));
  61314. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  61315. var BABYLON;
  61316. (function (BABYLON) {
  61317. var RayHelper = (function () {
  61318. function RayHelper(ray) {
  61319. this.ray = ray;
  61320. }
  61321. RayHelper.CreateAndShow = function (ray, scene, color) {
  61322. var helper = new RayHelper(ray);
  61323. helper.show(scene, color);
  61324. return helper;
  61325. };
  61326. RayHelper.prototype.show = function (scene, color) {
  61327. if (!this._renderFunction) {
  61328. var ray = this.ray;
  61329. this._renderFunction = this._render.bind(this);
  61330. this._scene = scene;
  61331. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  61332. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  61333. this._scene.registerBeforeRender(this._renderFunction);
  61334. }
  61335. if (color) {
  61336. this._renderLine.color.copyFrom(color);
  61337. }
  61338. };
  61339. RayHelper.prototype.hide = function () {
  61340. if (this._renderFunction) {
  61341. this._scene.unregisterBeforeRender(this._renderFunction);
  61342. this._scene = null;
  61343. this._renderFunction = null;
  61344. this._renderLine.dispose();
  61345. this._renderLine = null;
  61346. this._renderPoints = null;
  61347. }
  61348. };
  61349. RayHelper.prototype._render = function () {
  61350. var ray = this.ray;
  61351. var point = this._renderPoints[1];
  61352. var len = Math.min(ray.length, 1000000);
  61353. point.copyFrom(ray.direction);
  61354. point.scaleInPlace(len);
  61355. point.addInPlace(ray.origin);
  61356. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  61357. };
  61358. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  61359. this._attachedToMesh = mesh;
  61360. var ray = this.ray;
  61361. if (!ray.direction) {
  61362. ray.direction = BABYLON.Vector3.Zero();
  61363. }
  61364. if (!ray.origin) {
  61365. ray.origin = BABYLON.Vector3.Zero();
  61366. }
  61367. if (length) {
  61368. ray.length = length;
  61369. }
  61370. if (!meshSpaceOrigin) {
  61371. meshSpaceOrigin = BABYLON.Vector3.Zero();
  61372. }
  61373. if (!meshSpaceDirection) {
  61374. // -1 so that this will work with Mesh.lookAt
  61375. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  61376. }
  61377. if (!this._meshSpaceDirection) {
  61378. this._meshSpaceDirection = meshSpaceDirection.clone();
  61379. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  61380. }
  61381. else {
  61382. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  61383. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  61384. }
  61385. if (!this._updateToMeshFunction) {
  61386. this._updateToMeshFunction = this._updateToMesh.bind(this);
  61387. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  61388. }
  61389. this._updateToMesh();
  61390. };
  61391. RayHelper.prototype.detachFromMesh = function () {
  61392. if (this._attachedToMesh) {
  61393. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  61394. this._attachedToMesh = null;
  61395. this._updateToMeshFunction = null;
  61396. }
  61397. };
  61398. RayHelper.prototype._updateToMesh = function () {
  61399. var ray = this.ray;
  61400. if (this._attachedToMesh._isDisposed) {
  61401. this.detachFromMesh();
  61402. return;
  61403. }
  61404. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61405. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61406. };
  61407. RayHelper.prototype.dispose = function () {
  61408. this.hide();
  61409. this.detachFromMesh();
  61410. this.ray = null;
  61411. };
  61412. return RayHelper;
  61413. }());
  61414. BABYLON.RayHelper = RayHelper;
  61415. })(BABYLON || (BABYLON = {}));
  61416. //# sourceMappingURL=babylon.rayHelper.js.map
  61417. var BABYLON;
  61418. (function (BABYLON) {
  61419. var DebugLayer = (function () {
  61420. function DebugLayer(scene) {
  61421. this._scene = scene;
  61422. }
  61423. /** Creates the inspector window. */
  61424. DebugLayer.prototype._createInspector = function (config) {
  61425. if (config === void 0) { config = {}; }
  61426. var popup = config.popup || false;
  61427. var initialTab = config.initialTab || 0;
  61428. var parentElement = config.parentElement || null;
  61429. if (!this._inspector) {
  61430. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61431. } // else nothing to do,; instance is already existing
  61432. };
  61433. DebugLayer.prototype.isVisible = function () {
  61434. if (!this._inspector) {
  61435. return false;
  61436. }
  61437. return true;
  61438. };
  61439. DebugLayer.prototype.hide = function () {
  61440. if (this._inspector) {
  61441. try {
  61442. this._inspector.dispose();
  61443. }
  61444. catch (e) {
  61445. // If the inspector has been removed directly from the inspector tool
  61446. }
  61447. this._inspector = null;
  61448. }
  61449. };
  61450. DebugLayer.prototype.show = function (config) {
  61451. if (config === void 0) { config = {}; }
  61452. if (typeof INSPECTOR == 'undefined') {
  61453. // Load inspector and add it to the DOM
  61454. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  61455. }
  61456. else {
  61457. // Otherwise creates the inspector
  61458. this._createInspector(config);
  61459. }
  61460. };
  61461. return DebugLayer;
  61462. }());
  61463. // Get protocol used - http or https
  61464. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61465. BABYLON.DebugLayer = DebugLayer;
  61466. })(BABYLON || (BABYLON = {}));
  61467. //# sourceMappingURL=babylon.debugLayer.js.map
  61468. var BABYLON;
  61469. (function (BABYLON) {
  61470. var Debug;
  61471. (function (Debug) {
  61472. var PhysicsViewer = (function () {
  61473. function PhysicsViewer(scene) {
  61474. this._impostors = [];
  61475. this._meshes = [];
  61476. this._numMeshes = 0;
  61477. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61478. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  61479. }
  61480. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61481. var plugin = this._physicsEnginePlugin;
  61482. for (var i = 0; i < this._numMeshes; i++) {
  61483. if (this._impostors[i].isDisposed) {
  61484. this.hideImpostor(this._impostors[i--]);
  61485. }
  61486. else {
  61487. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  61488. }
  61489. }
  61490. };
  61491. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61492. for (var i = 0; i < this._numMeshes; i++) {
  61493. if (this._impostors[i] == impostor) {
  61494. return;
  61495. }
  61496. }
  61497. var debugMesh = this._physicsEnginePlugin.getDebugMesh(impostor, this._scene);
  61498. if (debugMesh) {
  61499. this._impostors[this._numMeshes] = impostor;
  61500. this._meshes[this._numMeshes] = debugMesh;
  61501. if (this._numMeshes === 0) {
  61502. this._renderFunction = this._updateDebugMeshes.bind(this);
  61503. this._scene.registerBeforeRender(this._renderFunction);
  61504. }
  61505. this._numMeshes++;
  61506. }
  61507. };
  61508. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61509. var removed = false;
  61510. for (var i = 0; i < this._numMeshes; i++) {
  61511. if (this._impostors[i] == impostor) {
  61512. this._scene.removeMesh(this._meshes[i]);
  61513. this._meshes[i].dispose();
  61514. this._numMeshes--;
  61515. if (this._numMeshes > 0) {
  61516. this._meshes[i] = this._meshes[this._numMeshes];
  61517. this._impostors[i] = this._impostors[this._numMeshes];
  61518. this._meshes[this._numMeshes] = null;
  61519. this._impostors[this._numMeshes] = null;
  61520. }
  61521. else {
  61522. this._meshes[0] = null;
  61523. this._impostors[0] = null;
  61524. }
  61525. removed = true;
  61526. break;
  61527. }
  61528. }
  61529. if (removed && this._numMeshes === 0) {
  61530. this._scene.unregisterBeforeRender(this._renderFunction);
  61531. }
  61532. };
  61533. PhysicsViewer.prototype.dispose = function () {
  61534. for (var i = 0; i < this._numMeshes; i++) {
  61535. this.hideImpostor(this._impostors[i]);
  61536. }
  61537. this._impostors.length = 0;
  61538. this._scene = null;
  61539. this._physicsEnginePlugin = null;
  61540. };
  61541. return PhysicsViewer;
  61542. }());
  61543. Debug.PhysicsViewer = PhysicsViewer;
  61544. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61545. })(BABYLON || (BABYLON = {}));
  61546. //# sourceMappingURL=babylon.physicsViewer.js.map
  61547. var BABYLON;
  61548. (function (BABYLON) {
  61549. var BoundingBoxRenderer = (function () {
  61550. function BoundingBoxRenderer(scene) {
  61551. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61552. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61553. this.showBackLines = true;
  61554. this.renderList = new BABYLON.SmartArray(32);
  61555. this._vertexBuffers = {};
  61556. this._scene = scene;
  61557. }
  61558. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61559. if (this._colorShader) {
  61560. return;
  61561. }
  61562. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  61563. attributes: [BABYLON.VertexBuffer.PositionKind],
  61564. uniforms: ["world", "viewProjection", "color"]
  61565. });
  61566. var engine = this._scene.getEngine();
  61567. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  61568. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61569. 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]);
  61570. };
  61571. BoundingBoxRenderer.prototype.reset = function () {
  61572. this.renderList.reset();
  61573. };
  61574. BoundingBoxRenderer.prototype.render = function () {
  61575. if (this.renderList.length === 0) {
  61576. return;
  61577. }
  61578. this._prepareRessources();
  61579. if (!this._colorShader.isReady()) {
  61580. return;
  61581. }
  61582. var engine = this._scene.getEngine();
  61583. engine.setDepthWrite(false);
  61584. this._colorShader._preBind();
  61585. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61586. var boundingBox = this.renderList.data[boundingBoxIndex];
  61587. var min = boundingBox.minimum;
  61588. var max = boundingBox.maximum;
  61589. var diff = max.subtract(min);
  61590. var median = min.add(diff.scale(0.5));
  61591. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61592. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61593. .multiply(boundingBox.getWorldMatrix());
  61594. // VBOs
  61595. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61596. if (this.showBackLines) {
  61597. // Back
  61598. engine.setDepthFunctionToGreaterOrEqual();
  61599. this._scene.resetCachedMaterial();
  61600. this._colorShader.setColor4("color", this.backColor.toColor4());
  61601. this._colorShader.bind(worldMatrix);
  61602. // Draw order
  61603. engine.draw(false, 0, 24);
  61604. }
  61605. // Front
  61606. engine.setDepthFunctionToLess();
  61607. this._scene.resetCachedMaterial();
  61608. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61609. this._colorShader.bind(worldMatrix);
  61610. // Draw order
  61611. engine.draw(false, 0, 24);
  61612. }
  61613. this._colorShader.unbind();
  61614. engine.setDepthFunctionToLessOrEqual();
  61615. engine.setDepthWrite(true);
  61616. };
  61617. BoundingBoxRenderer.prototype.dispose = function () {
  61618. if (!this._colorShader) {
  61619. return;
  61620. }
  61621. this.renderList.dispose();
  61622. this._colorShader.dispose();
  61623. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61624. if (buffer) {
  61625. buffer.dispose();
  61626. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61627. }
  61628. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61629. };
  61630. return BoundingBoxRenderer;
  61631. }());
  61632. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61633. })(BABYLON || (BABYLON = {}));
  61634. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61635. var BABYLON;
  61636. (function (BABYLON) {
  61637. var MorphTarget = (function () {
  61638. function MorphTarget(name, influence) {
  61639. if (influence === void 0) { influence = 0; }
  61640. this.name = name;
  61641. this.animations = new Array();
  61642. this.onInfluenceChanged = new BABYLON.Observable();
  61643. this.influence = influence;
  61644. }
  61645. Object.defineProperty(MorphTarget.prototype, "influence", {
  61646. get: function () {
  61647. return this._influence;
  61648. },
  61649. set: function (influence) {
  61650. if (this._influence === influence) {
  61651. return;
  61652. }
  61653. var previous = this._influence;
  61654. this._influence = influence;
  61655. if (this.onInfluenceChanged.hasObservers) {
  61656. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  61657. }
  61658. },
  61659. enumerable: true,
  61660. configurable: true
  61661. });
  61662. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  61663. get: function () {
  61664. return this._normals !== undefined;
  61665. },
  61666. enumerable: true,
  61667. configurable: true
  61668. });
  61669. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  61670. get: function () {
  61671. return this._tangents !== undefined;
  61672. },
  61673. enumerable: true,
  61674. configurable: true
  61675. });
  61676. MorphTarget.prototype.setPositions = function (data) {
  61677. this._positions = new Float32Array(data);
  61678. };
  61679. MorphTarget.prototype.getPositions = function () {
  61680. return this._positions;
  61681. };
  61682. MorphTarget.prototype.setNormals = function (data) {
  61683. this._normals = new Float32Array(data);
  61684. };
  61685. MorphTarget.prototype.getNormals = function () {
  61686. return this._normals;
  61687. };
  61688. MorphTarget.prototype.setTangents = function (data) {
  61689. this._tangents = new Float32Array(data);
  61690. };
  61691. MorphTarget.prototype.getTangents = function () {
  61692. return this._tangents;
  61693. };
  61694. /**
  61695. * Serializes the current target into a Serialization object.
  61696. * Returns the serialized object.
  61697. */
  61698. MorphTarget.prototype.serialize = function () {
  61699. var serializationObject = {};
  61700. serializationObject.name = this.name;
  61701. serializationObject.influence = this.influence;
  61702. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  61703. if (this.hasNormals) {
  61704. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  61705. }
  61706. if (this.hasTangents) {
  61707. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  61708. }
  61709. return serializationObject;
  61710. };
  61711. // Statics
  61712. MorphTarget.Parse = function (serializationObject) {
  61713. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  61714. result.setPositions(serializationObject.positions);
  61715. if (serializationObject.normals) {
  61716. result.setNormals(serializationObject.normals);
  61717. }
  61718. if (serializationObject.tangents) {
  61719. result.setTangents(serializationObject.tangents);
  61720. }
  61721. return result;
  61722. };
  61723. MorphTarget.FromMesh = function (mesh, name, influence) {
  61724. if (!name) {
  61725. name = mesh.name;
  61726. }
  61727. var result = new MorphTarget(name, influence);
  61728. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  61729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61730. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  61731. }
  61732. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  61733. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  61734. }
  61735. return result;
  61736. };
  61737. return MorphTarget;
  61738. }());
  61739. BABYLON.MorphTarget = MorphTarget;
  61740. })(BABYLON || (BABYLON = {}));
  61741. //# sourceMappingURL=babylon.morphTarget.js.map
  61742. var BABYLON;
  61743. (function (BABYLON) {
  61744. var MorphTargetManager = (function () {
  61745. function MorphTargetManager(scene) {
  61746. this._targets = new Array();
  61747. this._targetObservable = new Array();
  61748. this._activeTargets = new BABYLON.SmartArray(16);
  61749. this._supportsNormals = false;
  61750. this._supportsTangents = false;
  61751. this._vertexCount = 0;
  61752. this._uniqueId = 0;
  61753. if (!scene) {
  61754. scene = BABYLON.Engine.LastCreatedScene;
  61755. }
  61756. this._scene = scene;
  61757. this._scene.morphTargetManagers.push(this);
  61758. this._uniqueId = scene.getUniqueId();
  61759. }
  61760. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  61761. get: function () {
  61762. return this._uniqueId;
  61763. },
  61764. enumerable: true,
  61765. configurable: true
  61766. });
  61767. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  61768. get: function () {
  61769. return this._vertexCount;
  61770. },
  61771. enumerable: true,
  61772. configurable: true
  61773. });
  61774. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  61775. get: function () {
  61776. return this._supportsNormals;
  61777. },
  61778. enumerable: true,
  61779. configurable: true
  61780. });
  61781. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  61782. get: function () {
  61783. return this._supportsTangents;
  61784. },
  61785. enumerable: true,
  61786. configurable: true
  61787. });
  61788. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  61789. get: function () {
  61790. return this._targets.length;
  61791. },
  61792. enumerable: true,
  61793. configurable: true
  61794. });
  61795. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  61796. get: function () {
  61797. return this._activeTargets.length;
  61798. },
  61799. enumerable: true,
  61800. configurable: true
  61801. });
  61802. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  61803. get: function () {
  61804. return this._influences;
  61805. },
  61806. enumerable: true,
  61807. configurable: true
  61808. });
  61809. MorphTargetManager.prototype.getActiveTarget = function (index) {
  61810. return this._activeTargets.data[index];
  61811. };
  61812. MorphTargetManager.prototype.getTarget = function (index) {
  61813. return this._targets[index];
  61814. };
  61815. MorphTargetManager.prototype.addTarget = function (target) {
  61816. var _this = this;
  61817. if (this._vertexCount) {
  61818. if (this._vertexCount !== target.getPositions().length / 3) {
  61819. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  61820. return;
  61821. }
  61822. }
  61823. this._targets.push(target);
  61824. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  61825. _this._syncActiveTargets(needUpdate);
  61826. }));
  61827. this._syncActiveTargets(true);
  61828. };
  61829. MorphTargetManager.prototype.removeTarget = function (target) {
  61830. var index = this._targets.indexOf(target);
  61831. if (index >= 0) {
  61832. this._targets.splice(index, 1);
  61833. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  61834. this._vertexCount = 0;
  61835. this._syncActiveTargets(true);
  61836. }
  61837. };
  61838. /**
  61839. * Serializes the current manager into a Serialization object.
  61840. * Returns the serialized object.
  61841. */
  61842. MorphTargetManager.prototype.serialize = function () {
  61843. var serializationObject = {};
  61844. serializationObject.id = this.uniqueId;
  61845. serializationObject.targets = [];
  61846. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  61847. var target = _a[_i];
  61848. serializationObject.targets.push(target.serialize());
  61849. }
  61850. return serializationObject;
  61851. };
  61852. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  61853. this._syncActiveTargets(needUpdate);
  61854. };
  61855. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  61856. this._activeTargets.reset();
  61857. var tempInfluences = [];
  61858. this._supportsNormals = true;
  61859. this._supportsTangents = true;
  61860. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  61861. var target = _a[_i];
  61862. if (target.influence > 0) {
  61863. this._activeTargets.push(target);
  61864. tempInfluences.push(target.influence);
  61865. this._supportsNormals = this._supportsNormals && target.hasNormals;
  61866. this._supportsTangents = this._supportsTangents && target.hasTangents;
  61867. if (this._vertexCount === 0) {
  61868. this._vertexCount = target.getPositions().length / 3;
  61869. }
  61870. }
  61871. }
  61872. this._influences = new Float32Array(tempInfluences);
  61873. if (needUpdate) {
  61874. // Flag meshes as dirty to resync with the active targets
  61875. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  61876. var mesh = _c[_b];
  61877. if (mesh.morphTargetManager === this) {
  61878. mesh._syncGeometryWithMorphTargetManager();
  61879. }
  61880. }
  61881. }
  61882. };
  61883. // Statics
  61884. MorphTargetManager.Parse = function (serializationObject, scene) {
  61885. var result = new MorphTargetManager(scene);
  61886. result._uniqueId = serializationObject.id;
  61887. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  61888. var targetData = _a[_i];
  61889. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  61890. }
  61891. return result;
  61892. };
  61893. return MorphTargetManager;
  61894. }());
  61895. BABYLON.MorphTargetManager = MorphTargetManager;
  61896. })(BABYLON || (BABYLON = {}));
  61897. //# sourceMappingURL=babylon.morphTargetManager.js.map
  61898. var BABYLON;
  61899. (function (BABYLON) {
  61900. /**
  61901. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  61902. * It can help converting any input color in a desired output one. This can then be used to create effects
  61903. * from sepia, black and white to sixties or futuristic rendering...
  61904. *
  61905. * The only supported format is currently 3dl.
  61906. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  61907. */
  61908. var ColorGradingTexture = (function (_super) {
  61909. __extends(ColorGradingTexture, _super);
  61910. /**
  61911. * Instantiates a ColorGradingTexture from the following parameters.
  61912. *
  61913. * @param url The location of the color gradind data (currently only supporting 3dl)
  61914. * @param scene The scene the texture will be used in
  61915. */
  61916. function ColorGradingTexture(url, scene) {
  61917. var _this = _super.call(this, scene) || this;
  61918. if (!url) {
  61919. return _this;
  61920. }
  61921. _this._textureMatrix = BABYLON.Matrix.Identity();
  61922. _this.name = url;
  61923. _this.url = url;
  61924. _this.hasAlpha = false;
  61925. _this.isCube = false;
  61926. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61927. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61928. _this.anisotropicFilteringLevel = 1;
  61929. _this._texture = _this._getFromCache(url, true);
  61930. if (!_this._texture) {
  61931. if (!scene.useDelayedTextureLoading) {
  61932. _this.loadTexture();
  61933. }
  61934. else {
  61935. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61936. }
  61937. }
  61938. return _this;
  61939. }
  61940. /**
  61941. * Returns the texture matrix used in most of the material.
  61942. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  61943. */
  61944. ColorGradingTexture.prototype.getTextureMatrix = function () {
  61945. return this._textureMatrix;
  61946. };
  61947. /**
  61948. * Occurs when the file being loaded is a .3dl LUT file.
  61949. */
  61950. ColorGradingTexture.prototype.load3dlTexture = function () {
  61951. var _this = this;
  61952. var mipLevels = 0;
  61953. var floatArrayView = null;
  61954. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61955. this._texture = texture;
  61956. var callback = function (text) {
  61957. var data;
  61958. var tempData;
  61959. var line;
  61960. var lines = text.split('\n');
  61961. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  61962. var maxColor = 0;
  61963. for (var i = 0; i < lines.length; i++) {
  61964. line = lines[i];
  61965. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  61966. continue;
  61967. if (line.indexOf('#') === 0)
  61968. continue;
  61969. var words = line.split(" ");
  61970. if (size === 0) {
  61971. // Number of space + one
  61972. size = words.length;
  61973. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  61974. tempData = new Float32Array(size * size * size * 4);
  61975. continue;
  61976. }
  61977. if (size != 0) {
  61978. var r = Math.max(parseInt(words[0]), 0);
  61979. var g = Math.max(parseInt(words[1]), 0);
  61980. var b = Math.max(parseInt(words[2]), 0);
  61981. maxColor = Math.max(r, maxColor);
  61982. maxColor = Math.max(g, maxColor);
  61983. maxColor = Math.max(b, maxColor);
  61984. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  61985. tempData[pixelStorageIndex + 0] = r;
  61986. tempData[pixelStorageIndex + 1] = g;
  61987. tempData[pixelStorageIndex + 2] = b;
  61988. pixelIndexSlice++;
  61989. if (pixelIndexSlice % size == 0) {
  61990. pixelIndexH++;
  61991. pixelIndexSlice = 0;
  61992. if (pixelIndexH % size == 0) {
  61993. pixelIndexW++;
  61994. pixelIndexH = 0;
  61995. }
  61996. }
  61997. }
  61998. }
  61999. for (var i = 0; i < tempData.length; i++) {
  62000. if (i > 0 && (i + 1) % 4 === 0) {
  62001. data[i] = 255;
  62002. }
  62003. else {
  62004. var value = tempData[i];
  62005. data[i] = (value / maxColor * 255);
  62006. }
  62007. }
  62008. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  62009. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  62010. };
  62011. BABYLON.Tools.LoadFile(this.url, callback);
  62012. return this._texture;
  62013. };
  62014. /**
  62015. * Starts the loading process of the texture.
  62016. */
  62017. ColorGradingTexture.prototype.loadTexture = function () {
  62018. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  62019. this.load3dlTexture();
  62020. }
  62021. };
  62022. /**
  62023. * Clones the color gradind texture.
  62024. */
  62025. ColorGradingTexture.prototype.clone = function () {
  62026. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  62027. // Base texture
  62028. newTexture.level = this.level;
  62029. return newTexture;
  62030. };
  62031. /**
  62032. * Called during delayed load for textures.
  62033. */
  62034. ColorGradingTexture.prototype.delayLoad = function () {
  62035. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62036. return;
  62037. }
  62038. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62039. this._texture = this._getFromCache(this.url, true);
  62040. if (!this._texture) {
  62041. this.loadTexture();
  62042. }
  62043. };
  62044. /**
  62045. * Parses a color grading texture serialized by Babylon.
  62046. * @param parsedTexture The texture information being parsedTexture
  62047. * @param scene The scene to load the texture in
  62048. * @param rootUrl The root url of the data assets to load
  62049. * @return A color gradind texture
  62050. */
  62051. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62052. var texture = null;
  62053. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  62054. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  62055. texture.name = parsedTexture.name;
  62056. texture.level = parsedTexture.level;
  62057. }
  62058. return texture;
  62059. };
  62060. /**
  62061. * Serializes the LUT texture to json format.
  62062. */
  62063. ColorGradingTexture.prototype.serialize = function () {
  62064. if (!this.name) {
  62065. return null;
  62066. }
  62067. var serializationObject = {};
  62068. serializationObject.name = this.name;
  62069. serializationObject.level = this.level;
  62070. serializationObject.customType = "BABYLON.ColorGradingTexture";
  62071. return serializationObject;
  62072. };
  62073. return ColorGradingTexture;
  62074. }(BABYLON.BaseTexture));
  62075. /**
  62076. * Empty line regex stored for GC.
  62077. */
  62078. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  62079. BABYLON.ColorGradingTexture = ColorGradingTexture;
  62080. })(BABYLON || (BABYLON = {}));
  62081. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  62082. var BABYLON;
  62083. (function (BABYLON) {
  62084. /**
  62085. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  62086. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  62087. * 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;
  62088. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  62089. */
  62090. var ColorCurves = (function () {
  62091. function ColorCurves() {
  62092. this._dirty = true;
  62093. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  62094. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  62095. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  62096. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  62097. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  62098. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  62099. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  62100. this._globalHue = 30;
  62101. this._globalDensity = 0;
  62102. this._globalSaturation = 0;
  62103. this._globalExposure = 0;
  62104. this._highlightsHue = 30;
  62105. this._highlightsDensity = 0;
  62106. this._highlightsSaturation = 0;
  62107. this._highlightsExposure = 0;
  62108. this._midtonesHue = 30;
  62109. this._midtonesDensity = 0;
  62110. this._midtonesSaturation = 0;
  62111. this._midtonesExposure = 0;
  62112. this._shadowsHue = 30;
  62113. this._shadowsDensity = 0;
  62114. this._shadowsSaturation = 0;
  62115. this._shadowsExposure = 0;
  62116. }
  62117. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  62118. /**
  62119. * Gets the global Hue value.
  62120. * 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).
  62121. */
  62122. get: function () {
  62123. return this._globalHue;
  62124. },
  62125. /**
  62126. * Sets the global Hue value.
  62127. * 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).
  62128. */
  62129. set: function (value) {
  62130. this._globalHue = value;
  62131. this._dirty = true;
  62132. },
  62133. enumerable: true,
  62134. configurable: true
  62135. });
  62136. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  62137. /**
  62138. * Gets the global Density value.
  62139. * 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.
  62140. * Values less than zero provide a filter of opposite hue.
  62141. */
  62142. get: function () {
  62143. return this._globalDensity;
  62144. },
  62145. /**
  62146. * Sets the global Density value.
  62147. * 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.
  62148. * Values less than zero provide a filter of opposite hue.
  62149. */
  62150. set: function (value) {
  62151. this._globalDensity = value;
  62152. this._dirty = true;
  62153. },
  62154. enumerable: true,
  62155. configurable: true
  62156. });
  62157. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  62158. /**
  62159. * Gets the global Saturation value.
  62160. * 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.
  62161. */
  62162. get: function () {
  62163. return this._globalSaturation;
  62164. },
  62165. /**
  62166. * Sets the global Saturation value.
  62167. * 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.
  62168. */
  62169. set: function (value) {
  62170. this._globalSaturation = value;
  62171. this._dirty = true;
  62172. },
  62173. enumerable: true,
  62174. configurable: true
  62175. });
  62176. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  62177. /**
  62178. * Gets the highlights Hue value.
  62179. * 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).
  62180. */
  62181. get: function () {
  62182. return this._highlightsHue;
  62183. },
  62184. /**
  62185. * Sets the highlights Hue value.
  62186. * 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).
  62187. */
  62188. set: function (value) {
  62189. this._highlightsHue = value;
  62190. this._dirty = true;
  62191. },
  62192. enumerable: true,
  62193. configurable: true
  62194. });
  62195. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  62196. /**
  62197. * Gets the highlights Density value.
  62198. * 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.
  62199. * Values less than zero provide a filter of opposite hue.
  62200. */
  62201. get: function () {
  62202. return this._highlightsDensity;
  62203. },
  62204. /**
  62205. * Sets the highlights Density value.
  62206. * 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.
  62207. * Values less than zero provide a filter of opposite hue.
  62208. */
  62209. set: function (value) {
  62210. this._highlightsDensity = value;
  62211. this._dirty = true;
  62212. },
  62213. enumerable: true,
  62214. configurable: true
  62215. });
  62216. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  62217. /**
  62218. * Gets the highlights Saturation value.
  62219. * 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.
  62220. */
  62221. get: function () {
  62222. return this._highlightsSaturation;
  62223. },
  62224. /**
  62225. * Sets the highlights Saturation value.
  62226. * 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.
  62227. */
  62228. set: function (value) {
  62229. this._highlightsSaturation = value;
  62230. this._dirty = true;
  62231. },
  62232. enumerable: true,
  62233. configurable: true
  62234. });
  62235. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  62236. /**
  62237. * Gets the highlights Exposure value.
  62238. * 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.
  62239. */
  62240. get: function () {
  62241. return this._highlightsExposure;
  62242. },
  62243. /**
  62244. * Sets the highlights Exposure value.
  62245. * 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.
  62246. */
  62247. set: function (value) {
  62248. this._highlightsExposure = value;
  62249. this._dirty = true;
  62250. },
  62251. enumerable: true,
  62252. configurable: true
  62253. });
  62254. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  62255. /**
  62256. * Gets the midtones Hue value.
  62257. * 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).
  62258. */
  62259. get: function () {
  62260. return this._midtonesHue;
  62261. },
  62262. /**
  62263. * Sets the midtones Hue value.
  62264. * 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).
  62265. */
  62266. set: function (value) {
  62267. this._midtonesHue = value;
  62268. this._dirty = true;
  62269. },
  62270. enumerable: true,
  62271. configurable: true
  62272. });
  62273. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  62274. /**
  62275. * Gets the midtones Density value.
  62276. * 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.
  62277. * Values less than zero provide a filter of opposite hue.
  62278. */
  62279. get: function () {
  62280. return this._midtonesDensity;
  62281. },
  62282. /**
  62283. * Sets the midtones Density value.
  62284. * 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.
  62285. * Values less than zero provide a filter of opposite hue.
  62286. */
  62287. set: function (value) {
  62288. this._midtonesDensity = value;
  62289. this._dirty = true;
  62290. },
  62291. enumerable: true,
  62292. configurable: true
  62293. });
  62294. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  62295. /**
  62296. * Gets the midtones Saturation value.
  62297. * 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.
  62298. */
  62299. get: function () {
  62300. return this._midtonesSaturation;
  62301. },
  62302. /**
  62303. * Sets the midtones Saturation value.
  62304. * 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.
  62305. */
  62306. set: function (value) {
  62307. this._midtonesSaturation = value;
  62308. this._dirty = true;
  62309. },
  62310. enumerable: true,
  62311. configurable: true
  62312. });
  62313. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  62314. /**
  62315. * Gets the midtones Exposure value.
  62316. * 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.
  62317. */
  62318. get: function () {
  62319. return this._midtonesExposure;
  62320. },
  62321. /**
  62322. * Sets the midtones Exposure value.
  62323. * 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.
  62324. */
  62325. set: function (value) {
  62326. this._midtonesExposure = value;
  62327. this._dirty = true;
  62328. },
  62329. enumerable: true,
  62330. configurable: true
  62331. });
  62332. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  62333. /**
  62334. * Gets the shadows Hue value.
  62335. * 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).
  62336. */
  62337. get: function () {
  62338. return this._shadowsHue;
  62339. },
  62340. /**
  62341. * Sets the shadows Hue value.
  62342. * 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).
  62343. */
  62344. set: function (value) {
  62345. this._shadowsHue = value;
  62346. this._dirty = true;
  62347. },
  62348. enumerable: true,
  62349. configurable: true
  62350. });
  62351. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  62352. /**
  62353. * Gets the shadows Density value.
  62354. * 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.
  62355. * Values less than zero provide a filter of opposite hue.
  62356. */
  62357. get: function () {
  62358. return this._shadowsDensity;
  62359. },
  62360. /**
  62361. * Sets the shadows Density value.
  62362. * 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.
  62363. * Values less than zero provide a filter of opposite hue.
  62364. */
  62365. set: function (value) {
  62366. this._shadowsDensity = value;
  62367. this._dirty = true;
  62368. },
  62369. enumerable: true,
  62370. configurable: true
  62371. });
  62372. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  62373. /**
  62374. * Gets the shadows Saturation value.
  62375. * 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.
  62376. */
  62377. get: function () {
  62378. return this._shadowsSaturation;
  62379. },
  62380. /**
  62381. * Sets the shadows Saturation value.
  62382. * 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.
  62383. */
  62384. set: function (value) {
  62385. this._shadowsSaturation = value;
  62386. this._dirty = true;
  62387. },
  62388. enumerable: true,
  62389. configurable: true
  62390. });
  62391. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  62392. /**
  62393. * Gets the shadows Exposure value.
  62394. * 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.
  62395. */
  62396. get: function () {
  62397. return this._shadowsExposure;
  62398. },
  62399. /**
  62400. * Sets the shadows Exposure value.
  62401. * 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.
  62402. */
  62403. set: function (value) {
  62404. this._shadowsExposure = value;
  62405. this._dirty = true;
  62406. },
  62407. enumerable: true,
  62408. configurable: true
  62409. });
  62410. /**
  62411. * Binds the color curves to the shader.
  62412. * @param colorCurves The color curve to bind
  62413. * @param effect The effect to bind to
  62414. */
  62415. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  62416. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  62417. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  62418. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  62419. if (colorCurves._dirty) {
  62420. colorCurves._dirty = false;
  62421. // Fill in global info.
  62422. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  62423. // Compute highlights info.
  62424. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  62425. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  62426. // Compute midtones info.
  62427. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  62428. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  62429. // Compute shadows info.
  62430. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  62431. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  62432. // Compute deltas (neutral is midtones).
  62433. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  62434. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  62435. }
  62436. if (effect) {
  62437. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  62438. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  62439. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  62440. }
  62441. };
  62442. /**
  62443. * Prepare the list of uniforms associated with the ColorCurves effects.
  62444. * @param uniformsList The list of uniforms used in the effect
  62445. */
  62446. ColorCurves.PrepareUniforms = function (uniformsList) {
  62447. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  62448. };
  62449. /**
  62450. * Returns color grading data based on a hue, density, saturation and exposure value.
  62451. * @param filterHue The hue of the color filter.
  62452. * @param filterDensity The density of the color filter.
  62453. * @param saturation The saturation.
  62454. * @param exposure The exposure.
  62455. * @param result The result data container.
  62456. */
  62457. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  62458. if (hue == null) {
  62459. return;
  62460. }
  62461. hue = ColorCurves.clamp(hue, 0, 360);
  62462. density = ColorCurves.clamp(density, -100, 100);
  62463. saturation = ColorCurves.clamp(saturation, -100, 100);
  62464. exposure = ColorCurves.clamp(exposure, -100, 100);
  62465. // Remap the slider/config filter density with non-linear mapping and also scale by half
  62466. // so that the maximum filter density is only 50% control. This provides fine control
  62467. // for small values and reasonable range.
  62468. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  62469. density *= 0.5;
  62470. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  62471. if (density < 0) {
  62472. density *= -1;
  62473. hue = (hue + 180) % 360;
  62474. }
  62475. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  62476. result.scaleToRef(2, result);
  62477. result.a = 1 + 0.01 * saturation;
  62478. };
  62479. /**
  62480. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  62481. * @param value The input slider value in range [-100,100].
  62482. * @returns Adjusted value.
  62483. */
  62484. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  62485. value /= 100;
  62486. var x = Math.abs(value);
  62487. x = Math.pow(x, 2);
  62488. if (value < 0) {
  62489. x *= -1;
  62490. }
  62491. x *= 100;
  62492. return x;
  62493. };
  62494. /**
  62495. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  62496. * @param hue The hue (H) input.
  62497. * @param saturation The saturation (S) input.
  62498. * @param brightness The brightness (B) input.
  62499. * @result An RGBA color represented as Vector4.
  62500. */
  62501. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  62502. var h = ColorCurves.clamp(hue, 0, 360);
  62503. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  62504. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  62505. if (s === 0) {
  62506. result.r = v;
  62507. result.g = v;
  62508. result.b = v;
  62509. }
  62510. else {
  62511. // sector 0 to 5
  62512. h /= 60;
  62513. var i = Math.floor(h);
  62514. // fractional part of h
  62515. var f = h - i;
  62516. var p = v * (1 - s);
  62517. var q = v * (1 - s * f);
  62518. var t = v * (1 - s * (1 - f));
  62519. switch (i) {
  62520. case 0:
  62521. result.r = v;
  62522. result.g = t;
  62523. result.b = p;
  62524. break;
  62525. case 1:
  62526. result.r = q;
  62527. result.g = v;
  62528. result.b = p;
  62529. break;
  62530. case 2:
  62531. result.r = p;
  62532. result.g = v;
  62533. result.b = t;
  62534. break;
  62535. case 3:
  62536. result.r = p;
  62537. result.g = q;
  62538. result.b = v;
  62539. break;
  62540. case 4:
  62541. result.r = t;
  62542. result.g = p;
  62543. result.b = v;
  62544. break;
  62545. default:
  62546. result.r = v;
  62547. result.g = p;
  62548. result.b = q;
  62549. break;
  62550. }
  62551. }
  62552. result.a = 1;
  62553. };
  62554. /**
  62555. * Returns a value clamped between min and max
  62556. * @param value The value to clamp
  62557. * @param min The minimum of value
  62558. * @param max The maximum of value
  62559. * @returns The clamped value.
  62560. */
  62561. ColorCurves.clamp = function (value, min, max) {
  62562. return Math.min(Math.max(value, min), max);
  62563. };
  62564. /**
  62565. * Clones the current color curve instance.
  62566. * @return The cloned curves
  62567. */
  62568. ColorCurves.prototype.clone = function () {
  62569. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  62570. };
  62571. /**
  62572. * Serializes the current color curve instance to a json representation.
  62573. * @return a JSON representation
  62574. */
  62575. ColorCurves.prototype.serialize = function () {
  62576. return BABYLON.SerializationHelper.Serialize(this);
  62577. };
  62578. /**
  62579. * Parses the color curve from a json representation.
  62580. * @param source the JSON source to parse
  62581. * @return The parsed curves
  62582. */
  62583. ColorCurves.Parse = function (source) {
  62584. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  62585. };
  62586. return ColorCurves;
  62587. }());
  62588. __decorate([
  62589. BABYLON.serialize()
  62590. ], ColorCurves.prototype, "_globalHue", void 0);
  62591. __decorate([
  62592. BABYLON.serialize()
  62593. ], ColorCurves.prototype, "_globalDensity", void 0);
  62594. __decorate([
  62595. BABYLON.serialize()
  62596. ], ColorCurves.prototype, "_globalSaturation", void 0);
  62597. __decorate([
  62598. BABYLON.serialize()
  62599. ], ColorCurves.prototype, "_globalExposure", void 0);
  62600. __decorate([
  62601. BABYLON.serialize()
  62602. ], ColorCurves.prototype, "_highlightsHue", void 0);
  62603. __decorate([
  62604. BABYLON.serialize()
  62605. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  62606. __decorate([
  62607. BABYLON.serialize()
  62608. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  62609. __decorate([
  62610. BABYLON.serialize()
  62611. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  62612. __decorate([
  62613. BABYLON.serialize()
  62614. ], ColorCurves.prototype, "_midtonesHue", void 0);
  62615. __decorate([
  62616. BABYLON.serialize()
  62617. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  62618. __decorate([
  62619. BABYLON.serialize()
  62620. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  62621. __decorate([
  62622. BABYLON.serialize()
  62623. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  62624. BABYLON.ColorCurves = ColorCurves;
  62625. })(BABYLON || (BABYLON = {}));
  62626. //# sourceMappingURL=babylon.colorCurves.js.map
  62627. var BABYLON;
  62628. (function (BABYLON) {
  62629. var Octree = (function () {
  62630. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  62631. if (maxDepth === void 0) { maxDepth = 2; }
  62632. this.maxDepth = maxDepth;
  62633. this.dynamicContent = new Array();
  62634. this._maxBlockCapacity = maxBlockCapacity || 64;
  62635. this._selectionContent = new BABYLON.SmartArray(1024);
  62636. this._creationFunc = creationFunc;
  62637. }
  62638. // Methods
  62639. Octree.prototype.update = function (worldMin, worldMax, entries) {
  62640. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  62641. };
  62642. Octree.prototype.addMesh = function (entry) {
  62643. for (var index = 0; index < this.blocks.length; index++) {
  62644. var block = this.blocks[index];
  62645. block.addEntry(entry);
  62646. }
  62647. };
  62648. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  62649. this._selectionContent.reset();
  62650. for (var index = 0; index < this.blocks.length; index++) {
  62651. var block = this.blocks[index];
  62652. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  62653. }
  62654. if (allowDuplicate) {
  62655. this._selectionContent.concat(this.dynamicContent);
  62656. }
  62657. else {
  62658. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62659. }
  62660. return this._selectionContent;
  62661. };
  62662. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  62663. this._selectionContent.reset();
  62664. for (var index = 0; index < this.blocks.length; index++) {
  62665. var block = this.blocks[index];
  62666. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  62667. }
  62668. if (allowDuplicate) {
  62669. this._selectionContent.concat(this.dynamicContent);
  62670. }
  62671. else {
  62672. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62673. }
  62674. return this._selectionContent;
  62675. };
  62676. Octree.prototype.intersectsRay = function (ray) {
  62677. this._selectionContent.reset();
  62678. for (var index = 0; index < this.blocks.length; index++) {
  62679. var block = this.blocks[index];
  62680. block.intersectsRay(ray, this._selectionContent);
  62681. }
  62682. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62683. return this._selectionContent;
  62684. };
  62685. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  62686. target.blocks = new Array();
  62687. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  62688. // Segmenting space
  62689. for (var x = 0; x < 2; x++) {
  62690. for (var y = 0; y < 2; y++) {
  62691. for (var z = 0; z < 2; z++) {
  62692. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  62693. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  62694. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  62695. block.addEntries(entries);
  62696. target.blocks.push(block);
  62697. }
  62698. }
  62699. }
  62700. };
  62701. return Octree;
  62702. }());
  62703. Octree.CreationFuncForMeshes = function (entry, block) {
  62704. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  62705. block.entries.push(entry);
  62706. }
  62707. };
  62708. Octree.CreationFuncForSubMeshes = function (entry, block) {
  62709. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  62710. block.entries.push(entry);
  62711. }
  62712. };
  62713. BABYLON.Octree = Octree;
  62714. })(BABYLON || (BABYLON = {}));
  62715. //# sourceMappingURL=babylon.octree.js.map
  62716. var BABYLON;
  62717. (function (BABYLON) {
  62718. var OctreeBlock = (function () {
  62719. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  62720. this.entries = new Array();
  62721. this._boundingVectors = new Array();
  62722. this._capacity = capacity;
  62723. this._depth = depth;
  62724. this._maxDepth = maxDepth;
  62725. this._creationFunc = creationFunc;
  62726. this._minPoint = minPoint;
  62727. this._maxPoint = maxPoint;
  62728. this._boundingVectors.push(minPoint.clone());
  62729. this._boundingVectors.push(maxPoint.clone());
  62730. this._boundingVectors.push(minPoint.clone());
  62731. this._boundingVectors[2].x = maxPoint.x;
  62732. this._boundingVectors.push(minPoint.clone());
  62733. this._boundingVectors[3].y = maxPoint.y;
  62734. this._boundingVectors.push(minPoint.clone());
  62735. this._boundingVectors[4].z = maxPoint.z;
  62736. this._boundingVectors.push(maxPoint.clone());
  62737. this._boundingVectors[5].z = minPoint.z;
  62738. this._boundingVectors.push(maxPoint.clone());
  62739. this._boundingVectors[6].x = minPoint.x;
  62740. this._boundingVectors.push(maxPoint.clone());
  62741. this._boundingVectors[7].y = minPoint.y;
  62742. }
  62743. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  62744. // Property
  62745. get: function () {
  62746. return this._capacity;
  62747. },
  62748. enumerable: true,
  62749. configurable: true
  62750. });
  62751. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  62752. get: function () {
  62753. return this._minPoint;
  62754. },
  62755. enumerable: true,
  62756. configurable: true
  62757. });
  62758. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  62759. get: function () {
  62760. return this._maxPoint;
  62761. },
  62762. enumerable: true,
  62763. configurable: true
  62764. });
  62765. // Methods
  62766. OctreeBlock.prototype.addEntry = function (entry) {
  62767. if (this.blocks) {
  62768. for (var index = 0; index < this.blocks.length; index++) {
  62769. var block = this.blocks[index];
  62770. block.addEntry(entry);
  62771. }
  62772. return;
  62773. }
  62774. this._creationFunc(entry, this);
  62775. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  62776. this.createInnerBlocks();
  62777. }
  62778. };
  62779. OctreeBlock.prototype.addEntries = function (entries) {
  62780. for (var index = 0; index < entries.length; index++) {
  62781. var mesh = entries[index];
  62782. this.addEntry(mesh);
  62783. }
  62784. };
  62785. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  62786. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  62787. if (this.blocks) {
  62788. for (var index = 0; index < this.blocks.length; index++) {
  62789. var block = this.blocks[index];
  62790. block.select(frustumPlanes, selection, allowDuplicate);
  62791. }
  62792. return;
  62793. }
  62794. if (allowDuplicate) {
  62795. selection.concat(this.entries);
  62796. }
  62797. else {
  62798. selection.concatWithNoDuplicate(this.entries);
  62799. }
  62800. }
  62801. };
  62802. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  62803. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  62804. if (this.blocks) {
  62805. for (var index = 0; index < this.blocks.length; index++) {
  62806. var block = this.blocks[index];
  62807. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  62808. }
  62809. return;
  62810. }
  62811. if (allowDuplicate) {
  62812. selection.concat(this.entries);
  62813. }
  62814. else {
  62815. selection.concatWithNoDuplicate(this.entries);
  62816. }
  62817. }
  62818. };
  62819. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  62820. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  62821. if (this.blocks) {
  62822. for (var index = 0; index < this.blocks.length; index++) {
  62823. var block = this.blocks[index];
  62824. block.intersectsRay(ray, selection);
  62825. }
  62826. return;
  62827. }
  62828. selection.concatWithNoDuplicate(this.entries);
  62829. }
  62830. };
  62831. OctreeBlock.prototype.createInnerBlocks = function () {
  62832. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  62833. };
  62834. return OctreeBlock;
  62835. }());
  62836. BABYLON.OctreeBlock = OctreeBlock;
  62837. })(BABYLON || (BABYLON = {}));
  62838. //# sourceMappingURL=babylon.octreeBlock.js.map
  62839. var BABYLON;
  62840. (function (BABYLON) {
  62841. var SIMDVector3 = (function () {
  62842. function SIMDVector3() {
  62843. }
  62844. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  62845. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  62846. };
  62847. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  62848. var m = transformation.m;
  62849. var m0 = SIMD.Float32x4.load(m, 0);
  62850. var m1 = SIMD.Float32x4.load(m, 4);
  62851. var m2 = SIMD.Float32x4.load(m, 8);
  62852. var m3 = SIMD.Float32x4.load(m, 12);
  62853. 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));
  62854. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  62855. result.x = SIMD.Float32x4.extractLane(r, 0);
  62856. result.y = SIMD.Float32x4.extractLane(r, 1);
  62857. result.z = SIMD.Float32x4.extractLane(r, 2);
  62858. };
  62859. return SIMDVector3;
  62860. }());
  62861. var SIMDMatrix = (function () {
  62862. function SIMDMatrix() {
  62863. }
  62864. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  62865. var tm = this.m;
  62866. var om = other.m;
  62867. var m0 = SIMD.Float32x4.load(om, 0);
  62868. var m1 = SIMD.Float32x4.load(om, 4);
  62869. var m2 = SIMD.Float32x4.load(om, 8);
  62870. var m3 = SIMD.Float32x4.load(om, 12);
  62871. for (var i = 0; i < 16; i += 4) {
  62872. 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)))));
  62873. }
  62874. return this;
  62875. };
  62876. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  62877. var src = this.m;
  62878. var dest = other.m;
  62879. // Load the 4 rows
  62880. var src0 = SIMD.Float32x4.load(src, 0);
  62881. var src1 = SIMD.Float32x4.load(src, 4);
  62882. var src2 = SIMD.Float32x4.load(src, 8);
  62883. var src3 = SIMD.Float32x4.load(src, 12);
  62884. // Transpose the source matrix. Sort of. Not a true transpose operation
  62885. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  62886. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  62887. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  62888. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  62889. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  62890. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  62891. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  62892. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  62893. // This is a true transposition, but it will lead to an incorrect result
  62894. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  62895. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  62896. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  62897. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  62898. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  62899. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  62900. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  62901. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  62902. // ----
  62903. tmp1 = SIMD.Float32x4.mul(row2, row3);
  62904. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62905. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  62906. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  62907. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62908. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  62909. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  62910. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  62911. // ----
  62912. tmp1 = SIMD.Float32x4.mul(row1, row2);
  62913. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62914. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  62915. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  62916. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62917. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  62918. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  62919. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  62920. // ----
  62921. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  62922. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62923. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  62924. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  62925. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  62926. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62927. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  62928. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  62929. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  62930. // ----
  62931. tmp1 = SIMD.Float32x4.mul(row0, row1);
  62932. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62933. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  62934. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  62935. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62936. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  62937. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  62938. // ----
  62939. tmp1 = SIMD.Float32x4.mul(row0, row3);
  62940. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62941. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  62942. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  62943. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62944. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  62945. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  62946. // ----
  62947. tmp1 = SIMD.Float32x4.mul(row0, row2);
  62948. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62949. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  62950. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  62951. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62952. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  62953. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  62954. // Compute determinant
  62955. var det = SIMD.Float32x4.mul(row0, minor0);
  62956. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  62957. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  62958. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  62959. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  62960. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  62961. // These shuffles aren't necessary if the faulty transposition is done
  62962. // up at the top of this function.
  62963. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  62964. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  62965. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  62966. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  62967. // Compute final values by multiplying with 1/det
  62968. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  62969. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  62970. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  62971. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  62972. return this;
  62973. };
  62974. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  62975. var out = result.m;
  62976. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  62977. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  62978. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  62979. // cc.kmVec3Subtract(f, pCenter, pEye);
  62980. var f = SIMD.Float32x4.sub(center, eye);
  62981. // cc.kmVec3Normalize(f, f);
  62982. var tmp = SIMD.Float32x4.mul(f, f);
  62983. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62984. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62985. // cc.kmVec3Assign(up, pUp);
  62986. // cc.kmVec3Normalize(up, up);
  62987. tmp = SIMD.Float32x4.mul(up, up);
  62988. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62989. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62990. // cc.kmVec3Cross(s, f, up);
  62991. 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)));
  62992. // cc.kmVec3Normalize(s, s);
  62993. tmp = SIMD.Float32x4.mul(s, s);
  62994. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62995. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62996. // cc.kmVec3Cross(u, s, f);
  62997. 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)));
  62998. // cc.kmVec3Normalize(s, s);
  62999. tmp = SIMD.Float32x4.mul(s, s);
  63000. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63001. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63002. var zero = SIMD.Float32x4.splat(0.0);
  63003. s = SIMD.Float32x4.neg(s);
  63004. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  63005. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  63006. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  63007. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  63008. 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);
  63009. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  63010. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  63011. 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)))));
  63012. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  63013. 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)))));
  63014. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  63015. 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)))));
  63016. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  63017. 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)))));
  63018. };
  63019. return SIMDMatrix;
  63020. }());
  63021. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  63022. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  63023. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  63024. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  63025. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  63026. var SIMDHelper = (function () {
  63027. function SIMDHelper() {
  63028. }
  63029. Object.defineProperty(SIMDHelper, "IsEnabled", {
  63030. get: function () {
  63031. return SIMDHelper._isEnabled;
  63032. },
  63033. enumerable: true,
  63034. configurable: true
  63035. });
  63036. SIMDHelper.DisableSIMD = function () {
  63037. // Replace functions
  63038. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  63039. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  63040. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  63041. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  63042. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  63043. SIMDHelper._isEnabled = false;
  63044. };
  63045. SIMDHelper.EnableSIMD = function () {
  63046. if (self.SIMD === undefined) {
  63047. return;
  63048. }
  63049. // check if polyfills needed
  63050. if (!self.Math.fround) {
  63051. self.Math.fround = (function (array) { return function (x) {
  63052. return array[0] = x, array[0];
  63053. }; })(new Float32Array(1));
  63054. }
  63055. if (!self.Math.imul) {
  63056. self.Math.imul = function (a, b) {
  63057. var ah = (a >>> 16) & 0xffff;
  63058. var al = a & 0xffff;
  63059. var bh = (b >>> 16) & 0xffff;
  63060. var bl = b & 0xffff;
  63061. // the shift by 0 fixes the sign on the high part
  63062. // the final |0 converts the unsigned value into a signed value
  63063. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  63064. };
  63065. }
  63066. // Replace functions
  63067. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  63068. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  63069. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  63070. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  63071. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  63072. SIMDHelper._isEnabled = true;
  63073. };
  63074. return SIMDHelper;
  63075. }());
  63076. SIMDHelper._isEnabled = false;
  63077. BABYLON.SIMDHelper = SIMDHelper;
  63078. })(BABYLON || (BABYLON = {}));
  63079. //# sourceMappingURL=babylon.math.SIMD.js.map
  63080. var BABYLON;
  63081. (function (BABYLON) {
  63082. var VRDistortionCorrectionPostProcess = (function (_super) {
  63083. __extends(VRDistortionCorrectionPostProcess, _super);
  63084. //ANY
  63085. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  63086. var _this = _super.call(this, name, "vrDistortionCorrection", [
  63087. 'LensCenter',
  63088. 'Scale',
  63089. 'ScaleIn',
  63090. 'HmdWarpParam'
  63091. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  63092. _this._isRightEye = isRightEye;
  63093. _this._distortionFactors = vrMetrics.distortionK;
  63094. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  63095. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  63096. _this.onSizeChangedObservable.add(function () {
  63097. _this.aspectRatio = _this.width * .5 / _this.height;
  63098. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  63099. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  63100. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  63101. });
  63102. _this.onApplyObservable.add(function (effect) {
  63103. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  63104. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  63105. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  63106. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  63107. });
  63108. return _this;
  63109. }
  63110. return VRDistortionCorrectionPostProcess;
  63111. }(BABYLON.PostProcess));
  63112. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  63113. })(BABYLON || (BABYLON = {}));
  63114. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  63115. var BABYLON;
  63116. (function (BABYLON) {
  63117. var AnaglyphPostProcess = (function (_super) {
  63118. __extends(AnaglyphPostProcess, _super);
  63119. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  63120. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  63121. _this._passedProcess = rigCameras[0]._rigPostProcess;
  63122. _this.onApplyObservable.add(function (effect) {
  63123. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  63124. });
  63125. return _this;
  63126. }
  63127. return AnaglyphPostProcess;
  63128. }(BABYLON.PostProcess));
  63129. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  63130. })(BABYLON || (BABYLON = {}));
  63131. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  63132. var BABYLON;
  63133. (function (BABYLON) {
  63134. var StereoscopicInterlacePostProcess = (function (_super) {
  63135. __extends(StereoscopicInterlacePostProcess, _super);
  63136. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  63137. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  63138. _this._passedProcess = rigCameras[0]._rigPostProcess;
  63139. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  63140. _this.onSizeChangedObservable.add(function () {
  63141. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  63142. });
  63143. _this.onApplyObservable.add(function (effect) {
  63144. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  63145. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  63146. });
  63147. return _this;
  63148. }
  63149. return StereoscopicInterlacePostProcess;
  63150. }(BABYLON.PostProcess));
  63151. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  63152. })(BABYLON || (BABYLON = {}));
  63153. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  63154. var BABYLON;
  63155. (function (BABYLON) {
  63156. var FreeCameraDeviceOrientationInput = (function () {
  63157. function FreeCameraDeviceOrientationInput() {
  63158. var _this = this;
  63159. this._screenOrientationAngle = 0;
  63160. this._screenQuaternion = new BABYLON.Quaternion();
  63161. this._alpha = 0;
  63162. this._beta = 0;
  63163. this._gamma = 0;
  63164. this._orientationChanged = function () {
  63165. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  63166. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  63167. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  63168. };
  63169. this._deviceOrientation = function (evt) {
  63170. _this._alpha = evt.alpha;
  63171. _this._beta = evt.beta;
  63172. _this._gamma = evt.gamma;
  63173. };
  63174. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  63175. this._orientationChanged();
  63176. }
  63177. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  63178. get: function () {
  63179. return this._camera;
  63180. },
  63181. set: function (camera) {
  63182. this._camera = camera;
  63183. if (!this._camera.rotationQuaternion)
  63184. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  63185. },
  63186. enumerable: true,
  63187. configurable: true
  63188. });
  63189. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  63190. window.addEventListener("orientationchange", this._orientationChanged);
  63191. window.addEventListener("deviceorientation", this._deviceOrientation);
  63192. //In certain cases, the attach control is called AFTER orientation was changed,
  63193. //So this is needed.
  63194. this._orientationChanged();
  63195. };
  63196. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  63197. window.removeEventListener("orientationchange", this._orientationChanged);
  63198. window.removeEventListener("deviceorientation", this._deviceOrientation);
  63199. };
  63200. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  63201. //if no device orientation provided, don't update the rotation.
  63202. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  63203. if (!this._alpha)
  63204. return;
  63205. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  63206. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  63207. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  63208. //Mirror on XY Plane
  63209. this._camera.rotationQuaternion.z *= -1;
  63210. this._camera.rotationQuaternion.w *= -1;
  63211. };
  63212. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  63213. return "FreeCameraDeviceOrientationInput";
  63214. };
  63215. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  63216. return "deviceOrientation";
  63217. };
  63218. return FreeCameraDeviceOrientationInput;
  63219. }());
  63220. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  63221. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  63222. })(BABYLON || (BABYLON = {}));
  63223. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  63224. var BABYLON;
  63225. (function (BABYLON) {
  63226. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  63227. function ArcRotateCameraVRDeviceOrientationInput() {
  63228. this.alphaCorrection = 1;
  63229. this.betaCorrection = 1;
  63230. this.gammaCorrection = 1;
  63231. this._alpha = 0;
  63232. this._beta = 0;
  63233. this._gamma = 0;
  63234. this._dirty = false;
  63235. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  63236. }
  63237. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  63238. this.camera.attachControl(element, noPreventDefault);
  63239. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  63240. };
  63241. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  63242. var camera = this.camera;
  63243. this._alpha = +evt.alpha | 0;
  63244. this._beta = +evt.beta | 0;
  63245. this._gamma = +evt.gamma | 0;
  63246. this._dirty = true;
  63247. };
  63248. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  63249. if (this._dirty) {
  63250. this._dirty = false;
  63251. if (this._gamma < 0) {
  63252. this._gamma = 180 + this._gamma;
  63253. }
  63254. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  63255. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  63256. }
  63257. };
  63258. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  63259. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  63260. };
  63261. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  63262. return "ArcRotateCameraVRDeviceOrientationInput";
  63263. };
  63264. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  63265. return "VRDeviceOrientation";
  63266. };
  63267. return ArcRotateCameraVRDeviceOrientationInput;
  63268. }());
  63269. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  63270. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  63271. })(BABYLON || (BABYLON = {}));
  63272. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  63273. var BABYLON;
  63274. (function (BABYLON) {
  63275. var VRCameraMetrics = (function () {
  63276. function VRCameraMetrics() {
  63277. this.compensateDistortion = true;
  63278. }
  63279. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  63280. get: function () {
  63281. return this.hResolution / (2 * this.vResolution);
  63282. },
  63283. enumerable: true,
  63284. configurable: true
  63285. });
  63286. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  63287. get: function () {
  63288. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  63289. },
  63290. enumerable: true,
  63291. configurable: true
  63292. });
  63293. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  63294. get: function () {
  63295. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  63296. var h = (4 * meters) / this.hScreenSize;
  63297. return BABYLON.Matrix.Translation(h, 0, 0);
  63298. },
  63299. enumerable: true,
  63300. configurable: true
  63301. });
  63302. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  63303. get: function () {
  63304. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  63305. var h = (4 * meters) / this.hScreenSize;
  63306. return BABYLON.Matrix.Translation(-h, 0, 0);
  63307. },
  63308. enumerable: true,
  63309. configurable: true
  63310. });
  63311. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  63312. get: function () {
  63313. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  63314. },
  63315. enumerable: true,
  63316. configurable: true
  63317. });
  63318. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  63319. get: function () {
  63320. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  63321. },
  63322. enumerable: true,
  63323. configurable: true
  63324. });
  63325. VRCameraMetrics.GetDefault = function () {
  63326. var result = new VRCameraMetrics();
  63327. result.hResolution = 1280;
  63328. result.vResolution = 800;
  63329. result.hScreenSize = 0.149759993;
  63330. result.vScreenSize = 0.0935999975;
  63331. result.vScreenCenter = 0.0467999987;
  63332. result.eyeToScreenDistance = 0.0410000011;
  63333. result.lensSeparationDistance = 0.0635000020;
  63334. result.interpupillaryDistance = 0.0640000030;
  63335. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  63336. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  63337. result.postProcessScaleFactor = 1.714605507808412;
  63338. result.lensCenterOffset = 0.151976421;
  63339. return result;
  63340. };
  63341. return VRCameraMetrics;
  63342. }());
  63343. BABYLON.VRCameraMetrics = VRCameraMetrics;
  63344. })(BABYLON || (BABYLON = {}));
  63345. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  63346. var BABYLON;
  63347. (function (BABYLON) {
  63348. var WebVRFreeCamera = (function (_super) {
  63349. __extends(WebVRFreeCamera, _super);
  63350. function WebVRFreeCamera(name, position, scene, webVROptions) {
  63351. if (webVROptions === void 0) { webVROptions = {}; }
  63352. var _this = _super.call(this, name, position, scene) || this;
  63353. _this.webVROptions = webVROptions;
  63354. _this._vrDevice = null;
  63355. _this.rawPose = null;
  63356. _this._vrEnabled = false;
  63357. _this._specsVersion = 1.1;
  63358. _this._attached = false;
  63359. _this._positionOffset = BABYLON.Vector3.Zero();
  63360. _this._descendants = [];
  63361. _this.devicePosition = BABYLON.Vector3.Zero();
  63362. _this.deviceScaleFactor = 1;
  63363. _this.controllers = [];
  63364. _this.nonVRControllers = [];
  63365. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  63366. //legacy support - the compensation boolean was removed.
  63367. if (arguments.length === 5) {
  63368. _this.webVROptions = arguments[4];
  63369. }
  63370. // default webVR options
  63371. if (_this.webVROptions.trackPosition == undefined) {
  63372. _this.webVROptions.trackPosition = true;
  63373. }
  63374. if (_this.webVROptions.controllerMeshes == undefined) {
  63375. _this.webVROptions.controllerMeshes = true;
  63376. }
  63377. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  63378. _this.webVROptions.defaultLightningOnControllers = true;
  63379. }
  63380. _this.rotationQuaternion = new BABYLON.Quaternion();
  63381. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63382. if (_this.webVROptions && _this.webVROptions.positionScale) {
  63383. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  63384. }
  63385. //enable VR
  63386. _this.getEngine().initWebVR();
  63387. //check specs version
  63388. if (!window.VRFrameData) {
  63389. _this._specsVersion = 1.0;
  63390. _this._frameData = {};
  63391. }
  63392. else {
  63393. _this._frameData = new VRFrameData();
  63394. }
  63395. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  63396. if (!device) {
  63397. return;
  63398. }
  63399. _this._vrEnabled = true;
  63400. _this._vrDevice = device;
  63401. //reset the rig parameters.
  63402. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  63403. if (_this._attached) {
  63404. _this.getEngine().enableVR(_this._vrDevice);
  63405. }
  63406. });
  63407. // try to attach the controllers, if found.
  63408. _this.initControllers();
  63409. /**
  63410. * The idea behind the following lines:
  63411. * objects that have the camera as parent should actually have the rig cameras as a parent.
  63412. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  63413. * the second will not show it correctly.
  63414. *
  63415. * To solve this - each object that has the camera as parent will be added to a protected array.
  63416. * When the rig camera renders, it will take this array and set all of those to be its children.
  63417. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  63418. * Amazing!
  63419. */
  63420. scene.onBeforeCameraRenderObservable.add(function (camera) {
  63421. if (camera.parent === _this && _this.rigParenting) {
  63422. _this._descendants = _this.getDescendants(true, function (n) {
  63423. // don't take the cameras or the controllers!
  63424. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  63425. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  63426. return !isController && !isRigCamera;
  63427. });
  63428. _this._descendants.forEach(function (node) {
  63429. node.parent = camera;
  63430. });
  63431. }
  63432. });
  63433. scene.onAfterCameraRenderObservable.add(function (camera) {
  63434. if (camera.parent === _this && _this.rigParenting) {
  63435. _this._descendants.forEach(function (node) {
  63436. node.parent = _this;
  63437. });
  63438. }
  63439. });
  63440. return _this;
  63441. }
  63442. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  63443. set: function (callback) {
  63444. this._onControllersAttached = callback;
  63445. // after setting - if the controllers are already set, execute the callback.
  63446. if (this.controllers.length >= 2) {
  63447. callback(this.controllers);
  63448. }
  63449. },
  63450. enumerable: true,
  63451. configurable: true
  63452. });
  63453. Object.defineProperty(WebVRFreeCamera.prototype, "onNonVRControllerAttached", {
  63454. set: function (callback) {
  63455. this._onNonVRControllerAttached = callback;
  63456. this.nonVRControllers.forEach(function (controller) {
  63457. callback(controller);
  63458. });
  63459. },
  63460. enumerable: true,
  63461. configurable: true
  63462. });
  63463. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  63464. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  63465. var gp = _a[_i];
  63466. if (gp.hand === name) {
  63467. return gp;
  63468. }
  63469. }
  63470. return undefined;
  63471. };
  63472. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  63473. get: function () {
  63474. if (!this._leftController) {
  63475. this._leftController = this.getControllerByName("left");
  63476. }
  63477. return this._leftController;
  63478. },
  63479. enumerable: true,
  63480. configurable: true
  63481. });
  63482. ;
  63483. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  63484. get: function () {
  63485. if (!this._rightController) {
  63486. this._rightController = this.getControllerByName("right");
  63487. }
  63488. return this._rightController;
  63489. },
  63490. enumerable: true,
  63491. configurable: true
  63492. });
  63493. ;
  63494. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  63495. if (length === void 0) { length = 100; }
  63496. if (this.leftCamera) {
  63497. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  63498. }
  63499. else {
  63500. return _super.prototype.getForwardRay.call(this, length);
  63501. }
  63502. };
  63503. WebVRFreeCamera.prototype._checkInputs = function () {
  63504. if (this._vrEnabled) {
  63505. if (this._specsVersion === 1.1) {
  63506. this._vrDevice.getFrameData(this._frameData);
  63507. }
  63508. else {
  63509. //backwards comp
  63510. var pose = this._vrDevice.getPose();
  63511. this._frameData.pose = pose;
  63512. // calculate view and projection matrix
  63513. }
  63514. this.updateFromDevice(this._frameData.pose);
  63515. }
  63516. _super.prototype._checkInputs.call(this);
  63517. };
  63518. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  63519. if (poseData && poseData.orientation) {
  63520. this.rawPose = poseData;
  63521. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  63522. if (this.getScene().useRightHandedSystem) {
  63523. this.deviceRotationQuaternion.z *= -1;
  63524. this.deviceRotationQuaternion.w *= -1;
  63525. }
  63526. if (this.webVROptions.trackPosition && this.rawPose.position) {
  63527. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  63528. if (this.getScene().useRightHandedSystem) {
  63529. this.devicePosition.z *= -1;
  63530. }
  63531. }
  63532. }
  63533. };
  63534. /**
  63535. * WebVR's attach control will start broadcasting frames to the device.
  63536. * Note that in certain browsers (chrome for example) this function must be called
  63537. * within a user-interaction callback. Example:
  63538. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  63539. *
  63540. * @param {HTMLElement} element
  63541. * @param {boolean} [noPreventDefault]
  63542. *
  63543. * @memberOf WebVRFreeCamera
  63544. */
  63545. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  63546. _super.prototype.attachControl.call(this, element, noPreventDefault);
  63547. this._attached = true;
  63548. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  63549. if (this._vrEnabled) {
  63550. this.getEngine().enableVR(this._vrDevice);
  63551. }
  63552. };
  63553. WebVRFreeCamera.prototype.detachControl = function (element) {
  63554. _super.prototype.detachControl.call(this, element);
  63555. this._vrEnabled = false;
  63556. this._attached = false;
  63557. this.getEngine().disableVR();
  63558. };
  63559. WebVRFreeCamera.prototype.getClassName = function () {
  63560. return "WebVRFreeCamera";
  63561. };
  63562. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  63563. //uses the vrDisplay's "resetPose()".
  63564. //pitch and roll won't be affected.
  63565. this._vrDevice.resetPose();
  63566. };
  63567. WebVRFreeCamera.prototype._updateRigCameras = function () {
  63568. var camLeft = this._rigCameras[0];
  63569. var camRight = this._rigCameras[1];
  63570. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63571. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63572. camLeft.position.copyFrom(this.devicePosition);
  63573. camRight.position.copyFrom(this.devicePosition);
  63574. };
  63575. /**
  63576. * This function is called by the two RIG cameras.
  63577. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  63578. */
  63579. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  63580. var _this = this;
  63581. //WebVR 1.0
  63582. if (this._cameraRigParams["specs"] === 1.0) {
  63583. this._updateCameraRotationMatrix();
  63584. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  63585. // Computing target and final matrix
  63586. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  63587. if (this.getScene().useRightHandedSystem) {
  63588. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  63589. }
  63590. else {
  63591. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  63592. }
  63593. //now move the eye in the right direction
  63594. var eyeParams = this._cameraRigParams["eyeParameters"];
  63595. var offset = eyeParams.offset;
  63596. // it will actually always be 0, but just in case
  63597. if (this.getScene().useRightHandedSystem) {
  63598. offset[2] *= -1;
  63599. }
  63600. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  63601. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  63602. }
  63603. else {
  63604. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  63605. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  63606. if (!this.getScene().useRightHandedSystem) {
  63607. [2, 6, 8, 9, 14].forEach(function (num) {
  63608. _this._webvrViewMatrix.m[num] *= -1;
  63609. });
  63610. }
  63611. // update the camera rotation matrix
  63612. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  63613. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  63614. // Computing target and final matrix
  63615. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  63616. }
  63617. var parentCamera = this._cameraRigParams["parentCamera"];
  63618. // should the view matrix be updated with scale and position offset?
  63619. if (parentCamera.deviceScaleFactor !== 1) {
  63620. this._webvrViewMatrix.invert();
  63621. // scale the position, if set
  63622. if (parentCamera.deviceScaleFactor) {
  63623. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  63624. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  63625. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  63626. }
  63627. this._webvrViewMatrix.invert();
  63628. }
  63629. return this._webvrViewMatrix;
  63630. };
  63631. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  63632. var _this = this;
  63633. if (this._cameraRigParams["specs"] === 1.0) {
  63634. var eyeParams = this._cameraRigParams["eyeParameters"];
  63635. // deprecated!!
  63636. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  63637. }
  63638. else {
  63639. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  63640. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  63641. //babylon compatible matrix
  63642. if (!this.getScene().useRightHandedSystem) {
  63643. [8, 9, 10, 11].forEach(function (num) {
  63644. _this._projectionMatrix.m[num] *= -1;
  63645. });
  63646. }
  63647. }
  63648. return this._projectionMatrix;
  63649. };
  63650. WebVRFreeCamera.prototype.initControllers = function () {
  63651. var _this = this;
  63652. this.controllers = [];
  63653. new BABYLON.Gamepads(function (gp) {
  63654. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  63655. var webVrController = gp;
  63656. if (_this.webVROptions.controllerMeshes) {
  63657. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  63658. if (_this.webVROptions.defaultLightningOnControllers) {
  63659. if (!_this._lightOnControllers) {
  63660. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  63661. }
  63662. loadedMesh.getChildren().forEach(function (mesh) {
  63663. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  63664. });
  63665. }
  63666. });
  63667. }
  63668. webVrController.attachToPoseControlledCamera(_this);
  63669. // since this is async - sanity check. Is the controller already stored?
  63670. if (_this.controllers.indexOf(webVrController) === -1) {
  63671. //add to the controllers array
  63672. _this.controllers.push(webVrController);
  63673. //did we find enough controllers? Great! let the developer know.
  63674. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  63675. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  63676. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  63677. // So we're overriding setting left & right manually to be sure
  63678. var firstViveWandDetected = false;
  63679. for (var i = 0; i < _this.controllers.length; i++) {
  63680. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  63681. if (!firstViveWandDetected) {
  63682. firstViveWandDetected = true;
  63683. _this.controllers[i].hand = "left";
  63684. }
  63685. else {
  63686. _this.controllers[i].hand = "right";
  63687. }
  63688. }
  63689. }
  63690. _this._onControllersAttached(_this.controllers);
  63691. }
  63692. }
  63693. }
  63694. else {
  63695. _this.nonVRControllers.push(gp);
  63696. if (_this._onNonVRControllerAttached) {
  63697. _this._onNonVRControllerAttached(gp);
  63698. }
  63699. }
  63700. });
  63701. };
  63702. return WebVRFreeCamera;
  63703. }(BABYLON.FreeCamera));
  63704. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  63705. })(BABYLON || (BABYLON = {}));
  63706. //# sourceMappingURL=babylon.webVRCamera.js.map
  63707. /// <reference path="babylon.freeCamera.ts" />
  63708. var BABYLON;
  63709. (function (BABYLON) {
  63710. // We're mainly based on the logic defined into the FreeCamera code
  63711. var DeviceOrientationCamera = (function (_super) {
  63712. __extends(DeviceOrientationCamera, _super);
  63713. function DeviceOrientationCamera(name, position, scene) {
  63714. var _this = _super.call(this, name, position, scene) || this;
  63715. _this._quaternionCache = new BABYLON.Quaternion();
  63716. _this.inputs.addDeviceOrientation();
  63717. return _this;
  63718. }
  63719. DeviceOrientationCamera.prototype.getClassName = function () {
  63720. return "DeviceOrientationCamera";
  63721. };
  63722. DeviceOrientationCamera.prototype._checkInputs = function () {
  63723. _super.prototype._checkInputs.call(this);
  63724. this._quaternionCache.copyFrom(this.rotationQuaternion);
  63725. if (this._initialQuaternion) {
  63726. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  63727. }
  63728. };
  63729. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  63730. var _this = this;
  63731. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  63732. //can only work if this camera has a rotation quaternion already.
  63733. if (!this.rotationQuaternion)
  63734. return;
  63735. if (!this._initialQuaternion) {
  63736. this._initialQuaternion = new BABYLON.Quaternion();
  63737. }
  63738. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  63739. ['x', 'y', 'z'].forEach(function (axisName) {
  63740. if (!axis[axisName]) {
  63741. _this._initialQuaternion[axisName] = 0;
  63742. }
  63743. else {
  63744. _this._initialQuaternion[axisName] *= -1;
  63745. }
  63746. });
  63747. this._initialQuaternion.normalize();
  63748. //force rotation update
  63749. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  63750. };
  63751. return DeviceOrientationCamera;
  63752. }(BABYLON.FreeCamera));
  63753. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  63754. })(BABYLON || (BABYLON = {}));
  63755. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  63756. var BABYLON;
  63757. (function (BABYLON) {
  63758. var VRDeviceOrientationFreeCamera = (function (_super) {
  63759. __extends(VRDeviceOrientationFreeCamera, _super);
  63760. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  63761. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63762. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63763. var _this = _super.call(this, name, position, scene) || this;
  63764. vrCameraMetrics.compensateDistortion = compensateDistortion;
  63765. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  63766. return _this;
  63767. }
  63768. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  63769. return "VRDeviceOrientationFreeCamera";
  63770. };
  63771. return VRDeviceOrientationFreeCamera;
  63772. }(BABYLON.DeviceOrientationCamera));
  63773. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  63774. var VRDeviceOrientationGamepadCamera = (function (_super) {
  63775. __extends(VRDeviceOrientationGamepadCamera, _super);
  63776. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  63777. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63778. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63779. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  63780. _this.inputs.addGamepad();
  63781. return _this;
  63782. }
  63783. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  63784. return "VRDeviceOrientationGamepadCamera";
  63785. };
  63786. return VRDeviceOrientationGamepadCamera;
  63787. }(VRDeviceOrientationFreeCamera));
  63788. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  63789. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  63790. __extends(VRDeviceOrientationArcRotateCamera, _super);
  63791. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  63792. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63793. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63794. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63795. vrCameraMetrics.compensateDistortion = compensateDistortion;
  63796. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  63797. _this.inputs.addVRDeviceOrientation();
  63798. return _this;
  63799. }
  63800. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  63801. return "VRDeviceOrientationArcRotateCamera";
  63802. };
  63803. return VRDeviceOrientationArcRotateCamera;
  63804. }(BABYLON.ArcRotateCamera));
  63805. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  63806. })(BABYLON || (BABYLON = {}));
  63807. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  63808. /// <reference path="babylon.freeCamera.ts" />
  63809. /// <reference path="babylon.arcRotateCamera.ts" />
  63810. /// <reference path="babylon.gamepadCamera.ts" />
  63811. /// <reference path="babylon.universalCamera.ts" />
  63812. var BABYLON;
  63813. (function (BABYLON) {
  63814. var AnaglyphFreeCamera = (function (_super) {
  63815. __extends(AnaglyphFreeCamera, _super);
  63816. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  63817. var _this = _super.call(this, name, position, scene) || this;
  63818. _this.interaxialDistance = interaxialDistance;
  63819. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63820. return _this;
  63821. }
  63822. AnaglyphFreeCamera.prototype.getClassName = function () {
  63823. return "AnaglyphFreeCamera";
  63824. };
  63825. return AnaglyphFreeCamera;
  63826. }(BABYLON.FreeCamera));
  63827. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  63828. var AnaglyphArcRotateCamera = (function (_super) {
  63829. __extends(AnaglyphArcRotateCamera, _super);
  63830. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  63831. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63832. _this.interaxialDistance = interaxialDistance;
  63833. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63834. return _this;
  63835. }
  63836. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  63837. return "AnaglyphArcRotateCamera";
  63838. };
  63839. return AnaglyphArcRotateCamera;
  63840. }(BABYLON.ArcRotateCamera));
  63841. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  63842. var AnaglyphGamepadCamera = (function (_super) {
  63843. __extends(AnaglyphGamepadCamera, _super);
  63844. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  63845. var _this = _super.call(this, name, position, scene) || this;
  63846. _this.interaxialDistance = interaxialDistance;
  63847. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63848. return _this;
  63849. }
  63850. AnaglyphGamepadCamera.prototype.getClassName = function () {
  63851. return "AnaglyphGamepadCamera";
  63852. };
  63853. return AnaglyphGamepadCamera;
  63854. }(BABYLON.GamepadCamera));
  63855. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  63856. var AnaglyphUniversalCamera = (function (_super) {
  63857. __extends(AnaglyphUniversalCamera, _super);
  63858. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  63859. var _this = _super.call(this, name, position, scene) || this;
  63860. _this.interaxialDistance = interaxialDistance;
  63861. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63862. return _this;
  63863. }
  63864. AnaglyphUniversalCamera.prototype.getClassName = function () {
  63865. return "AnaglyphUniversalCamera";
  63866. };
  63867. return AnaglyphUniversalCamera;
  63868. }(BABYLON.UniversalCamera));
  63869. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  63870. var StereoscopicFreeCamera = (function (_super) {
  63871. __extends(StereoscopicFreeCamera, _super);
  63872. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63873. var _this = _super.call(this, name, position, scene) || this;
  63874. _this.interaxialDistance = interaxialDistance;
  63875. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63876. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63877. return _this;
  63878. }
  63879. StereoscopicFreeCamera.prototype.getClassName = function () {
  63880. return "StereoscopicFreeCamera";
  63881. };
  63882. return StereoscopicFreeCamera;
  63883. }(BABYLON.FreeCamera));
  63884. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  63885. var StereoscopicArcRotateCamera = (function (_super) {
  63886. __extends(StereoscopicArcRotateCamera, _super);
  63887. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  63888. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63889. _this.interaxialDistance = interaxialDistance;
  63890. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63891. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63892. return _this;
  63893. }
  63894. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  63895. return "StereoscopicArcRotateCamera";
  63896. };
  63897. return StereoscopicArcRotateCamera;
  63898. }(BABYLON.ArcRotateCamera));
  63899. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  63900. var StereoscopicGamepadCamera = (function (_super) {
  63901. __extends(StereoscopicGamepadCamera, _super);
  63902. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63903. var _this = _super.call(this, name, position, scene) || this;
  63904. _this.interaxialDistance = interaxialDistance;
  63905. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63906. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63907. return _this;
  63908. }
  63909. StereoscopicGamepadCamera.prototype.getClassName = function () {
  63910. return "StereoscopicGamepadCamera";
  63911. };
  63912. return StereoscopicGamepadCamera;
  63913. }(BABYLON.GamepadCamera));
  63914. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  63915. var StereoscopicUniversalCamera = (function (_super) {
  63916. __extends(StereoscopicUniversalCamera, _super);
  63917. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63918. var _this = _super.call(this, name, position, scene) || this;
  63919. _this.interaxialDistance = interaxialDistance;
  63920. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63921. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63922. return _this;
  63923. }
  63924. StereoscopicUniversalCamera.prototype.getClassName = function () {
  63925. return "StereoscopicUniversalCamera";
  63926. };
  63927. return StereoscopicUniversalCamera;
  63928. }(BABYLON.UniversalCamera));
  63929. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  63930. })(BABYLON || (BABYLON = {}));
  63931. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  63932. // Mainly based on these 2 articles :
  63933. // 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
  63934. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  63935. var BABYLON;
  63936. (function (BABYLON) {
  63937. var JoystickAxis;
  63938. (function (JoystickAxis) {
  63939. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  63940. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  63941. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  63942. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  63943. var VirtualJoystick = (function () {
  63944. function VirtualJoystick(leftJoystick) {
  63945. var _this = this;
  63946. if (leftJoystick) {
  63947. this._leftJoystick = true;
  63948. }
  63949. else {
  63950. this._leftJoystick = false;
  63951. }
  63952. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  63953. VirtualJoystick._globalJoystickIndex++;
  63954. // By default left & right arrow keys are moving the X
  63955. // and up & down keys are moving the Y
  63956. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  63957. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  63958. this.reverseLeftRight = false;
  63959. this.reverseUpDown = false;
  63960. // collections of pointers
  63961. this._touches = new BABYLON.StringDictionary();
  63962. this.deltaPosition = BABYLON.Vector3.Zero();
  63963. this._joystickSensibility = 25;
  63964. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  63965. this._rotationSpeed = 25;
  63966. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  63967. this._rotateOnAxisRelativeToMesh = false;
  63968. this._onResize = function (evt) {
  63969. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  63970. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  63971. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  63972. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  63973. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  63974. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  63975. };
  63976. // injecting a canvas element on top of the canvas 3D game
  63977. if (!VirtualJoystick.vjCanvas) {
  63978. window.addEventListener("resize", this._onResize, false);
  63979. VirtualJoystick.vjCanvas = document.createElement("canvas");
  63980. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  63981. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  63982. VirtualJoystick.vjCanvas.width = window.innerWidth;
  63983. VirtualJoystick.vjCanvas.height = window.innerHeight;
  63984. VirtualJoystick.vjCanvas.style.width = "100%";
  63985. VirtualJoystick.vjCanvas.style.height = "100%";
  63986. VirtualJoystick.vjCanvas.style.position = "absolute";
  63987. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  63988. VirtualJoystick.vjCanvas.style.top = "0px";
  63989. VirtualJoystick.vjCanvas.style.left = "0px";
  63990. VirtualJoystick.vjCanvas.style.zIndex = "5";
  63991. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  63992. // Support for jQuery PEP polyfill
  63993. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  63994. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  63995. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  63996. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  63997. document.body.appendChild(VirtualJoystick.vjCanvas);
  63998. }
  63999. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  64000. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  64001. this.pressed = false;
  64002. // default joystick color
  64003. this._joystickColor = "cyan";
  64004. this._joystickPointerID = -1;
  64005. // current joystick position
  64006. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  64007. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  64008. // origin joystick position
  64009. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  64010. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  64011. this._onPointerDownHandlerRef = function (evt) {
  64012. _this._onPointerDown(evt);
  64013. };
  64014. this._onPointerMoveHandlerRef = function (evt) {
  64015. _this._onPointerMove(evt);
  64016. };
  64017. this._onPointerOutHandlerRef = function (evt) {
  64018. _this._onPointerUp(evt);
  64019. };
  64020. this._onPointerUpHandlerRef = function (evt) {
  64021. _this._onPointerUp(evt);
  64022. };
  64023. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  64024. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  64025. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  64026. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  64027. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  64028. evt.preventDefault(); // Disables system menu
  64029. }, false);
  64030. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  64031. }
  64032. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  64033. this._joystickSensibility = newJoystickSensibility;
  64034. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  64035. };
  64036. VirtualJoystick.prototype._onPointerDown = function (e) {
  64037. var positionOnScreenCondition;
  64038. e.preventDefault();
  64039. if (this._leftJoystick === true) {
  64040. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  64041. }
  64042. else {
  64043. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  64044. }
  64045. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  64046. // First contact will be dedicated to the virtual joystick
  64047. this._joystickPointerID = e.pointerId;
  64048. this._joystickPointerStartPos.x = e.clientX;
  64049. this._joystickPointerStartPos.y = e.clientY;
  64050. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  64051. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  64052. this._deltaJoystickVector.x = 0;
  64053. this._deltaJoystickVector.y = 0;
  64054. this.pressed = true;
  64055. this._touches.add(e.pointerId.toString(), e);
  64056. }
  64057. else {
  64058. // You can only trigger the action buttons with a joystick declared
  64059. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  64060. this._action();
  64061. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  64062. }
  64063. }
  64064. };
  64065. VirtualJoystick.prototype._onPointerMove = function (e) {
  64066. // If the current pointer is the one associated to the joystick (first touch contact)
  64067. if (this._joystickPointerID == e.pointerId) {
  64068. this._joystickPointerPos.x = e.clientX;
  64069. this._joystickPointerPos.y = e.clientY;
  64070. this._deltaJoystickVector = this._joystickPointerPos.clone();
  64071. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  64072. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  64073. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  64074. switch (this._axisTargetedByLeftAndRight) {
  64075. case JoystickAxis.X:
  64076. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  64077. break;
  64078. case JoystickAxis.Y:
  64079. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  64080. break;
  64081. case JoystickAxis.Z:
  64082. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  64083. break;
  64084. }
  64085. var directionUpDown = this.reverseUpDown ? 1 : -1;
  64086. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  64087. switch (this._axisTargetedByUpAndDown) {
  64088. case JoystickAxis.X:
  64089. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  64090. break;
  64091. case JoystickAxis.Y:
  64092. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  64093. break;
  64094. case JoystickAxis.Z:
  64095. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  64096. break;
  64097. }
  64098. }
  64099. else {
  64100. var data = this._touches.get(e.pointerId.toString());
  64101. if (data) {
  64102. data.x = e.clientX;
  64103. data.y = e.clientY;
  64104. }
  64105. }
  64106. };
  64107. VirtualJoystick.prototype._onPointerUp = function (e) {
  64108. if (this._joystickPointerID == e.pointerId) {
  64109. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  64110. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  64111. this._joystickPointerID = -1;
  64112. this.pressed = false;
  64113. }
  64114. else {
  64115. var touch = this._touches.get(e.pointerId.toString());
  64116. if (touch) {
  64117. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  64118. }
  64119. }
  64120. this._deltaJoystickVector.x = 0;
  64121. this._deltaJoystickVector.y = 0;
  64122. this._touches.remove(e.pointerId.toString());
  64123. };
  64124. /**
  64125. * Change the color of the virtual joystick
  64126. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  64127. */
  64128. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  64129. this._joystickColor = newColor;
  64130. };
  64131. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  64132. this._action = action;
  64133. };
  64134. // Define which axis you'd like to control for left & right
  64135. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  64136. switch (axis) {
  64137. case JoystickAxis.X:
  64138. case JoystickAxis.Y:
  64139. case JoystickAxis.Z:
  64140. this._axisTargetedByLeftAndRight = axis;
  64141. break;
  64142. default:
  64143. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  64144. break;
  64145. }
  64146. };
  64147. // Define which axis you'd like to control for up & down
  64148. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  64149. switch (axis) {
  64150. case JoystickAxis.X:
  64151. case JoystickAxis.Y:
  64152. case JoystickAxis.Z:
  64153. this._axisTargetedByUpAndDown = axis;
  64154. break;
  64155. default:
  64156. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  64157. break;
  64158. }
  64159. };
  64160. VirtualJoystick.prototype._clearCanvas = function () {
  64161. if (this._leftJoystick) {
  64162. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  64163. }
  64164. else {
  64165. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  64166. }
  64167. };
  64168. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  64169. var _this = this;
  64170. if (this.pressed) {
  64171. this._touches.forEach(function (key, touch) {
  64172. if (touch.pointerId === _this._joystickPointerID) {
  64173. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  64174. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  64175. VirtualJoystick.vjCanvasContext.beginPath();
  64176. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  64177. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64178. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  64179. VirtualJoystick.vjCanvasContext.stroke();
  64180. VirtualJoystick.vjCanvasContext.closePath();
  64181. VirtualJoystick.vjCanvasContext.beginPath();
  64182. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64183. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  64184. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  64185. VirtualJoystick.vjCanvasContext.stroke();
  64186. VirtualJoystick.vjCanvasContext.closePath();
  64187. VirtualJoystick.vjCanvasContext.beginPath();
  64188. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64189. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  64190. VirtualJoystick.vjCanvasContext.stroke();
  64191. VirtualJoystick.vjCanvasContext.closePath();
  64192. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  64193. }
  64194. else {
  64195. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  64196. VirtualJoystick.vjCanvasContext.beginPath();
  64197. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  64198. VirtualJoystick.vjCanvasContext.beginPath();
  64199. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  64200. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  64201. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  64202. VirtualJoystick.vjCanvasContext.stroke();
  64203. VirtualJoystick.vjCanvasContext.closePath();
  64204. touch.prevX = touch.x;
  64205. touch.prevY = touch.y;
  64206. }
  64207. ;
  64208. });
  64209. }
  64210. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  64211. };
  64212. VirtualJoystick.prototype.releaseCanvas = function () {
  64213. if (VirtualJoystick.vjCanvas) {
  64214. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  64215. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  64216. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  64217. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  64218. window.removeEventListener("resize", this._onResize);
  64219. document.body.removeChild(VirtualJoystick.vjCanvas);
  64220. VirtualJoystick.vjCanvas = null;
  64221. }
  64222. };
  64223. return VirtualJoystick;
  64224. }());
  64225. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  64226. VirtualJoystick._globalJoystickIndex = 0;
  64227. BABYLON.VirtualJoystick = VirtualJoystick;
  64228. })(BABYLON || (BABYLON = {}));
  64229. //# sourceMappingURL=babylon.virtualJoystick.js.map
  64230. var BABYLON;
  64231. (function (BABYLON) {
  64232. // We're mainly based on the logic defined into the FreeCamera code
  64233. var VirtualJoysticksCamera = (function (_super) {
  64234. __extends(VirtualJoysticksCamera, _super);
  64235. function VirtualJoysticksCamera(name, position, scene) {
  64236. var _this = _super.call(this, name, position, scene) || this;
  64237. _this.inputs.addVirtualJoystick();
  64238. return _this;
  64239. }
  64240. VirtualJoysticksCamera.prototype.getClassName = function () {
  64241. return "VirtualJoysticksCamera";
  64242. };
  64243. return VirtualJoysticksCamera;
  64244. }(BABYLON.FreeCamera));
  64245. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  64246. })(BABYLON || (BABYLON = {}));
  64247. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  64248. var BABYLON;
  64249. (function (BABYLON) {
  64250. var FreeCameraVirtualJoystickInput = (function () {
  64251. function FreeCameraVirtualJoystickInput() {
  64252. }
  64253. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  64254. return this._leftjoystick;
  64255. };
  64256. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  64257. return this._rightjoystick;
  64258. };
  64259. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  64260. if (this._leftjoystick) {
  64261. var camera = this.camera;
  64262. var speed = camera._computeLocalCameraSpeed() * 50;
  64263. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  64264. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  64265. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  64266. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  64267. if (!this._leftjoystick.pressed) {
  64268. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  64269. }
  64270. if (!this._rightjoystick.pressed) {
  64271. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  64272. }
  64273. }
  64274. };
  64275. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  64276. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  64277. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  64278. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  64279. this._leftjoystick.setJoystickSensibility(0.15);
  64280. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  64281. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  64282. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  64283. this._rightjoystick.reverseUpDown = true;
  64284. this._rightjoystick.setJoystickSensibility(0.05);
  64285. this._rightjoystick.setJoystickColor("yellow");
  64286. };
  64287. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  64288. this._leftjoystick.releaseCanvas();
  64289. this._rightjoystick.releaseCanvas();
  64290. };
  64291. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  64292. return "FreeCameraVirtualJoystickInput";
  64293. };
  64294. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  64295. return "virtualJoystick";
  64296. };
  64297. return FreeCameraVirtualJoystickInput;
  64298. }());
  64299. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  64300. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  64301. })(BABYLON || (BABYLON = {}));
  64302. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  64303. var BABYLON;
  64304. (function (BABYLON) {
  64305. var SimplificationSettings = (function () {
  64306. function SimplificationSettings(quality, distance, optimizeMesh) {
  64307. this.quality = quality;
  64308. this.distance = distance;
  64309. this.optimizeMesh = optimizeMesh;
  64310. }
  64311. return SimplificationSettings;
  64312. }());
  64313. BABYLON.SimplificationSettings = SimplificationSettings;
  64314. var SimplificationQueue = (function () {
  64315. function SimplificationQueue() {
  64316. this.running = false;
  64317. this._simplificationArray = [];
  64318. }
  64319. SimplificationQueue.prototype.addTask = function (task) {
  64320. this._simplificationArray.push(task);
  64321. };
  64322. SimplificationQueue.prototype.executeNext = function () {
  64323. var task = this._simplificationArray.pop();
  64324. if (task) {
  64325. this.running = true;
  64326. this.runSimplification(task);
  64327. }
  64328. else {
  64329. this.running = false;
  64330. }
  64331. };
  64332. SimplificationQueue.prototype.runSimplification = function (task) {
  64333. var _this = this;
  64334. if (task.parallelProcessing) {
  64335. //parallel simplifier
  64336. task.settings.forEach(function (setting) {
  64337. var simplifier = _this.getSimplifier(task);
  64338. simplifier.simplify(setting, function (newMesh) {
  64339. task.mesh.addLODLevel(setting.distance, newMesh);
  64340. newMesh.isVisible = true;
  64341. //check if it is the last
  64342. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  64343. //all done, run the success callback.
  64344. task.successCallback();
  64345. }
  64346. _this.executeNext();
  64347. });
  64348. });
  64349. }
  64350. else {
  64351. //single simplifier.
  64352. var simplifier = this.getSimplifier(task);
  64353. var runDecimation = function (setting, callback) {
  64354. simplifier.simplify(setting, function (newMesh) {
  64355. task.mesh.addLODLevel(setting.distance, newMesh);
  64356. newMesh.isVisible = true;
  64357. //run the next quality level
  64358. callback();
  64359. });
  64360. };
  64361. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  64362. runDecimation(task.settings[loop.index], function () {
  64363. loop.executeNext();
  64364. });
  64365. }, function () {
  64366. //execution ended, run the success callback.
  64367. if (task.successCallback) {
  64368. task.successCallback();
  64369. }
  64370. _this.executeNext();
  64371. });
  64372. }
  64373. };
  64374. SimplificationQueue.prototype.getSimplifier = function (task) {
  64375. switch (task.simplificationType) {
  64376. case SimplificationType.QUADRATIC:
  64377. default:
  64378. return new QuadraticErrorSimplification(task.mesh);
  64379. }
  64380. };
  64381. return SimplificationQueue;
  64382. }());
  64383. BABYLON.SimplificationQueue = SimplificationQueue;
  64384. /**
  64385. * The implemented types of simplification.
  64386. * At the moment only Quadratic Error Decimation is implemented.
  64387. */
  64388. var SimplificationType;
  64389. (function (SimplificationType) {
  64390. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  64391. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  64392. var DecimationTriangle = (function () {
  64393. function DecimationTriangle(vertices) {
  64394. this.vertices = vertices;
  64395. this.error = new Array(4);
  64396. this.deleted = false;
  64397. this.isDirty = false;
  64398. this.deletePending = false;
  64399. this.borderFactor = 0;
  64400. }
  64401. return DecimationTriangle;
  64402. }());
  64403. BABYLON.DecimationTriangle = DecimationTriangle;
  64404. var DecimationVertex = (function () {
  64405. function DecimationVertex(position, id) {
  64406. this.position = position;
  64407. this.id = id;
  64408. this.isBorder = true;
  64409. this.q = new QuadraticMatrix();
  64410. this.triangleCount = 0;
  64411. this.triangleStart = 0;
  64412. this.originalOffsets = [];
  64413. }
  64414. DecimationVertex.prototype.updatePosition = function (newPosition) {
  64415. this.position.copyFrom(newPosition);
  64416. };
  64417. return DecimationVertex;
  64418. }());
  64419. BABYLON.DecimationVertex = DecimationVertex;
  64420. var QuadraticMatrix = (function () {
  64421. function QuadraticMatrix(data) {
  64422. this.data = new Array(10);
  64423. for (var i = 0; i < 10; ++i) {
  64424. if (data && data[i]) {
  64425. this.data[i] = data[i];
  64426. }
  64427. else {
  64428. this.data[i] = 0;
  64429. }
  64430. }
  64431. }
  64432. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  64433. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  64434. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  64435. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  64436. return det;
  64437. };
  64438. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  64439. for (var i = 0; i < 10; ++i) {
  64440. this.data[i] += matrix.data[i];
  64441. }
  64442. };
  64443. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  64444. for (var i = 0; i < 10; ++i) {
  64445. this.data[i] += data[i];
  64446. }
  64447. };
  64448. QuadraticMatrix.prototype.add = function (matrix) {
  64449. var m = new QuadraticMatrix();
  64450. for (var i = 0; i < 10; ++i) {
  64451. m.data[i] = this.data[i] + matrix.data[i];
  64452. }
  64453. return m;
  64454. };
  64455. QuadraticMatrix.FromData = function (a, b, c, d) {
  64456. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  64457. };
  64458. //returning an array to avoid garbage collection
  64459. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  64460. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  64461. };
  64462. return QuadraticMatrix;
  64463. }());
  64464. BABYLON.QuadraticMatrix = QuadraticMatrix;
  64465. var Reference = (function () {
  64466. function Reference(vertexId, triangleId) {
  64467. this.vertexId = vertexId;
  64468. this.triangleId = triangleId;
  64469. }
  64470. return Reference;
  64471. }());
  64472. BABYLON.Reference = Reference;
  64473. /**
  64474. * An implementation of the Quadratic Error simplification algorithm.
  64475. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  64476. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  64477. * @author RaananW
  64478. */
  64479. var QuadraticErrorSimplification = (function () {
  64480. function QuadraticErrorSimplification(_mesh) {
  64481. this._mesh = _mesh;
  64482. this.initialized = false;
  64483. this.syncIterations = 5000;
  64484. this.aggressiveness = 7;
  64485. this.decimationIterations = 100;
  64486. this.boundingBoxEpsilon = BABYLON.Epsilon;
  64487. }
  64488. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  64489. var _this = this;
  64490. this.initDecimatedMesh();
  64491. //iterating through the submeshes array, one after the other.
  64492. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  64493. _this.initWithMesh(loop.index, function () {
  64494. _this.runDecimation(settings, loop.index, function () {
  64495. loop.executeNext();
  64496. });
  64497. }, settings.optimizeMesh);
  64498. }, function () {
  64499. setTimeout(function () {
  64500. successCallback(_this._reconstructedMesh);
  64501. }, 0);
  64502. });
  64503. };
  64504. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  64505. var _this = this;
  64506. var gCount = 0;
  64507. triangle.vertices.forEach(function (vertex) {
  64508. var count = 0;
  64509. var vPos = vertex.position;
  64510. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  64511. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  64512. ++count;
  64513. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  64514. ++count;
  64515. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  64516. ++count;
  64517. if (count > 1) {
  64518. ++gCount;
  64519. }
  64520. ;
  64521. });
  64522. if (gCount > 1) {
  64523. console.log(triangle, gCount);
  64524. }
  64525. return gCount > 1;
  64526. };
  64527. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  64528. var _this = this;
  64529. var targetCount = ~~(this.triangles.length * settings.quality);
  64530. var deletedTriangles = 0;
  64531. var triangleCount = this.triangles.length;
  64532. var iterationFunction = function (iteration, callback) {
  64533. setTimeout(function () {
  64534. if (iteration % 5 === 0) {
  64535. _this.updateMesh(iteration === 0);
  64536. }
  64537. for (var i = 0; i < _this.triangles.length; ++i) {
  64538. _this.triangles[i].isDirty = false;
  64539. }
  64540. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  64541. var trianglesIterator = function (i) {
  64542. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  64543. var t = _this.triangles[tIdx];
  64544. if (!t)
  64545. return;
  64546. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  64547. return;
  64548. }
  64549. for (var j = 0; j < 3; ++j) {
  64550. if (t.error[j] < threshold) {
  64551. var deleted0 = [];
  64552. var deleted1 = [];
  64553. var v0 = t.vertices[j];
  64554. var v1 = t.vertices[(j + 1) % 3];
  64555. if (v0.isBorder || v1.isBorder)
  64556. continue;
  64557. var p = BABYLON.Vector3.Zero();
  64558. var n = BABYLON.Vector3.Zero();
  64559. var uv = BABYLON.Vector2.Zero();
  64560. var color = new BABYLON.Color4(0, 0, 0, 1);
  64561. _this.calculateError(v0, v1, p, n, uv, color);
  64562. var delTr = [];
  64563. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  64564. continue;
  64565. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  64566. continue;
  64567. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  64568. continue;
  64569. var uniqueArray = [];
  64570. delTr.forEach(function (deletedT) {
  64571. if (uniqueArray.indexOf(deletedT) === -1) {
  64572. deletedT.deletePending = true;
  64573. uniqueArray.push(deletedT);
  64574. }
  64575. });
  64576. if (uniqueArray.length % 2 !== 0) {
  64577. continue;
  64578. }
  64579. v0.q = v1.q.add(v0.q);
  64580. v0.updatePosition(p);
  64581. var tStart = _this.references.length;
  64582. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  64583. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  64584. var tCount = _this.references.length - tStart;
  64585. if (tCount <= v0.triangleCount) {
  64586. if (tCount) {
  64587. for (var c = 0; c < tCount; c++) {
  64588. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  64589. }
  64590. }
  64591. }
  64592. else {
  64593. v0.triangleStart = tStart;
  64594. }
  64595. v0.triangleCount = tCount;
  64596. break;
  64597. }
  64598. }
  64599. };
  64600. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  64601. }, 0);
  64602. };
  64603. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  64604. if (triangleCount - deletedTriangles <= targetCount)
  64605. loop.breakLoop();
  64606. else {
  64607. iterationFunction(loop.index, function () {
  64608. loop.executeNext();
  64609. });
  64610. }
  64611. }, function () {
  64612. setTimeout(function () {
  64613. //reconstruct this part of the mesh
  64614. _this.reconstructMesh(submeshIndex);
  64615. successCallback();
  64616. }, 0);
  64617. });
  64618. };
  64619. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  64620. var _this = this;
  64621. this.vertices = [];
  64622. this.triangles = [];
  64623. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64624. var indices = this._mesh.getIndices();
  64625. var submesh = this._mesh.subMeshes[submeshIndex];
  64626. var findInVertices = function (positionToSearch) {
  64627. if (optimizeMesh) {
  64628. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  64629. if (_this.vertices[ii].position.equals(positionToSearch)) {
  64630. return _this.vertices[ii];
  64631. }
  64632. }
  64633. }
  64634. return null;
  64635. };
  64636. var vertexReferences = [];
  64637. var vertexInit = function (i) {
  64638. var offset = i + submesh.verticesStart;
  64639. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  64640. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  64641. vertex.originalOffsets.push(offset);
  64642. if (vertex.id === _this.vertices.length) {
  64643. _this.vertices.push(vertex);
  64644. }
  64645. vertexReferences.push(vertex.id);
  64646. };
  64647. //var totalVertices = mesh.getTotalVertices();
  64648. var totalVertices = submesh.verticesCount;
  64649. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  64650. var indicesInit = function (i) {
  64651. var offset = (submesh.indexStart / 3) + i;
  64652. var pos = (offset * 3);
  64653. var i0 = indices[pos + 0];
  64654. var i1 = indices[pos + 1];
  64655. var i2 = indices[pos + 2];
  64656. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  64657. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  64658. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  64659. var triangle = new DecimationTriangle([v0, v1, v2]);
  64660. triangle.originalOffset = pos;
  64661. _this.triangles.push(triangle);
  64662. };
  64663. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  64664. _this.init(callback);
  64665. });
  64666. });
  64667. };
  64668. QuadraticErrorSimplification.prototype.init = function (callback) {
  64669. var _this = this;
  64670. var triangleInit1 = function (i) {
  64671. var t = _this.triangles[i];
  64672. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  64673. for (var j = 0; j < 3; j++) {
  64674. 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))));
  64675. }
  64676. };
  64677. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  64678. var triangleInit2 = function (i) {
  64679. var t = _this.triangles[i];
  64680. for (var j = 0; j < 3; ++j) {
  64681. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  64682. }
  64683. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  64684. };
  64685. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  64686. _this.initialized = true;
  64687. callback();
  64688. });
  64689. });
  64690. };
  64691. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  64692. var newTriangles = [];
  64693. var i;
  64694. for (i = 0; i < this.vertices.length; ++i) {
  64695. this.vertices[i].triangleCount = 0;
  64696. }
  64697. var t;
  64698. var j;
  64699. for (i = 0; i < this.triangles.length; ++i) {
  64700. if (!this.triangles[i].deleted) {
  64701. t = this.triangles[i];
  64702. for (j = 0; j < 3; ++j) {
  64703. t.vertices[j].triangleCount = 1;
  64704. }
  64705. newTriangles.push(t);
  64706. }
  64707. }
  64708. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  64709. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  64710. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  64711. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  64712. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64713. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64714. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64715. var vertexCount = 0;
  64716. for (i = 0; i < this.vertices.length; ++i) {
  64717. var vertex = this.vertices[i];
  64718. vertex.id = vertexCount;
  64719. if (vertex.triangleCount) {
  64720. vertex.originalOffsets.forEach(function (originalOffset) {
  64721. newPositionData.push(vertex.position.x);
  64722. newPositionData.push(vertex.position.y);
  64723. newPositionData.push(vertex.position.z);
  64724. newNormalData.push(normalData[originalOffset * 3]);
  64725. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  64726. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  64727. if (uvs && uvs.length) {
  64728. newUVsData.push(uvs[(originalOffset * 2)]);
  64729. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  64730. }
  64731. else if (colorsData && colorsData.length) {
  64732. newColorsData.push(colorsData[(originalOffset * 4)]);
  64733. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  64734. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  64735. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  64736. }
  64737. ++vertexCount;
  64738. });
  64739. }
  64740. }
  64741. var startingIndex = this._reconstructedMesh.getTotalIndices();
  64742. var startingVertex = this._reconstructedMesh.getTotalVertices();
  64743. var submeshesArray = this._reconstructedMesh.subMeshes;
  64744. this._reconstructedMesh.subMeshes = [];
  64745. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  64746. var originalIndices = this._mesh.getIndices();
  64747. for (i = 0; i < newTriangles.length; ++i) {
  64748. t = newTriangles[i]; //now get the new referencing point for each vertex
  64749. [0, 1, 2].forEach(function (idx) {
  64750. var id = originalIndices[t.originalOffset + idx];
  64751. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  64752. if (offset < 0)
  64753. offset = 0;
  64754. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  64755. });
  64756. }
  64757. //overwriting the old vertex buffers and indices.
  64758. this._reconstructedMesh.setIndices(newIndicesArray);
  64759. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  64760. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  64761. if (newUVsData.length > 0)
  64762. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  64763. if (newColorsData.length > 0)
  64764. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  64765. //create submesh
  64766. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  64767. if (submeshIndex > 0) {
  64768. this._reconstructedMesh.subMeshes = [];
  64769. submeshesArray.forEach(function (submesh) {
  64770. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  64771. });
  64772. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  64773. }
  64774. };
  64775. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  64776. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  64777. this._reconstructedMesh.material = this._mesh.material;
  64778. this._reconstructedMesh.parent = this._mesh.parent;
  64779. this._reconstructedMesh.isVisible = false;
  64780. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  64781. };
  64782. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  64783. for (var i = 0; i < vertex1.triangleCount; ++i) {
  64784. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  64785. if (t.deleted)
  64786. continue;
  64787. var s = this.references[vertex1.triangleStart + i].vertexId;
  64788. var v1 = t.vertices[(s + 1) % 3];
  64789. var v2 = t.vertices[(s + 2) % 3];
  64790. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  64791. deletedArray[i] = true;
  64792. delTr.push(t);
  64793. continue;
  64794. }
  64795. var d1 = v1.position.subtract(point);
  64796. d1 = d1.normalize();
  64797. var d2 = v2.position.subtract(point);
  64798. d2 = d2.normalize();
  64799. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  64800. return true;
  64801. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  64802. deletedArray[i] = false;
  64803. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  64804. return true;
  64805. }
  64806. return false;
  64807. };
  64808. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  64809. var newDeleted = deletedTriangles;
  64810. for (var i = 0; i < vertex.triangleCount; ++i) {
  64811. var ref = this.references[vertex.triangleStart + i];
  64812. var t = this.triangles[ref.triangleId];
  64813. if (t.deleted)
  64814. continue;
  64815. if (deletedArray[i] && t.deletePending) {
  64816. t.deleted = true;
  64817. newDeleted++;
  64818. continue;
  64819. }
  64820. t.vertices[ref.vertexId] = origVertex;
  64821. t.isDirty = true;
  64822. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  64823. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  64824. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  64825. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  64826. this.references.push(ref);
  64827. }
  64828. return newDeleted;
  64829. };
  64830. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  64831. for (var i = 0; i < this.vertices.length; ++i) {
  64832. var vCount = [];
  64833. var vId = [];
  64834. var v = this.vertices[i];
  64835. var j;
  64836. for (j = 0; j < v.triangleCount; ++j) {
  64837. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  64838. for (var ii = 0; ii < 3; ii++) {
  64839. var ofs = 0;
  64840. var vv = triangle.vertices[ii];
  64841. while (ofs < vCount.length) {
  64842. if (vId[ofs] === vv.id)
  64843. break;
  64844. ++ofs;
  64845. }
  64846. if (ofs === vCount.length) {
  64847. vCount.push(1);
  64848. vId.push(vv.id);
  64849. }
  64850. else {
  64851. vCount[ofs]++;
  64852. }
  64853. }
  64854. }
  64855. for (j = 0; j < vCount.length; ++j) {
  64856. if (vCount[j] === 1) {
  64857. this.vertices[vId[j]].isBorder = true;
  64858. }
  64859. else {
  64860. this.vertices[vId[j]].isBorder = false;
  64861. }
  64862. }
  64863. }
  64864. };
  64865. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  64866. if (identifyBorders === void 0) { identifyBorders = false; }
  64867. var i;
  64868. if (!identifyBorders) {
  64869. var newTrianglesVector = [];
  64870. for (i = 0; i < this.triangles.length; ++i) {
  64871. if (!this.triangles[i].deleted) {
  64872. newTrianglesVector.push(this.triangles[i]);
  64873. }
  64874. }
  64875. this.triangles = newTrianglesVector;
  64876. }
  64877. for (i = 0; i < this.vertices.length; ++i) {
  64878. this.vertices[i].triangleCount = 0;
  64879. this.vertices[i].triangleStart = 0;
  64880. }
  64881. var t;
  64882. var j;
  64883. var v;
  64884. for (i = 0; i < this.triangles.length; ++i) {
  64885. t = this.triangles[i];
  64886. for (j = 0; j < 3; ++j) {
  64887. v = t.vertices[j];
  64888. v.triangleCount++;
  64889. }
  64890. }
  64891. var tStart = 0;
  64892. for (i = 0; i < this.vertices.length; ++i) {
  64893. this.vertices[i].triangleStart = tStart;
  64894. tStart += this.vertices[i].triangleCount;
  64895. this.vertices[i].triangleCount = 0;
  64896. }
  64897. var newReferences = new Array(this.triangles.length * 3);
  64898. for (i = 0; i < this.triangles.length; ++i) {
  64899. t = this.triangles[i];
  64900. for (j = 0; j < 3; ++j) {
  64901. v = t.vertices[j];
  64902. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  64903. v.triangleCount++;
  64904. }
  64905. }
  64906. this.references = newReferences;
  64907. if (identifyBorders) {
  64908. this.identifyBorder();
  64909. }
  64910. };
  64911. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  64912. var x = point.x;
  64913. var y = point.y;
  64914. var z = point.z;
  64915. 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
  64916. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  64917. };
  64918. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  64919. var q = vertex1.q.add(vertex2.q);
  64920. var border = vertex1.isBorder && vertex2.isBorder;
  64921. var error = 0;
  64922. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  64923. if (qDet !== 0 && !border) {
  64924. if (!pointResult) {
  64925. pointResult = BABYLON.Vector3.Zero();
  64926. }
  64927. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  64928. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  64929. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  64930. error = this.vertexError(q, pointResult);
  64931. }
  64932. else {
  64933. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  64934. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  64935. var error1 = this.vertexError(q, vertex1.position);
  64936. var error2 = this.vertexError(q, vertex2.position);
  64937. var error3 = this.vertexError(q, p3);
  64938. error = Math.min(error1, error2, error3);
  64939. if (error === error1) {
  64940. if (pointResult) {
  64941. pointResult.copyFrom(vertex1.position);
  64942. }
  64943. }
  64944. else if (error === error2) {
  64945. if (pointResult) {
  64946. pointResult.copyFrom(vertex2.position);
  64947. }
  64948. }
  64949. else {
  64950. if (pointResult) {
  64951. pointResult.copyFrom(p3);
  64952. }
  64953. }
  64954. }
  64955. return error;
  64956. };
  64957. return QuadraticErrorSimplification;
  64958. }());
  64959. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  64960. })(BABYLON || (BABYLON = {}));
  64961. //# sourceMappingURL=babylon.meshSimplification.js.map
  64962. var BABYLON;
  64963. (function (BABYLON) {
  64964. var Internals;
  64965. (function (Internals) {
  64966. var MeshLODLevel = (function () {
  64967. function MeshLODLevel(distance, mesh) {
  64968. this.distance = distance;
  64969. this.mesh = mesh;
  64970. }
  64971. return MeshLODLevel;
  64972. }());
  64973. Internals.MeshLODLevel = MeshLODLevel;
  64974. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64975. })(BABYLON || (BABYLON = {}));
  64976. //# sourceMappingURL=babylon.meshLODLevel.js.map
  64977. var BABYLON;
  64978. (function (BABYLON) {
  64979. // Standard optimizations
  64980. var SceneOptimization = (function () {
  64981. function SceneOptimization(priority) {
  64982. if (priority === void 0) { priority = 0; }
  64983. this.priority = priority;
  64984. this.apply = function (scene) {
  64985. return true; // Return true if everything that can be done was applied
  64986. };
  64987. }
  64988. return SceneOptimization;
  64989. }());
  64990. BABYLON.SceneOptimization = SceneOptimization;
  64991. var TextureOptimization = (function (_super) {
  64992. __extends(TextureOptimization, _super);
  64993. function TextureOptimization(priority, maximumSize) {
  64994. if (priority === void 0) { priority = 0; }
  64995. if (maximumSize === void 0) { maximumSize = 1024; }
  64996. var _this = _super.call(this, priority) || this;
  64997. _this.priority = priority;
  64998. _this.maximumSize = maximumSize;
  64999. _this.apply = function (scene) {
  65000. var allDone = true;
  65001. for (var index = 0; index < scene.textures.length; index++) {
  65002. var texture = scene.textures[index];
  65003. if (!texture.canRescale) {
  65004. continue;
  65005. }
  65006. var currentSize = texture.getSize();
  65007. var maxDimension = Math.max(currentSize.width, currentSize.height);
  65008. if (maxDimension > _this.maximumSize) {
  65009. texture.scale(0.5);
  65010. allDone = false;
  65011. }
  65012. }
  65013. return allDone;
  65014. };
  65015. return _this;
  65016. }
  65017. return TextureOptimization;
  65018. }(SceneOptimization));
  65019. BABYLON.TextureOptimization = TextureOptimization;
  65020. var HardwareScalingOptimization = (function (_super) {
  65021. __extends(HardwareScalingOptimization, _super);
  65022. function HardwareScalingOptimization(priority, maximumScale) {
  65023. if (priority === void 0) { priority = 0; }
  65024. if (maximumScale === void 0) { maximumScale = 2; }
  65025. var _this = _super.call(this, priority) || this;
  65026. _this.priority = priority;
  65027. _this.maximumScale = maximumScale;
  65028. _this._currentScale = 1;
  65029. _this.apply = function (scene) {
  65030. _this._currentScale++;
  65031. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  65032. return _this._currentScale >= _this.maximumScale;
  65033. };
  65034. return _this;
  65035. }
  65036. return HardwareScalingOptimization;
  65037. }(SceneOptimization));
  65038. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  65039. var ShadowsOptimization = (function (_super) {
  65040. __extends(ShadowsOptimization, _super);
  65041. function ShadowsOptimization() {
  65042. var _this = _super !== null && _super.apply(this, arguments) || this;
  65043. _this.apply = function (scene) {
  65044. scene.shadowsEnabled = false;
  65045. return true;
  65046. };
  65047. return _this;
  65048. }
  65049. return ShadowsOptimization;
  65050. }(SceneOptimization));
  65051. BABYLON.ShadowsOptimization = ShadowsOptimization;
  65052. var PostProcessesOptimization = (function (_super) {
  65053. __extends(PostProcessesOptimization, _super);
  65054. function PostProcessesOptimization() {
  65055. var _this = _super !== null && _super.apply(this, arguments) || this;
  65056. _this.apply = function (scene) {
  65057. scene.postProcessesEnabled = false;
  65058. return true;
  65059. };
  65060. return _this;
  65061. }
  65062. return PostProcessesOptimization;
  65063. }(SceneOptimization));
  65064. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  65065. var LensFlaresOptimization = (function (_super) {
  65066. __extends(LensFlaresOptimization, _super);
  65067. function LensFlaresOptimization() {
  65068. var _this = _super !== null && _super.apply(this, arguments) || this;
  65069. _this.apply = function (scene) {
  65070. scene.lensFlaresEnabled = false;
  65071. return true;
  65072. };
  65073. return _this;
  65074. }
  65075. return LensFlaresOptimization;
  65076. }(SceneOptimization));
  65077. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  65078. var ParticlesOptimization = (function (_super) {
  65079. __extends(ParticlesOptimization, _super);
  65080. function ParticlesOptimization() {
  65081. var _this = _super !== null && _super.apply(this, arguments) || this;
  65082. _this.apply = function (scene) {
  65083. scene.particlesEnabled = false;
  65084. return true;
  65085. };
  65086. return _this;
  65087. }
  65088. return ParticlesOptimization;
  65089. }(SceneOptimization));
  65090. BABYLON.ParticlesOptimization = ParticlesOptimization;
  65091. var RenderTargetsOptimization = (function (_super) {
  65092. __extends(RenderTargetsOptimization, _super);
  65093. function RenderTargetsOptimization() {
  65094. var _this = _super !== null && _super.apply(this, arguments) || this;
  65095. _this.apply = function (scene) {
  65096. scene.renderTargetsEnabled = false;
  65097. return true;
  65098. };
  65099. return _this;
  65100. }
  65101. return RenderTargetsOptimization;
  65102. }(SceneOptimization));
  65103. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  65104. var MergeMeshesOptimization = (function (_super) {
  65105. __extends(MergeMeshesOptimization, _super);
  65106. function MergeMeshesOptimization() {
  65107. var _this = _super !== null && _super.apply(this, arguments) || this;
  65108. _this._canBeMerged = function (abstractMesh) {
  65109. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  65110. return false;
  65111. }
  65112. var mesh = abstractMesh;
  65113. if (!mesh.isVisible || !mesh.isEnabled()) {
  65114. return false;
  65115. }
  65116. if (mesh.instances.length > 0) {
  65117. return false;
  65118. }
  65119. if (mesh.skeleton || mesh.hasLODLevels) {
  65120. return false;
  65121. }
  65122. if (mesh.parent) {
  65123. return false;
  65124. }
  65125. return true;
  65126. };
  65127. _this.apply = function (scene, updateSelectionTree) {
  65128. var globalPool = scene.meshes.slice(0);
  65129. var globalLength = globalPool.length;
  65130. for (var index = 0; index < globalLength; index++) {
  65131. var currentPool = new Array();
  65132. var current = globalPool[index];
  65133. // Checks
  65134. if (!_this._canBeMerged(current)) {
  65135. continue;
  65136. }
  65137. currentPool.push(current);
  65138. // Find compatible meshes
  65139. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  65140. var otherMesh = globalPool[subIndex];
  65141. if (!_this._canBeMerged(otherMesh)) {
  65142. continue;
  65143. }
  65144. if (otherMesh.material !== current.material) {
  65145. continue;
  65146. }
  65147. if (otherMesh.checkCollisions !== current.checkCollisions) {
  65148. continue;
  65149. }
  65150. currentPool.push(otherMesh);
  65151. globalLength--;
  65152. globalPool.splice(subIndex, 1);
  65153. subIndex--;
  65154. }
  65155. if (currentPool.length < 2) {
  65156. continue;
  65157. }
  65158. // Merge meshes
  65159. BABYLON.Mesh.MergeMeshes(currentPool);
  65160. }
  65161. if (updateSelectionTree != undefined) {
  65162. if (updateSelectionTree) {
  65163. scene.createOrUpdateSelectionOctree();
  65164. }
  65165. }
  65166. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  65167. scene.createOrUpdateSelectionOctree();
  65168. }
  65169. return true;
  65170. };
  65171. return _this;
  65172. }
  65173. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  65174. get: function () {
  65175. return MergeMeshesOptimization._UpdateSelectionTree;
  65176. },
  65177. set: function (value) {
  65178. MergeMeshesOptimization._UpdateSelectionTree = value;
  65179. },
  65180. enumerable: true,
  65181. configurable: true
  65182. });
  65183. return MergeMeshesOptimization;
  65184. }(SceneOptimization));
  65185. MergeMeshesOptimization._UpdateSelectionTree = false;
  65186. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  65187. // Options
  65188. var SceneOptimizerOptions = (function () {
  65189. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  65190. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  65191. if (trackerDuration === void 0) { trackerDuration = 2000; }
  65192. this.targetFrameRate = targetFrameRate;
  65193. this.trackerDuration = trackerDuration;
  65194. this.optimizations = new Array();
  65195. }
  65196. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  65197. var result = new SceneOptimizerOptions(targetFrameRate);
  65198. var priority = 0;
  65199. result.optimizations.push(new MergeMeshesOptimization(priority));
  65200. result.optimizations.push(new ShadowsOptimization(priority));
  65201. result.optimizations.push(new LensFlaresOptimization(priority));
  65202. // Next priority
  65203. priority++;
  65204. result.optimizations.push(new PostProcessesOptimization(priority));
  65205. result.optimizations.push(new ParticlesOptimization(priority));
  65206. // Next priority
  65207. priority++;
  65208. result.optimizations.push(new TextureOptimization(priority, 1024));
  65209. return result;
  65210. };
  65211. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  65212. var result = new SceneOptimizerOptions(targetFrameRate);
  65213. var priority = 0;
  65214. result.optimizations.push(new MergeMeshesOptimization(priority));
  65215. result.optimizations.push(new ShadowsOptimization(priority));
  65216. result.optimizations.push(new LensFlaresOptimization(priority));
  65217. // Next priority
  65218. priority++;
  65219. result.optimizations.push(new PostProcessesOptimization(priority));
  65220. result.optimizations.push(new ParticlesOptimization(priority));
  65221. // Next priority
  65222. priority++;
  65223. result.optimizations.push(new TextureOptimization(priority, 512));
  65224. // Next priority
  65225. priority++;
  65226. result.optimizations.push(new RenderTargetsOptimization(priority));
  65227. // Next priority
  65228. priority++;
  65229. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  65230. return result;
  65231. };
  65232. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  65233. var result = new SceneOptimizerOptions(targetFrameRate);
  65234. var priority = 0;
  65235. result.optimizations.push(new MergeMeshesOptimization(priority));
  65236. result.optimizations.push(new ShadowsOptimization(priority));
  65237. result.optimizations.push(new LensFlaresOptimization(priority));
  65238. // Next priority
  65239. priority++;
  65240. result.optimizations.push(new PostProcessesOptimization(priority));
  65241. result.optimizations.push(new ParticlesOptimization(priority));
  65242. // Next priority
  65243. priority++;
  65244. result.optimizations.push(new TextureOptimization(priority, 256));
  65245. // Next priority
  65246. priority++;
  65247. result.optimizations.push(new RenderTargetsOptimization(priority));
  65248. // Next priority
  65249. priority++;
  65250. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  65251. return result;
  65252. };
  65253. return SceneOptimizerOptions;
  65254. }());
  65255. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  65256. // Scene optimizer tool
  65257. var SceneOptimizer = (function () {
  65258. function SceneOptimizer() {
  65259. }
  65260. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  65261. // TODO: add an epsilon
  65262. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  65263. if (onSuccess) {
  65264. onSuccess();
  65265. }
  65266. return;
  65267. }
  65268. // Apply current level of optimizations
  65269. var allDone = true;
  65270. var noOptimizationApplied = true;
  65271. for (var index = 0; index < options.optimizations.length; index++) {
  65272. var optimization = options.optimizations[index];
  65273. if (optimization.priority === currentPriorityLevel) {
  65274. noOptimizationApplied = false;
  65275. allDone = allDone && optimization.apply(scene);
  65276. }
  65277. }
  65278. // If no optimization was applied, this is a failure :(
  65279. if (noOptimizationApplied) {
  65280. if (onFailure) {
  65281. onFailure();
  65282. }
  65283. return;
  65284. }
  65285. // If all optimizations were done, move to next level
  65286. if (allDone) {
  65287. currentPriorityLevel++;
  65288. }
  65289. // Let's the system running for a specific amount of time before checking FPS
  65290. scene.executeWhenReady(function () {
  65291. setTimeout(function () {
  65292. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  65293. }, options.trackerDuration);
  65294. });
  65295. };
  65296. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  65297. if (!options) {
  65298. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  65299. }
  65300. // Let's the system running for a specific amount of time before checking FPS
  65301. scene.executeWhenReady(function () {
  65302. setTimeout(function () {
  65303. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  65304. }, options.trackerDuration);
  65305. });
  65306. };
  65307. return SceneOptimizer;
  65308. }());
  65309. BABYLON.SceneOptimizer = SceneOptimizer;
  65310. })(BABYLON || (BABYLON = {}));
  65311. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  65312. var BABYLON;
  65313. (function (BABYLON) {
  65314. var OutlineRenderer = (function () {
  65315. function OutlineRenderer(scene) {
  65316. this.zOffset = 1;
  65317. this._scene = scene;
  65318. }
  65319. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  65320. var _this = this;
  65321. if (useOverlay === void 0) { useOverlay = false; }
  65322. var scene = this._scene;
  65323. var engine = this._scene.getEngine();
  65324. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65325. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  65326. return;
  65327. }
  65328. var mesh = subMesh.getRenderingMesh();
  65329. var material = subMesh.getMaterial();
  65330. engine.enableEffect(this._effect);
  65331. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  65332. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  65333. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65334. // Bones
  65335. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65336. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65337. }
  65338. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65339. // Alpha test
  65340. if (material && material.needAlphaTesting()) {
  65341. var alphaTexture = material.getAlphaTestTexture();
  65342. this._effect.setTexture("diffuseSampler", alphaTexture);
  65343. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65344. }
  65345. engine.setZOffset(-this.zOffset);
  65346. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  65347. engine.setZOffset(0);
  65348. };
  65349. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  65350. var defines = [];
  65351. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  65352. var mesh = subMesh.getMesh();
  65353. var material = subMesh.getMaterial();
  65354. // Alpha test
  65355. if (material && material.needAlphaTesting()) {
  65356. defines.push("#define ALPHATEST");
  65357. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65358. attribs.push(BABYLON.VertexBuffer.UVKind);
  65359. defines.push("#define UV1");
  65360. }
  65361. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65362. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65363. defines.push("#define UV2");
  65364. }
  65365. }
  65366. // Bones
  65367. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65368. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65369. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65370. if (mesh.numBoneInfluencers > 4) {
  65371. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65372. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65373. }
  65374. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65375. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65376. }
  65377. else {
  65378. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65379. }
  65380. // Instances
  65381. if (useInstances) {
  65382. defines.push("#define INSTANCES");
  65383. attribs.push("world0");
  65384. attribs.push("world1");
  65385. attribs.push("world2");
  65386. attribs.push("world3");
  65387. }
  65388. // Get correct effect
  65389. var join = defines.join("\n");
  65390. if (this._cachedDefines !== join) {
  65391. this._cachedDefines = join;
  65392. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  65393. }
  65394. return this._effect.isReady();
  65395. };
  65396. return OutlineRenderer;
  65397. }());
  65398. BABYLON.OutlineRenderer = OutlineRenderer;
  65399. })(BABYLON || (BABYLON = {}));
  65400. //# sourceMappingURL=babylon.outlineRenderer.js.map
  65401. var BABYLON;
  65402. (function (BABYLON) {
  65403. var FaceAdjacencies = (function () {
  65404. function FaceAdjacencies() {
  65405. this.edges = new Array();
  65406. this.edgesConnectedCount = 0;
  65407. }
  65408. return FaceAdjacencies;
  65409. }());
  65410. var EdgesRenderer = (function () {
  65411. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  65412. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  65413. if (epsilon === void 0) { epsilon = 0.95; }
  65414. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  65415. this.edgesWidthScalerForOrthographic = 1000.0;
  65416. this.edgesWidthScalerForPerspective = 50.0;
  65417. this._linesPositions = new Array();
  65418. this._linesNormals = new Array();
  65419. this._linesIndices = new Array();
  65420. this._buffers = {};
  65421. this._checkVerticesInsteadOfIndices = false;
  65422. this._source = source;
  65423. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  65424. this._epsilon = epsilon;
  65425. this._prepareRessources();
  65426. this._generateEdgesLines();
  65427. }
  65428. EdgesRenderer.prototype._prepareRessources = function () {
  65429. if (this._lineShader) {
  65430. return;
  65431. }
  65432. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  65433. attributes: ["position", "normal"],
  65434. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  65435. });
  65436. this._lineShader.disableDepthWrite = true;
  65437. this._lineShader.backFaceCulling = false;
  65438. };
  65439. EdgesRenderer.prototype.dispose = function () {
  65440. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  65441. if (buffer) {
  65442. buffer.dispose();
  65443. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  65444. }
  65445. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  65446. if (buffer) {
  65447. buffer.dispose();
  65448. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  65449. }
  65450. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  65451. this._lineShader.dispose();
  65452. };
  65453. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  65454. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  65455. return 0;
  65456. }
  65457. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  65458. return 1;
  65459. }
  65460. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  65461. return 2;
  65462. }
  65463. return -1;
  65464. };
  65465. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  65466. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  65467. return 0;
  65468. }
  65469. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  65470. return 1;
  65471. }
  65472. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  65473. return 2;
  65474. }
  65475. return -1;
  65476. };
  65477. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  65478. var needToCreateLine;
  65479. if (edge === undefined) {
  65480. needToCreateLine = true;
  65481. }
  65482. else {
  65483. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  65484. needToCreateLine = dotProduct < this._epsilon;
  65485. }
  65486. if (needToCreateLine) {
  65487. var offset = this._linesPositions.length / 3;
  65488. var normal = p0.subtract(p1);
  65489. normal.normalize();
  65490. // Positions
  65491. this._linesPositions.push(p0.x);
  65492. this._linesPositions.push(p0.y);
  65493. this._linesPositions.push(p0.z);
  65494. this._linesPositions.push(p0.x);
  65495. this._linesPositions.push(p0.y);
  65496. this._linesPositions.push(p0.z);
  65497. this._linesPositions.push(p1.x);
  65498. this._linesPositions.push(p1.y);
  65499. this._linesPositions.push(p1.z);
  65500. this._linesPositions.push(p1.x);
  65501. this._linesPositions.push(p1.y);
  65502. this._linesPositions.push(p1.z);
  65503. // Normals
  65504. this._linesNormals.push(p1.x);
  65505. this._linesNormals.push(p1.y);
  65506. this._linesNormals.push(p1.z);
  65507. this._linesNormals.push(-1);
  65508. this._linesNormals.push(p1.x);
  65509. this._linesNormals.push(p1.y);
  65510. this._linesNormals.push(p1.z);
  65511. this._linesNormals.push(1);
  65512. this._linesNormals.push(p0.x);
  65513. this._linesNormals.push(p0.y);
  65514. this._linesNormals.push(p0.z);
  65515. this._linesNormals.push(-1);
  65516. this._linesNormals.push(p0.x);
  65517. this._linesNormals.push(p0.y);
  65518. this._linesNormals.push(p0.z);
  65519. this._linesNormals.push(1);
  65520. // Indices
  65521. this._linesIndices.push(offset);
  65522. this._linesIndices.push(offset + 1);
  65523. this._linesIndices.push(offset + 2);
  65524. this._linesIndices.push(offset);
  65525. this._linesIndices.push(offset + 2);
  65526. this._linesIndices.push(offset + 3);
  65527. }
  65528. };
  65529. EdgesRenderer.prototype._generateEdgesLines = function () {
  65530. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65531. var indices = this._source.getIndices();
  65532. // First let's find adjacencies
  65533. var adjacencies = new Array();
  65534. var faceNormals = new Array();
  65535. var index;
  65536. var faceAdjacencies;
  65537. // Prepare faces
  65538. for (index = 0; index < indices.length; index += 3) {
  65539. faceAdjacencies = new FaceAdjacencies();
  65540. var p0Index = indices[index];
  65541. var p1Index = indices[index + 1];
  65542. var p2Index = indices[index + 2];
  65543. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  65544. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  65545. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  65546. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  65547. faceNormal.normalize();
  65548. faceNormals.push(faceNormal);
  65549. adjacencies.push(faceAdjacencies);
  65550. }
  65551. // Scan
  65552. for (index = 0; index < adjacencies.length; index++) {
  65553. faceAdjacencies = adjacencies[index];
  65554. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  65555. var otherFaceAdjacencies = adjacencies[otherIndex];
  65556. if (faceAdjacencies.edgesConnectedCount === 3) {
  65557. break;
  65558. }
  65559. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  65560. continue;
  65561. }
  65562. var otherP0 = indices[otherIndex * 3];
  65563. var otherP1 = indices[otherIndex * 3 + 1];
  65564. var otherP2 = indices[otherIndex * 3 + 2];
  65565. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  65566. var otherEdgeIndex;
  65567. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  65568. continue;
  65569. }
  65570. switch (edgeIndex) {
  65571. case 0:
  65572. if (this._checkVerticesInsteadOfIndices) {
  65573. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65574. }
  65575. else {
  65576. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  65577. }
  65578. break;
  65579. case 1:
  65580. if (this._checkVerticesInsteadOfIndices) {
  65581. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65582. }
  65583. else {
  65584. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  65585. }
  65586. break;
  65587. case 2:
  65588. if (this._checkVerticesInsteadOfIndices) {
  65589. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65590. }
  65591. else {
  65592. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  65593. }
  65594. break;
  65595. }
  65596. if (otherEdgeIndex === -1) {
  65597. continue;
  65598. }
  65599. faceAdjacencies.edges[edgeIndex] = otherIndex;
  65600. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  65601. faceAdjacencies.edgesConnectedCount++;
  65602. otherFaceAdjacencies.edgesConnectedCount++;
  65603. if (faceAdjacencies.edgesConnectedCount === 3) {
  65604. break;
  65605. }
  65606. }
  65607. }
  65608. }
  65609. // Create lines
  65610. for (index = 0; index < adjacencies.length; index++) {
  65611. // 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
  65612. var current = adjacencies[index];
  65613. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  65614. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  65615. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  65616. }
  65617. // Merge into a single mesh
  65618. var engine = this._source.getScene().getEngine();
  65619. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  65620. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  65621. this._ib = engine.createIndexBuffer(this._linesIndices);
  65622. this._indicesCount = this._linesIndices.length;
  65623. };
  65624. EdgesRenderer.prototype.render = function () {
  65625. if (!this._lineShader.isReady()) {
  65626. return;
  65627. }
  65628. var scene = this._source.getScene();
  65629. var engine = scene.getEngine();
  65630. this._lineShader._preBind();
  65631. // VBOs
  65632. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  65633. scene.resetCachedMaterial();
  65634. this._lineShader.setColor4("color", this._source.edgesColor);
  65635. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  65636. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  65637. }
  65638. else {
  65639. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  65640. }
  65641. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  65642. this._lineShader.bind(this._source.getWorldMatrix());
  65643. // Draw order
  65644. engine.draw(true, 0, this._indicesCount);
  65645. this._lineShader.unbind();
  65646. engine.setDepthWrite(true);
  65647. };
  65648. return EdgesRenderer;
  65649. }());
  65650. BABYLON.EdgesRenderer = EdgesRenderer;
  65651. })(BABYLON || (BABYLON = {}));
  65652. //# sourceMappingURL=babylon.edgesRenderer.js.map
  65653. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  65654. /// <reference path="..\Math\babylon.math.ts" />
  65655. var BABYLON;
  65656. (function (BABYLON) {
  65657. /**
  65658. * Special Glow Blur post process only blurring the alpha channel
  65659. * It enforces keeping the most luminous color in the color channel.
  65660. */
  65661. var GlowBlurPostProcess = (function (_super) {
  65662. __extends(GlowBlurPostProcess, _super);
  65663. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  65664. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65665. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  65666. _this.direction = direction;
  65667. _this.kernel = kernel;
  65668. _this.onApplyObservable.add(function (effect) {
  65669. effect.setFloat2("screenSize", _this.width, _this.height);
  65670. effect.setVector2("direction", _this.direction);
  65671. effect.setFloat("blurWidth", _this.kernel);
  65672. });
  65673. return _this;
  65674. }
  65675. return GlowBlurPostProcess;
  65676. }(BABYLON.PostProcess));
  65677. /**
  65678. * The highlight layer Helps adding a glow effect around a mesh.
  65679. *
  65680. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  65681. * glowy meshes to your scene.
  65682. *
  65683. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  65684. */
  65685. var HighlightLayer = (function () {
  65686. /**
  65687. * Instantiates a new highlight Layer and references it to the scene..
  65688. * @param name The name of the layer
  65689. * @param scene The scene to use the layer in
  65690. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  65691. */
  65692. function HighlightLayer(name, scene, options) {
  65693. this.name = name;
  65694. this._vertexBuffers = {};
  65695. this._mainTextureDesiredSize = { width: 0, height: 0 };
  65696. this._meshes = {};
  65697. this._maxSize = 0;
  65698. this._shouldRender = false;
  65699. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  65700. this._excludedMeshes = {};
  65701. /**
  65702. * Specifies whether or not the inner glow is ACTIVE in the layer.
  65703. */
  65704. this.innerGlow = true;
  65705. /**
  65706. * Specifies whether or not the outer glow is ACTIVE in the layer.
  65707. */
  65708. this.outerGlow = true;
  65709. /**
  65710. * Specifies wether the highlight layer is enabled or not.
  65711. */
  65712. this.isEnabled = true;
  65713. /**
  65714. * An event triggered when the highlight layer has been disposed.
  65715. * @type {BABYLON.Observable}
  65716. */
  65717. this.onDisposeObservable = new BABYLON.Observable();
  65718. /**
  65719. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  65720. * @type {BABYLON.Observable}
  65721. */
  65722. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  65723. /**
  65724. * An event triggered when the highlight layer is being blurred.
  65725. * @type {BABYLON.Observable}
  65726. */
  65727. this.onBeforeBlurObservable = new BABYLON.Observable();
  65728. /**
  65729. * An event triggered when the highlight layer has been blurred.
  65730. * @type {BABYLON.Observable}
  65731. */
  65732. this.onAfterBlurObservable = new BABYLON.Observable();
  65733. /**
  65734. * An event triggered when the glowing blurred texture is being merged in the scene.
  65735. * @type {BABYLON.Observable}
  65736. */
  65737. this.onBeforeComposeObservable = new BABYLON.Observable();
  65738. /**
  65739. * An event triggered when the glowing blurred texture has been merged in the scene.
  65740. * @type {BABYLON.Observable}
  65741. */
  65742. this.onAfterComposeObservable = new BABYLON.Observable();
  65743. /**
  65744. * An event triggered when the highlight layer changes its size.
  65745. * @type {BABYLON.Observable}
  65746. */
  65747. this.onSizeChangedObservable = new BABYLON.Observable();
  65748. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65749. var engine = scene.getEngine();
  65750. this._engine = engine;
  65751. this._maxSize = this._engine.getCaps().maxTextureSize;
  65752. this._scene.highlightLayers.push(this);
  65753. // Warn on stencil.
  65754. if (!this._engine.isStencilEnable) {
  65755. 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 }");
  65756. }
  65757. // Adapt options
  65758. this._options = options || {
  65759. mainTextureRatio: 0.25,
  65760. blurTextureSizeRatio: 0.5,
  65761. blurHorizontalSize: 1,
  65762. blurVerticalSize: 1,
  65763. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  65764. };
  65765. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  65766. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  65767. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  65768. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  65769. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  65770. // VBO
  65771. var vertices = [];
  65772. vertices.push(1, 1);
  65773. vertices.push(-1, 1);
  65774. vertices.push(-1, -1);
  65775. vertices.push(1, -1);
  65776. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  65778. // Indices
  65779. var indices = [];
  65780. indices.push(0);
  65781. indices.push(1);
  65782. indices.push(2);
  65783. indices.push(0);
  65784. indices.push(2);
  65785. indices.push(3);
  65786. this._indexBuffer = engine.createIndexBuffer(indices);
  65787. // Effect
  65788. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  65789. // Render target
  65790. this.setMainTextureSize();
  65791. // Create Textures and post processes
  65792. this.createTextureAndPostProcesses();
  65793. }
  65794. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  65795. /**
  65796. * Gets the horizontal size of the blur.
  65797. */
  65798. get: function () {
  65799. return this._horizontalBlurPostprocess.kernel;
  65800. },
  65801. /**
  65802. * Specifies the horizontal size of the blur.
  65803. */
  65804. set: function (value) {
  65805. this._horizontalBlurPostprocess.kernel = value;
  65806. },
  65807. enumerable: true,
  65808. configurable: true
  65809. });
  65810. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  65811. /**
  65812. * Gets the vertical size of the blur.
  65813. */
  65814. get: function () {
  65815. return this._verticalBlurPostprocess.kernel;
  65816. },
  65817. /**
  65818. * Specifies the vertical size of the blur.
  65819. */
  65820. set: function (value) {
  65821. this._verticalBlurPostprocess.kernel = value;
  65822. },
  65823. enumerable: true,
  65824. configurable: true
  65825. });
  65826. Object.defineProperty(HighlightLayer.prototype, "camera", {
  65827. /**
  65828. * Gets the camera attached to the layer.
  65829. */
  65830. get: function () {
  65831. return this._options.camera;
  65832. },
  65833. enumerable: true,
  65834. configurable: true
  65835. });
  65836. /**
  65837. * Creates the render target textures and post processes used in the highlight layer.
  65838. */
  65839. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  65840. var _this = this;
  65841. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  65842. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  65843. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  65844. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  65845. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  65846. width: this._mainTextureDesiredSize.width,
  65847. height: this._mainTextureDesiredSize.height
  65848. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65849. this._mainTexture.activeCamera = this._options.camera;
  65850. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65851. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65852. this._mainTexture.anisotropicFilteringLevel = 1;
  65853. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65854. this._mainTexture.renderParticles = false;
  65855. this._mainTexture.renderList = null;
  65856. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  65857. width: blurTextureWidth,
  65858. height: blurTextureHeight
  65859. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65860. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65861. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65862. this._blurTexture.anisotropicFilteringLevel = 16;
  65863. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65864. this._blurTexture.renderParticles = false;
  65865. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65866. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  65867. effect.setTexture("textureSampler", _this._mainTexture);
  65868. });
  65869. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  65870. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65871. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  65872. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65873. });
  65874. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65875. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  65876. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65877. });
  65878. }
  65879. else {
  65880. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65881. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  65882. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65883. });
  65884. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65885. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  65886. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65887. });
  65888. }
  65889. this._mainTexture.onAfterUnbindObservable.add(function () {
  65890. _this.onBeforeBlurObservable.notifyObservers(_this);
  65891. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  65892. _this.onAfterBlurObservable.notifyObservers(_this);
  65893. });
  65894. // Custom render function
  65895. var renderSubMesh = function (subMesh) {
  65896. var mesh = subMesh.getRenderingMesh();
  65897. var scene = _this._scene;
  65898. var engine = scene.getEngine();
  65899. // Culling
  65900. engine.setState(subMesh.getMaterial().backFaceCulling);
  65901. // Managing instances
  65902. var batch = mesh._getInstancesRenderList(subMesh._id);
  65903. if (batch.mustReturn) {
  65904. return;
  65905. }
  65906. // Excluded Mesh
  65907. if (_this._excludedMeshes[mesh.uniqueId]) {
  65908. return;
  65909. }
  65910. ;
  65911. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65912. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  65913. var material = subMesh.getMaterial();
  65914. var emissiveTexture = null;
  65915. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  65916. emissiveTexture = material.emissiveTexture;
  65917. }
  65918. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  65919. engine.enableEffect(_this._glowMapGenerationEffect);
  65920. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  65921. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  65922. if (highlightLayerMesh) {
  65923. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  65924. }
  65925. else {
  65926. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  65927. }
  65928. // Alpha test
  65929. if (material && material.needAlphaTesting()) {
  65930. var alphaTexture = material.getAlphaTestTexture();
  65931. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  65932. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65933. }
  65934. // Glow emissive only
  65935. if (emissiveTexture) {
  65936. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  65937. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  65938. }
  65939. // Bones
  65940. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65941. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65942. }
  65943. // Draw
  65944. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  65945. }
  65946. else {
  65947. // Need to reset refresh rate of the shadowMap
  65948. _this._mainTexture.resetRefreshCounter();
  65949. }
  65950. };
  65951. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  65952. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  65953. var index;
  65954. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65955. renderSubMesh(opaqueSubMeshes.data[index]);
  65956. }
  65957. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65958. renderSubMesh(alphaTestSubMeshes.data[index]);
  65959. }
  65960. for (index = 0; index < transparentSubMeshes.length; index++) {
  65961. renderSubMesh(transparentSubMeshes.data[index]);
  65962. }
  65963. };
  65964. this._mainTexture.onClearObservable.add(function (engine) {
  65965. engine.clear(HighlightLayer.neutralColor, true, true, true);
  65966. });
  65967. };
  65968. /**
  65969. * Checks for the readiness of the element composing the layer.
  65970. * @param subMesh the mesh to check for
  65971. * @param useInstances specify wether or not to use instances to render the mesh
  65972. * @param emissiveTexture the associated emissive texture used to generate the glow
  65973. * @return true if ready otherwise, false
  65974. */
  65975. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  65976. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  65977. return false;
  65978. }
  65979. var defines = [];
  65980. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65981. var mesh = subMesh.getMesh();
  65982. var material = subMesh.getMaterial();
  65983. var uv1 = false;
  65984. var uv2 = false;
  65985. // Alpha test
  65986. if (material && material.needAlphaTesting()) {
  65987. var alphaTexture = material.getAlphaTestTexture();
  65988. if (alphaTexture) {
  65989. defines.push("#define ALPHATEST");
  65990. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  65991. alphaTexture.coordinatesIndex === 1) {
  65992. defines.push("#define DIFFUSEUV2");
  65993. uv2 = true;
  65994. }
  65995. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65996. defines.push("#define DIFFUSEUV1");
  65997. uv1 = true;
  65998. }
  65999. }
  66000. }
  66001. // Emissive
  66002. if (emissiveTexture) {
  66003. defines.push("#define EMISSIVE");
  66004. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  66005. emissiveTexture.coordinatesIndex === 1) {
  66006. defines.push("#define EMISSIVEUV2");
  66007. uv2 = true;
  66008. }
  66009. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66010. defines.push("#define EMISSIVEUV1");
  66011. uv1 = true;
  66012. }
  66013. }
  66014. if (uv1) {
  66015. attribs.push(BABYLON.VertexBuffer.UVKind);
  66016. defines.push("#define UV1");
  66017. }
  66018. if (uv2) {
  66019. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66020. defines.push("#define UV2");
  66021. }
  66022. // Bones
  66023. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66024. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66025. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66026. if (mesh.numBoneInfluencers > 4) {
  66027. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66028. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66029. }
  66030. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66031. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66032. }
  66033. else {
  66034. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66035. }
  66036. // Instances
  66037. if (useInstances) {
  66038. defines.push("#define INSTANCES");
  66039. attribs.push("world0");
  66040. attribs.push("world1");
  66041. attribs.push("world2");
  66042. attribs.push("world3");
  66043. }
  66044. // Get correct effect
  66045. var join = defines.join("\n");
  66046. if (this._cachedDefines !== join) {
  66047. this._cachedDefines = join;
  66048. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  66049. }
  66050. return this._glowMapGenerationEffect.isReady();
  66051. };
  66052. /**
  66053. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  66054. */
  66055. HighlightLayer.prototype.render = function () {
  66056. var currentEffect = this._glowMapMergeEffect;
  66057. // Check
  66058. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  66059. return;
  66060. var engine = this._scene.getEngine();
  66061. this.onBeforeComposeObservable.notifyObservers(this);
  66062. // Render
  66063. engine.enableEffect(currentEffect);
  66064. engine.setState(false);
  66065. // Cache
  66066. var previousStencilBuffer = engine.getStencilBuffer();
  66067. var previousStencilFunction = engine.getStencilFunction();
  66068. var previousStencilMask = engine.getStencilMask();
  66069. var previousStencilOperationPass = engine.getStencilOperationPass();
  66070. var previousStencilOperationFail = engine.getStencilOperationFail();
  66071. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  66072. var previousAlphaMode = engine.getAlphaMode();
  66073. // Texture
  66074. currentEffect.setTexture("textureSampler", this._blurTexture);
  66075. // VBOs
  66076. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  66077. // Stencil operations
  66078. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  66079. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  66080. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  66081. // Draw order
  66082. engine.setAlphaMode(this._options.alphaBlendingMode);
  66083. engine.setStencilMask(0x00);
  66084. engine.setStencilBuffer(true);
  66085. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  66086. if (this.outerGlow) {
  66087. currentEffect.setFloat("offset", 0);
  66088. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  66089. engine.draw(true, 0, 6);
  66090. }
  66091. if (this.innerGlow) {
  66092. currentEffect.setFloat("offset", 1);
  66093. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  66094. engine.draw(true, 0, 6);
  66095. }
  66096. // Restore Cache
  66097. engine.setStencilFunction(previousStencilFunction);
  66098. engine.setStencilMask(previousStencilMask);
  66099. engine.setAlphaMode(previousAlphaMode);
  66100. engine.setStencilBuffer(previousStencilBuffer);
  66101. engine.setStencilOperationPass(previousStencilOperationPass);
  66102. engine.setStencilOperationFail(previousStencilOperationFail);
  66103. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  66104. engine._stencilState.reset();
  66105. this.onAfterComposeObservable.notifyObservers(this);
  66106. // Handle size changes.
  66107. var size = this._mainTexture.getSize();
  66108. this.setMainTextureSize();
  66109. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  66110. // Recreate RTT and post processes on size change.
  66111. this.onSizeChangedObservable.notifyObservers(this);
  66112. this.disposeTextureAndPostProcesses();
  66113. this.createTextureAndPostProcesses();
  66114. }
  66115. };
  66116. /**
  66117. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  66118. * @param mesh The mesh to exclude from the highlight layer
  66119. */
  66120. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  66121. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  66122. if (!meshExcluded) {
  66123. this._excludedMeshes[mesh.uniqueId] = {
  66124. mesh: mesh,
  66125. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  66126. mesh.getEngine().setStencilBuffer(false);
  66127. }),
  66128. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  66129. mesh.getEngine().setStencilBuffer(true);
  66130. }),
  66131. };
  66132. }
  66133. };
  66134. /**
  66135. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  66136. * @param mesh The mesh to highlight
  66137. */
  66138. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  66139. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  66140. if (meshExcluded) {
  66141. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  66142. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  66143. }
  66144. this._excludedMeshes[mesh.uniqueId] = undefined;
  66145. };
  66146. /**
  66147. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  66148. * @param mesh The mesh to highlight
  66149. * @param color The color of the highlight
  66150. * @param glowEmissiveOnly Extract the glow from the emissive texture
  66151. */
  66152. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  66153. var _this = this;
  66154. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  66155. var meshHighlight = this._meshes[mesh.uniqueId];
  66156. if (meshHighlight) {
  66157. meshHighlight.color = color;
  66158. }
  66159. else {
  66160. this._meshes[mesh.uniqueId] = {
  66161. mesh: mesh,
  66162. color: color,
  66163. // Lambda required for capture due to Observable this context
  66164. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  66165. if (_this._excludedMeshes[mesh.uniqueId]) {
  66166. _this.defaultStencilReference(mesh);
  66167. }
  66168. else {
  66169. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  66170. }
  66171. }),
  66172. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  66173. glowEmissiveOnly: glowEmissiveOnly
  66174. };
  66175. }
  66176. this._shouldRender = true;
  66177. };
  66178. /**
  66179. * Remove a mesh from the highlight layer in order to make it stop glowing.
  66180. * @param mesh The mesh to highlight
  66181. */
  66182. HighlightLayer.prototype.removeMesh = function (mesh) {
  66183. var meshHighlight = this._meshes[mesh.uniqueId];
  66184. if (meshHighlight) {
  66185. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  66186. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  66187. }
  66188. this._meshes[mesh.uniqueId] = undefined;
  66189. this._shouldRender = false;
  66190. for (var meshHighlightToCheck in this._meshes) {
  66191. if (meshHighlightToCheck) {
  66192. this._shouldRender = true;
  66193. break;
  66194. }
  66195. }
  66196. };
  66197. /**
  66198. * Returns true if the layer contains information to display, otherwise false.
  66199. */
  66200. HighlightLayer.prototype.shouldRender = function () {
  66201. return this.isEnabled && this._shouldRender;
  66202. };
  66203. /**
  66204. * Sets the main texture desired size which is the closest power of two
  66205. * of the engine canvas size.
  66206. */
  66207. HighlightLayer.prototype.setMainTextureSize = function () {
  66208. if (this._options.mainTextureFixedSize) {
  66209. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  66210. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  66211. }
  66212. else {
  66213. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  66214. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  66215. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  66216. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  66217. }
  66218. };
  66219. /**
  66220. * Force the stencil to the normal expected value for none glowing parts
  66221. */
  66222. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  66223. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  66224. };
  66225. /**
  66226. * Dispose only the render target textures and post process.
  66227. */
  66228. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  66229. this._blurTexture.dispose();
  66230. this._mainTexture.dispose();
  66231. this._downSamplePostprocess.dispose();
  66232. this._horizontalBlurPostprocess.dispose();
  66233. this._verticalBlurPostprocess.dispose();
  66234. };
  66235. /**
  66236. * Dispose the highlight layer and free resources.
  66237. */
  66238. HighlightLayer.prototype.dispose = function () {
  66239. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66240. if (vertexBuffer) {
  66241. vertexBuffer.dispose();
  66242. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66243. }
  66244. if (this._indexBuffer) {
  66245. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66246. this._indexBuffer = null;
  66247. }
  66248. // Clean textures and post processes
  66249. this.disposeTextureAndPostProcesses();
  66250. // Clean mesh references
  66251. for (var id in this._meshes) {
  66252. var meshHighlight = this._meshes[id];
  66253. if (meshHighlight && meshHighlight.mesh) {
  66254. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  66255. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  66256. }
  66257. }
  66258. this._meshes = null;
  66259. for (var id in this._excludedMeshes) {
  66260. var meshHighlight = this._excludedMeshes[id];
  66261. if (meshHighlight) {
  66262. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  66263. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  66264. }
  66265. }
  66266. this._excludedMeshes = null;
  66267. // Remove from scene
  66268. var index = this._scene.highlightLayers.indexOf(this, 0);
  66269. if (index > -1) {
  66270. this._scene.highlightLayers.splice(index, 1);
  66271. }
  66272. // Callback
  66273. this.onDisposeObservable.notifyObservers(this);
  66274. this.onDisposeObservable.clear();
  66275. this.onBeforeRenderMainTextureObservable.clear();
  66276. this.onBeforeBlurObservable.clear();
  66277. this.onBeforeComposeObservable.clear();
  66278. this.onAfterComposeObservable.clear();
  66279. this.onSizeChangedObservable.clear();
  66280. };
  66281. return HighlightLayer;
  66282. }());
  66283. /**
  66284. * The neutral color used during the preparation of the glow effect.
  66285. * This is black by default as the blend operation is a blend operation.
  66286. */
  66287. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  66288. /**
  66289. * Stencil value used for glowing meshes.
  66290. */
  66291. HighlightLayer.glowingMeshStencilReference = 0x02;
  66292. /**
  66293. * Stencil value used for the other meshes in the scene.
  66294. */
  66295. HighlightLayer.normalMeshStencilReference = 0x01;
  66296. BABYLON.HighlightLayer = HighlightLayer;
  66297. })(BABYLON || (BABYLON = {}));
  66298. //# sourceMappingURL=babylon.highlightlayer.js.map
  66299. var BABYLON;
  66300. (function (BABYLON) {
  66301. var MeshAssetTask = (function () {
  66302. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  66303. this.name = name;
  66304. this.meshesNames = meshesNames;
  66305. this.rootUrl = rootUrl;
  66306. this.sceneFilename = sceneFilename;
  66307. this.isCompleted = false;
  66308. }
  66309. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66310. var _this = this;
  66311. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  66312. _this.loadedMeshes = meshes;
  66313. _this.loadedParticleSystems = particleSystems;
  66314. _this.loadedSkeletons = skeletons;
  66315. _this.isCompleted = true;
  66316. if (_this.onSuccess) {
  66317. _this.onSuccess(_this);
  66318. }
  66319. onSuccess();
  66320. }, null, function () {
  66321. if (_this.onError) {
  66322. _this.onError(_this);
  66323. }
  66324. onError();
  66325. });
  66326. };
  66327. return MeshAssetTask;
  66328. }());
  66329. BABYLON.MeshAssetTask = MeshAssetTask;
  66330. var TextFileAssetTask = (function () {
  66331. function TextFileAssetTask(name, url) {
  66332. this.name = name;
  66333. this.url = url;
  66334. this.isCompleted = false;
  66335. }
  66336. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66337. var _this = this;
  66338. BABYLON.Tools.LoadFile(this.url, function (data) {
  66339. _this.text = data;
  66340. _this.isCompleted = true;
  66341. if (_this.onSuccess) {
  66342. _this.onSuccess(_this);
  66343. }
  66344. onSuccess();
  66345. }, null, scene.database, false, function () {
  66346. if (_this.onError) {
  66347. _this.onError(_this);
  66348. }
  66349. onError();
  66350. });
  66351. };
  66352. return TextFileAssetTask;
  66353. }());
  66354. BABYLON.TextFileAssetTask = TextFileAssetTask;
  66355. var BinaryFileAssetTask = (function () {
  66356. function BinaryFileAssetTask(name, url) {
  66357. this.name = name;
  66358. this.url = url;
  66359. this.isCompleted = false;
  66360. }
  66361. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66362. var _this = this;
  66363. BABYLON.Tools.LoadFile(this.url, function (data) {
  66364. _this.data = data;
  66365. _this.isCompleted = true;
  66366. if (_this.onSuccess) {
  66367. _this.onSuccess(_this);
  66368. }
  66369. onSuccess();
  66370. }, null, scene.database, true, function () {
  66371. if (_this.onError) {
  66372. _this.onError(_this);
  66373. }
  66374. onError();
  66375. });
  66376. };
  66377. return BinaryFileAssetTask;
  66378. }());
  66379. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  66380. var ImageAssetTask = (function () {
  66381. function ImageAssetTask(name, url) {
  66382. this.name = name;
  66383. this.url = url;
  66384. this.isCompleted = false;
  66385. }
  66386. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66387. var _this = this;
  66388. var img = new Image();
  66389. BABYLON.Tools.SetCorsBehavior(this.url, img);
  66390. img.onload = function () {
  66391. _this.image = img;
  66392. _this.isCompleted = true;
  66393. if (_this.onSuccess) {
  66394. _this.onSuccess(_this);
  66395. }
  66396. onSuccess();
  66397. };
  66398. img.onerror = function () {
  66399. if (_this.onError) {
  66400. _this.onError(_this);
  66401. }
  66402. onError();
  66403. };
  66404. img.src = this.url;
  66405. };
  66406. return ImageAssetTask;
  66407. }());
  66408. BABYLON.ImageAssetTask = ImageAssetTask;
  66409. var TextureAssetTask = (function () {
  66410. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  66411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66412. this.name = name;
  66413. this.url = url;
  66414. this.noMipmap = noMipmap;
  66415. this.invertY = invertY;
  66416. this.samplingMode = samplingMode;
  66417. this.isCompleted = false;
  66418. }
  66419. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66420. var _this = this;
  66421. var onload = function () {
  66422. _this.isCompleted = true;
  66423. if (_this.onSuccess) {
  66424. _this.onSuccess(_this);
  66425. }
  66426. onSuccess();
  66427. };
  66428. var onerror = function () {
  66429. if (_this.onError) {
  66430. _this.onError(_this);
  66431. }
  66432. onError();
  66433. };
  66434. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  66435. };
  66436. return TextureAssetTask;
  66437. }());
  66438. BABYLON.TextureAssetTask = TextureAssetTask;
  66439. var CubeTextureAssetTask = (function () {
  66440. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  66441. this.name = name;
  66442. this.url = url;
  66443. this.extensions = extensions;
  66444. this.noMipmap = noMipmap;
  66445. this.files = files;
  66446. this.isCompleted = false;
  66447. }
  66448. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66449. var _this = this;
  66450. var onload = function () {
  66451. _this.isCompleted = true;
  66452. if (_this.onSuccess) {
  66453. _this.onSuccess(_this);
  66454. }
  66455. onSuccess();
  66456. };
  66457. var onerror = function () {
  66458. if (_this.onError) {
  66459. _this.onError(_this);
  66460. }
  66461. onError();
  66462. };
  66463. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  66464. };
  66465. return CubeTextureAssetTask;
  66466. }());
  66467. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  66468. var HDRCubeTextureAssetTask = (function () {
  66469. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  66470. if (noMipmap === void 0) { noMipmap = false; }
  66471. if (generateHarmonics === void 0) { generateHarmonics = true; }
  66472. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  66473. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  66474. this.name = name;
  66475. this.url = url;
  66476. this.size = size;
  66477. this.noMipmap = noMipmap;
  66478. this.generateHarmonics = generateHarmonics;
  66479. this.useInGammaSpace = useInGammaSpace;
  66480. this.usePMREMGenerator = usePMREMGenerator;
  66481. this.isCompleted = false;
  66482. }
  66483. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66484. var _this = this;
  66485. var onload = function () {
  66486. _this.isCompleted = true;
  66487. if (_this.onSuccess) {
  66488. _this.onSuccess(_this);
  66489. }
  66490. onSuccess();
  66491. };
  66492. var onerror = function () {
  66493. if (_this.onError) {
  66494. _this.onError(_this);
  66495. }
  66496. onError();
  66497. };
  66498. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  66499. };
  66500. return HDRCubeTextureAssetTask;
  66501. }());
  66502. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  66503. var AssetsManager = (function () {
  66504. function AssetsManager(scene) {
  66505. this.tasks = new Array();
  66506. this.waitingTasksCount = 0;
  66507. this.useDefaultLoadingScreen = true;
  66508. this._scene = scene;
  66509. }
  66510. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  66511. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  66512. this.tasks.push(task);
  66513. return task;
  66514. };
  66515. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  66516. var task = new TextFileAssetTask(taskName, url);
  66517. this.tasks.push(task);
  66518. return task;
  66519. };
  66520. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  66521. var task = new BinaryFileAssetTask(taskName, url);
  66522. this.tasks.push(task);
  66523. return task;
  66524. };
  66525. AssetsManager.prototype.addImageTask = function (taskName, url) {
  66526. var task = new ImageAssetTask(taskName, url);
  66527. this.tasks.push(task);
  66528. return task;
  66529. };
  66530. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  66531. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66532. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  66533. this.tasks.push(task);
  66534. return task;
  66535. };
  66536. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  66537. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  66538. this.tasks.push(task);
  66539. return task;
  66540. };
  66541. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  66542. if (noMipmap === void 0) { noMipmap = false; }
  66543. if (generateHarmonics === void 0) { generateHarmonics = true; }
  66544. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  66545. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  66546. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  66547. this.tasks.push(task);
  66548. return task;
  66549. };
  66550. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  66551. this.waitingTasksCount--;
  66552. if (this.waitingTasksCount === 0) {
  66553. if (this.onFinish) {
  66554. this.onFinish(this.tasks);
  66555. }
  66556. this._scene.getEngine().hideLoadingUI();
  66557. }
  66558. };
  66559. AssetsManager.prototype._runTask = function (task) {
  66560. var _this = this;
  66561. task.run(this._scene, function () {
  66562. if (_this.onTaskSuccess) {
  66563. _this.onTaskSuccess(task);
  66564. }
  66565. _this._decreaseWaitingTasksCount();
  66566. }, function () {
  66567. if (_this.onTaskError) {
  66568. _this.onTaskError(task);
  66569. }
  66570. _this._decreaseWaitingTasksCount();
  66571. });
  66572. };
  66573. AssetsManager.prototype.reset = function () {
  66574. this.tasks = new Array();
  66575. return this;
  66576. };
  66577. AssetsManager.prototype.load = function () {
  66578. this.waitingTasksCount = this.tasks.length;
  66579. if (this.waitingTasksCount === 0) {
  66580. if (this.onFinish) {
  66581. this.onFinish(this.tasks);
  66582. }
  66583. return this;
  66584. }
  66585. if (this.useDefaultLoadingScreen) {
  66586. this._scene.getEngine().displayLoadingUI();
  66587. }
  66588. for (var index = 0; index < this.tasks.length; index++) {
  66589. var task = this.tasks[index];
  66590. this._runTask(task);
  66591. }
  66592. return this;
  66593. };
  66594. return AssetsManager;
  66595. }());
  66596. BABYLON.AssetsManager = AssetsManager;
  66597. })(BABYLON || (BABYLON = {}));
  66598. //# sourceMappingURL=babylon.assetsManager.js.map
  66599. var BABYLON;
  66600. (function (BABYLON) {
  66601. var MapTexture = (function (_super) {
  66602. __extends(MapTexture, _super);
  66603. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  66604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66605. if (useMipMap === void 0) { useMipMap = false; }
  66606. if (margin === void 0) { margin = 0; }
  66607. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  66608. _this.name = name;
  66609. _this._size = size;
  66610. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66611. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66612. // Create the rectPackMap that will allocate portion of the texture
  66613. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  66614. // Create the texture that will store the content
  66615. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  66616. return _this;
  66617. }
  66618. /**
  66619. * Allocate a rectangle of a given size in the texture map
  66620. * @param size the size of the rectangle to allocation
  66621. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  66622. */
  66623. MapTexture.prototype.allocateRect = function (size) {
  66624. return this._rectPackingMap.addRect(size);
  66625. };
  66626. /**
  66627. * Free a given rectangle from the texture map
  66628. * @param rectInfo the instance corresponding to the rect to free.
  66629. */
  66630. MapTexture.prototype.freeRect = function (rectInfo) {
  66631. if (rectInfo) {
  66632. rectInfo.freeContent();
  66633. }
  66634. };
  66635. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  66636. /**
  66637. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  66638. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  66639. * @returns {}
  66640. */
  66641. get: function () {
  66642. return this._rectPackingMap.freeSpace;
  66643. },
  66644. enumerable: true,
  66645. configurable: true
  66646. });
  66647. /**
  66648. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  66649. * 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.
  66650. * Don't forget to call unbindTexture when you're done rendering
  66651. * @param rect the zone to render to
  66652. * @param clear true to clear the portion's color/depth data
  66653. */
  66654. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  66655. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  66656. };
  66657. /**
  66658. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  66659. * 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.
  66660. * Don't forget to call unbindTexture when you're done rendering
  66661. * @param pos the position into the texture
  66662. * @param size the portion to fit the clip space to
  66663. * @param clear true to clear the portion's color/depth data
  66664. */
  66665. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  66666. var engine = this.getScene().getEngine();
  66667. engine.bindFramebuffer(this._texture);
  66668. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  66669. if (clear) {
  66670. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  66671. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  66672. }
  66673. };
  66674. /**
  66675. * Unbind the texture map from the rendering engine.
  66676. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  66677. * @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.
  66678. */
  66679. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  66680. // Dump ?
  66681. if (dumpForDebug) {
  66682. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  66683. }
  66684. var engine = this.getScene().getEngine();
  66685. if (this._replacedViewport) {
  66686. engine.setViewport(this._replacedViewport);
  66687. this._replacedViewport = null;
  66688. }
  66689. engine.unBindFramebuffer(this._texture);
  66690. };
  66691. Object.defineProperty(MapTexture.prototype, "canRescale", {
  66692. get: function () {
  66693. return false;
  66694. },
  66695. enumerable: true,
  66696. configurable: true
  66697. });
  66698. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  66699. // Anyway, there's not much point to use this method for this kind of texture I guess
  66700. MapTexture.prototype.clone = function () {
  66701. return null;
  66702. };
  66703. return MapTexture;
  66704. }(BABYLON.Texture));
  66705. BABYLON.MapTexture = MapTexture;
  66706. })(BABYLON || (BABYLON = {}));
  66707. //# sourceMappingURL=babylon.mapTexture.js.map
  66708. var BABYLON;
  66709. (function (BABYLON) {
  66710. /**
  66711. * This class describe a rectangle that were added to the map.
  66712. * You have access to its coordinates either in pixel or normalized (UV)
  66713. */
  66714. var PackedRect = (function () {
  66715. function PackedRect(root, parent, pos, size) {
  66716. this._pos = pos;
  66717. this._size = size;
  66718. this._root = root;
  66719. this._parent = parent;
  66720. this._contentSize = null;
  66721. this._bottomNode = null;
  66722. this._leftNode = null;
  66723. this._initialSize = null;
  66724. this._rightNode = null;
  66725. }
  66726. Object.defineProperty(PackedRect.prototype, "pos", {
  66727. /**
  66728. * @returns the position of this node into the map
  66729. */
  66730. get: function () {
  66731. return this._pos;
  66732. },
  66733. enumerable: true,
  66734. configurable: true
  66735. });
  66736. Object.defineProperty(PackedRect.prototype, "contentSize", {
  66737. /**
  66738. * @returns the size of the rectangle this node handles
  66739. */
  66740. get: function () {
  66741. return this._contentSize;
  66742. },
  66743. enumerable: true,
  66744. configurable: true
  66745. });
  66746. /**
  66747. * Retrieve the inner position (considering the margin) and stores it into the res object
  66748. * @param res must be a valid Vector2 that will contain the inner position after this call
  66749. */
  66750. PackedRect.prototype.getInnerPosToRef = function (res) {
  66751. var m = this._root._margin;
  66752. res.x = this._pos.x + m;
  66753. res.y = this._pos.y + m;
  66754. };
  66755. /**
  66756. * Retrieve the inner size (considering the margin) and stores it into the res object
  66757. * @param res must be a valid Size that will contain the inner size after this call
  66758. */
  66759. PackedRect.prototype.getInnerSizeToRef = function (res) {
  66760. var m = this._root._margin;
  66761. res.width = this._contentSize.width - (m * 2);
  66762. res.height = this._contentSize.height - (m * 2);
  66763. };
  66764. Object.defineProperty(PackedRect.prototype, "UVs", {
  66765. /**
  66766. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  66767. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  66768. */
  66769. get: function () {
  66770. if (!this._contentSize) {
  66771. throw new Error("Can't compute UVs for this object because it's nor allocated");
  66772. }
  66773. return this.getUVsForCustomSize(this._contentSize);
  66774. },
  66775. enumerable: true,
  66776. configurable: true
  66777. });
  66778. /**
  66779. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  66780. * and then using only a part of the PackRect.
  66781. * This method will return the UVs for this part by given the custom size of what you really use
  66782. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  66783. */
  66784. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  66785. var mainWidth = this._root._size.width;
  66786. var mainHeight = this._root._size.height;
  66787. var margin = this._root._margin;
  66788. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  66789. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  66790. var uvs = new Array();
  66791. uvs.push(topLeft);
  66792. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  66793. uvs.push(rightBottom);
  66794. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  66795. return uvs;
  66796. };
  66797. /**
  66798. * Free this rectangle from the map.
  66799. * Call this method when you no longer need the rectangle to be in the map.
  66800. */
  66801. PackedRect.prototype.freeContent = function () {
  66802. if (!this.contentSize) {
  66803. return;
  66804. }
  66805. this._contentSize = null;
  66806. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  66807. this.attemptDefrag();
  66808. };
  66809. Object.defineProperty(PackedRect.prototype, "isUsed", {
  66810. get: function () {
  66811. return this._contentSize != null || this._leftNode != null;
  66812. },
  66813. enumerable: true,
  66814. configurable: true
  66815. });
  66816. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  66817. var node = this.findNode(contentSize);
  66818. // Not enough space...
  66819. if (!node) {
  66820. return null;
  66821. }
  66822. node.splitNode(contentSize);
  66823. return node;
  66824. };
  66825. PackedRect.prototype.findNode = function (size) {
  66826. var resNode = null;
  66827. var margin = this._root._margin * 2;
  66828. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  66829. if (this.isUsed) {
  66830. if (this._leftNode) {
  66831. resNode = this._leftNode.findNode(size);
  66832. }
  66833. if (!resNode && this._rightNode) {
  66834. resNode = this._rightNode.findNode(size);
  66835. }
  66836. if (!resNode && this._bottomNode) {
  66837. resNode = this._bottomNode.findNode(size);
  66838. }
  66839. }
  66840. else if (this._initialSize) {
  66841. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  66842. resNode = this;
  66843. }
  66844. else {
  66845. return null;
  66846. }
  66847. }
  66848. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  66849. resNode = this;
  66850. }
  66851. return resNode;
  66852. };
  66853. PackedRect.prototype.splitNode = function (contentSize) {
  66854. var cs = PackedRect.TpsSize;
  66855. var margin = this._root._margin * 2;
  66856. cs.copyFrom(contentSize);
  66857. cs.width += margin;
  66858. cs.height += margin;
  66859. // 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)
  66860. if (!this._contentSize && this._initialSize) {
  66861. this._contentSize = cs.clone();
  66862. 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));
  66863. return this._leftNode.splitNode(contentSize);
  66864. }
  66865. else {
  66866. this._contentSize = cs.clone();
  66867. this._initialSize = cs.clone();
  66868. if (cs.width !== this._size.width) {
  66869. 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));
  66870. }
  66871. if (cs.height !== this._size.height) {
  66872. 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));
  66873. }
  66874. return this;
  66875. }
  66876. };
  66877. PackedRect.prototype.attemptDefrag = function () {
  66878. if (!this.isUsed && this.isRecursiveFree) {
  66879. this.clearNode();
  66880. if (this._parent) {
  66881. this._parent.attemptDefrag();
  66882. }
  66883. }
  66884. };
  66885. PackedRect.prototype.clearNode = function () {
  66886. this._initialSize = null;
  66887. this._rightNode = null;
  66888. this._bottomNode = null;
  66889. };
  66890. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  66891. get: function () {
  66892. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  66893. },
  66894. enumerable: true,
  66895. configurable: true
  66896. });
  66897. PackedRect.prototype.evalFreeSize = function (size) {
  66898. var levelSize = 0;
  66899. if (!this.isUsed) {
  66900. var margin = this._root._margin;
  66901. var is = this._initialSize;
  66902. if (is) {
  66903. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  66904. }
  66905. else {
  66906. var size_1 = this._size;
  66907. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  66908. }
  66909. }
  66910. if (this._rightNode) {
  66911. levelSize += this._rightNode.evalFreeSize(0);
  66912. }
  66913. if (this._bottomNode) {
  66914. levelSize += this._bottomNode.evalFreeSize(0);
  66915. }
  66916. return levelSize + size;
  66917. };
  66918. return PackedRect;
  66919. }());
  66920. PackedRect.TpsSize = BABYLON.Size.Zero();
  66921. BABYLON.PackedRect = PackedRect;
  66922. /**
  66923. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  66924. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  66925. * 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.
  66926. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  66927. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  66928. */
  66929. var RectPackingMap = (function (_super) {
  66930. __extends(RectPackingMap, _super);
  66931. /**
  66932. * Create an instance of the object with a dimension using the given size
  66933. * @param size The dimension of the rectangle that will contain all the sub ones.
  66934. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  66935. */
  66936. function RectPackingMap(size, margin) {
  66937. if (margin === void 0) { margin = 0; }
  66938. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  66939. _this._margin = margin;
  66940. _this._root = _this;
  66941. return _this;
  66942. }
  66943. /**
  66944. * Add a rectangle, finding the best location to store it into the map
  66945. * @param size the dimension of the rectangle to store
  66946. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  66947. */
  66948. RectPackingMap.prototype.addRect = function (size) {
  66949. var node = this.findAndSplitNode(size);
  66950. return node;
  66951. };
  66952. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  66953. /**
  66954. * Return the current space free normalized between [0;1]
  66955. * @returns {}
  66956. */
  66957. get: function () {
  66958. var freeSize = 0;
  66959. freeSize = this.evalFreeSize(freeSize);
  66960. return freeSize / (this._size.width * this._size.height);
  66961. },
  66962. enumerable: true,
  66963. configurable: true
  66964. });
  66965. return RectPackingMap;
  66966. }(PackedRect));
  66967. BABYLON.RectPackingMap = RectPackingMap;
  66968. })(BABYLON || (BABYLON = {}));
  66969. //# sourceMappingURL=babylon.rectPackingMap.js.map
  66970. var BABYLON;
  66971. (function (BABYLON) {
  66972. /**
  66973. * This groups together the common properties used for image processing either in direct forward pass
  66974. * or through post processing effect depending on the use of the image processing pipeline in your scene
  66975. * or not.
  66976. */
  66977. var ImageProcessingConfiguration = (function () {
  66978. function ImageProcessingConfiguration() {
  66979. /**
  66980. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  66981. */
  66982. this.colorCurves = new BABYLON.ColorCurves();
  66983. this._colorCurvesEnabled = false;
  66984. this._colorGradingEnabled = false;
  66985. this._colorGradingWithGreenDepth = false;
  66986. this._colorGradingBGR = false;
  66987. this._exposure = 1.0;
  66988. this._toneMappingEnabled = false;
  66989. this._contrast = 1.0;
  66990. /**
  66991. * Vignette stretch size.
  66992. */
  66993. this.vignetteStretch = 0;
  66994. /**
  66995. * Vignette centre X Offset.
  66996. */
  66997. this.vignetteCentreX = 0;
  66998. /**
  66999. * Vignette centre Y Offset.
  67000. */
  67001. this.vignetteCentreY = 0;
  67002. /**
  67003. * Vignette weight or intensity of the vignette effect.
  67004. */
  67005. this.vignetteWeight = 1.5;
  67006. /**
  67007. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67008. * if vignetteEnabled is set to true.
  67009. */
  67010. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  67011. /**
  67012. * Camera field of view used by the Vignette effect.
  67013. */
  67014. this.vignetteCameraFov = 0.5;
  67015. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  67016. this._vignetteEnabled = false;
  67017. this._applyByPostProcess = false;
  67018. /**
  67019. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  67020. * @type {BABYLON.Observable}
  67021. */
  67022. this.onUpdateParameters = new BABYLON.Observable();
  67023. }
  67024. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  67025. /**
  67026. * Gets wether the color curves effect is enabled.
  67027. */
  67028. get: function () {
  67029. return this._colorCurvesEnabled;
  67030. },
  67031. /**
  67032. * Sets wether the color curves effect is enabled.
  67033. */
  67034. set: function (value) {
  67035. if (this._colorCurvesEnabled === value) {
  67036. return;
  67037. }
  67038. this._colorCurvesEnabled = value;
  67039. this._updateParameters();
  67040. },
  67041. enumerable: true,
  67042. configurable: true
  67043. });
  67044. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  67045. /**
  67046. * Gets wether the color grading effect is enabled.
  67047. */
  67048. get: function () {
  67049. return this._colorGradingEnabled;
  67050. },
  67051. /**
  67052. * Sets wether the color grading effect is enabled.
  67053. */
  67054. set: function (value) {
  67055. if (this._colorGradingEnabled === value) {
  67056. return;
  67057. }
  67058. this._colorGradingEnabled = value;
  67059. this._updateParameters();
  67060. },
  67061. enumerable: true,
  67062. configurable: true
  67063. });
  67064. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  67065. /**
  67066. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  67067. */
  67068. get: function () {
  67069. return this._colorGradingWithGreenDepth;
  67070. },
  67071. /**
  67072. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  67073. */
  67074. set: function (value) {
  67075. if (this._colorGradingWithGreenDepth === value) {
  67076. return;
  67077. }
  67078. this._colorGradingWithGreenDepth = value;
  67079. this._updateParameters();
  67080. },
  67081. enumerable: true,
  67082. configurable: true
  67083. });
  67084. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  67085. /**
  67086. * Gets wether the color grading texture contains BGR values.
  67087. */
  67088. get: function () {
  67089. return this._colorGradingBGR;
  67090. },
  67091. /**
  67092. * Sets wether the color grading texture contains BGR values.
  67093. */
  67094. set: function (value) {
  67095. if (this._colorGradingBGR === value) {
  67096. return;
  67097. }
  67098. this._colorGradingBGR = value;
  67099. this._updateParameters();
  67100. },
  67101. enumerable: true,
  67102. configurable: true
  67103. });
  67104. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  67105. /**
  67106. * Gets the Exposure used in the effect.
  67107. */
  67108. get: function () {
  67109. return this._exposure;
  67110. },
  67111. /**
  67112. * Sets the Exposure used in the effect.
  67113. */
  67114. set: function (value) {
  67115. if (this._exposure === value) {
  67116. return;
  67117. }
  67118. this._exposure = value;
  67119. this._updateParameters();
  67120. },
  67121. enumerable: true,
  67122. configurable: true
  67123. });
  67124. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  67125. /**
  67126. * Gets wether the tone mapping effect is enabled.
  67127. */
  67128. get: function () {
  67129. return this._toneMappingEnabled;
  67130. },
  67131. /**
  67132. * Sets wether the tone mapping effect is enabled.
  67133. */
  67134. set: function (value) {
  67135. if (this._toneMappingEnabled === value) {
  67136. return;
  67137. }
  67138. this._toneMappingEnabled = value;
  67139. this._updateParameters();
  67140. },
  67141. enumerable: true,
  67142. configurable: true
  67143. });
  67144. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  67145. /**
  67146. * Gets the contrast used in the effect.
  67147. */
  67148. get: function () {
  67149. return this._contrast;
  67150. },
  67151. /**
  67152. * Sets the contrast used in the effect.
  67153. */
  67154. set: function (value) {
  67155. if (this._contrast === value) {
  67156. return;
  67157. }
  67158. this._contrast = value;
  67159. this._updateParameters();
  67160. },
  67161. enumerable: true,
  67162. configurable: true
  67163. });
  67164. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  67165. /**
  67166. * Gets the vignette blend mode allowing different kind of effect.
  67167. */
  67168. get: function () {
  67169. return this._vignetteBlendMode;
  67170. },
  67171. /**
  67172. * Sets the vignette blend mode allowing different kind of effect.
  67173. */
  67174. set: function (value) {
  67175. if (this._vignetteBlendMode === value) {
  67176. return;
  67177. }
  67178. this._vignetteBlendMode = value;
  67179. this._updateParameters();
  67180. },
  67181. enumerable: true,
  67182. configurable: true
  67183. });
  67184. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  67185. /**
  67186. * Gets wether the vignette effect is enabled.
  67187. */
  67188. get: function () {
  67189. return this._vignetteEnabled;
  67190. },
  67191. /**
  67192. * Sets wether the vignette effect is enabled.
  67193. */
  67194. set: function (value) {
  67195. if (this._vignetteEnabled === value) {
  67196. return;
  67197. }
  67198. this._vignetteEnabled = value;
  67199. this._updateParameters();
  67200. },
  67201. enumerable: true,
  67202. configurable: true
  67203. });
  67204. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  67205. /**
  67206. * Gets wether the image processing is applied through a post process or not.
  67207. */
  67208. get: function () {
  67209. return this._applyByPostProcess;
  67210. },
  67211. /**
  67212. * Sets wether the image processing is applied through a post process or not.
  67213. */
  67214. set: function (value) {
  67215. if (this._applyByPostProcess === value) {
  67216. return;
  67217. }
  67218. this._applyByPostProcess = value;
  67219. this._updateParameters();
  67220. },
  67221. enumerable: true,
  67222. configurable: true
  67223. });
  67224. /**
  67225. * Method called each time the image processing information changes requires to recompile the effect.
  67226. */
  67227. ImageProcessingConfiguration.prototype._updateParameters = function () {
  67228. this.onUpdateParameters.notifyObservers(this);
  67229. };
  67230. /**
  67231. * Prepare the list of uniforms associated with the Image Processing effects.
  67232. * @param uniformsList The list of uniforms used in the effect
  67233. * @param defines the list of defines currently in use
  67234. */
  67235. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  67236. if (defines.EXPOSURE) {
  67237. uniforms.push("exposureLinear");
  67238. }
  67239. if (defines.CONTRAST) {
  67240. uniforms.push("contrast");
  67241. }
  67242. if (defines.COLORGRADING) {
  67243. uniforms.push("colorTransformSettings");
  67244. }
  67245. if (defines.VIGNETTE) {
  67246. uniforms.push("vInverseScreenSize");
  67247. uniforms.push("vignetteSettings1");
  67248. uniforms.push("vignetteSettings2");
  67249. }
  67250. if (defines.COLORCURVES) {
  67251. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  67252. }
  67253. };
  67254. /**
  67255. * Prepare the list of samplers associated with the Image Processing effects.
  67256. * @param uniformsList The list of uniforms used in the effect
  67257. * @param defines the list of defines currently in use
  67258. */
  67259. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  67260. if (defines.COLORGRADING) {
  67261. samplersList.push("txColorTransform");
  67262. }
  67263. };
  67264. /**
  67265. * Prepare the list of defines associated to the shader.
  67266. * @param defines the list of defines to complete
  67267. */
  67268. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  67269. defines.VIGNETTE = this.vignetteEnabled;
  67270. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  67271. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  67272. defines.TONEMAPPING = this.toneMappingEnabled;
  67273. defines.CONTRAST = (this.contrast !== 1.0);
  67274. defines.EXPOSURE = (this.exposure !== 1.0);
  67275. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  67276. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  67277. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  67278. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  67279. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  67280. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  67281. };
  67282. /**
  67283. * Returns true if all the image processing information are ready.
  67284. */
  67285. ImageProcessingConfiguration.prototype.isReady = function () {
  67286. // Color Grading texure can not be none blocking.
  67287. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  67288. };
  67289. /**
  67290. * Binds the image processing to the shader.
  67291. * @param effect The effect to bind to
  67292. */
  67293. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  67294. if (aspectRatio === void 0) { aspectRatio = 1; }
  67295. // Color Curves
  67296. if (this._colorCurvesEnabled) {
  67297. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  67298. }
  67299. // Vignette
  67300. if (this._vignetteEnabled) {
  67301. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  67302. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  67303. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  67304. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  67305. var vignetteScaleX = vignetteScaleY * aspectRatio;
  67306. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  67307. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  67308. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  67309. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  67310. var vignettePower = -2.0 * this.vignetteWeight;
  67311. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  67312. }
  67313. // Exposure
  67314. effect.setFloat("exposureLinear", this.exposure);
  67315. // Contrast
  67316. effect.setFloat("contrast", this.contrast);
  67317. // Color transform settings
  67318. if (this.colorGradingTexture) {
  67319. effect.setTexture("txColorTransform", this.colorGradingTexture);
  67320. var textureSize = this.colorGradingTexture.getSize().height;
  67321. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  67322. 0.5 / textureSize, // textureOffset
  67323. textureSize, // textureSize
  67324. this.colorGradingTexture.level // weight
  67325. );
  67326. }
  67327. };
  67328. /**
  67329. * Clones the current image processing instance.
  67330. * @return The cloned image processing
  67331. */
  67332. ImageProcessingConfiguration.prototype.clone = function () {
  67333. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  67334. };
  67335. /**
  67336. * Serializes the current image processing instance to a json representation.
  67337. * @return a JSON representation
  67338. */
  67339. ImageProcessingConfiguration.prototype.serialize = function () {
  67340. return BABYLON.SerializationHelper.Serialize(this);
  67341. };
  67342. /**
  67343. * Parses the image processing from a json representation.
  67344. * @param source the JSON source to parse
  67345. * @return The parsed image processing
  67346. */
  67347. ImageProcessingConfiguration.Parse = function (source) {
  67348. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  67349. };
  67350. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  67351. /**
  67352. * Used to apply the vignette as a mix with the pixel color.
  67353. */
  67354. get: function () {
  67355. return this._VIGNETTEMODE_MULTIPLY;
  67356. },
  67357. enumerable: true,
  67358. configurable: true
  67359. });
  67360. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  67361. /**
  67362. * Used to apply the vignette as a replacement of the pixel color.
  67363. */
  67364. get: function () {
  67365. return this._VIGNETTEMODE_OPAQUE;
  67366. },
  67367. enumerable: true,
  67368. configurable: true
  67369. });
  67370. return ImageProcessingConfiguration;
  67371. }());
  67372. // Static constants associated to the image processing.
  67373. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  67374. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  67375. __decorate([
  67376. BABYLON.serializeAsColorCurves()
  67377. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  67378. __decorate([
  67379. BABYLON.serialize()
  67380. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  67381. __decorate([
  67382. BABYLON.serializeAsTexture()
  67383. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  67384. __decorate([
  67385. BABYLON.serialize()
  67386. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  67387. __decorate([
  67388. BABYLON.serialize()
  67389. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  67390. __decorate([
  67391. BABYLON.serialize()
  67392. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  67393. __decorate([
  67394. BABYLON.serialize()
  67395. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  67396. __decorate([
  67397. BABYLON.serialize()
  67398. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  67399. __decorate([
  67400. BABYLON.serialize()
  67401. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  67402. __decorate([
  67403. BABYLON.serialize()
  67404. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  67405. __decorate([
  67406. BABYLON.serialize()
  67407. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  67408. __decorate([
  67409. BABYLON.serialize()
  67410. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  67411. __decorate([
  67412. BABYLON.serialize()
  67413. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  67414. __decorate([
  67415. BABYLON.serializeAsColor4()
  67416. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  67417. __decorate([
  67418. BABYLON.serialize()
  67419. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  67420. __decorate([
  67421. BABYLON.serialize()
  67422. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  67423. __decorate([
  67424. BABYLON.serialize()
  67425. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  67426. __decorate([
  67427. BABYLON.serialize()
  67428. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  67429. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  67430. })(BABYLON || (BABYLON = {}));
  67431. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  67432. var BABYLON;
  67433. (function (BABYLON) {
  67434. var serializedGeometries = [];
  67435. var serializeGeometry = function (geometry, serializationGeometries) {
  67436. if (serializedGeometries[geometry.id]) {
  67437. return;
  67438. }
  67439. if (geometry.doNotSerialize) {
  67440. return;
  67441. }
  67442. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  67443. serializationGeometries.boxes.push(geometry.serialize());
  67444. }
  67445. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  67446. serializationGeometries.spheres.push(geometry.serialize());
  67447. }
  67448. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  67449. serializationGeometries.cylinders.push(geometry.serialize());
  67450. }
  67451. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  67452. serializationGeometries.toruses.push(geometry.serialize());
  67453. }
  67454. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  67455. serializationGeometries.grounds.push(geometry.serialize());
  67456. }
  67457. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  67458. serializationGeometries.planes.push(geometry.serialize());
  67459. }
  67460. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  67461. serializationGeometries.torusKnots.push(geometry.serialize());
  67462. }
  67463. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  67464. throw new Error("Unknown primitive type");
  67465. }
  67466. else {
  67467. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  67468. }
  67469. serializedGeometries[geometry.id] = true;
  67470. };
  67471. var serializeMesh = function (mesh, serializationScene) {
  67472. var serializationObject = {};
  67473. // Geometry
  67474. var geometry = mesh._geometry;
  67475. if (geometry) {
  67476. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  67477. // 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
  67478. serializeGeometry(geometry, serializationScene.geometries);
  67479. }
  67480. }
  67481. // Custom
  67482. if (mesh.serialize) {
  67483. mesh.serialize(serializationObject);
  67484. }
  67485. return serializationObject;
  67486. };
  67487. var finalizeSingleMesh = function (mesh, serializationObject) {
  67488. //only works if the mesh is already loaded
  67489. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  67490. //serialize material
  67491. if (mesh.material) {
  67492. if (mesh.material instanceof BABYLON.StandardMaterial) {
  67493. serializationObject.materials = serializationObject.materials || [];
  67494. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  67495. serializationObject.materials.push(mesh.material.serialize());
  67496. }
  67497. }
  67498. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  67499. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  67500. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  67501. serializationObject.multiMaterials.push(mesh.material.serialize());
  67502. }
  67503. }
  67504. }
  67505. //serialize geometry
  67506. var geometry = mesh._geometry;
  67507. if (geometry) {
  67508. if (!serializationObject.geometries) {
  67509. serializationObject.geometries = {};
  67510. serializationObject.geometries.boxes = [];
  67511. serializationObject.geometries.spheres = [];
  67512. serializationObject.geometries.cylinders = [];
  67513. serializationObject.geometries.toruses = [];
  67514. serializationObject.geometries.grounds = [];
  67515. serializationObject.geometries.planes = [];
  67516. serializationObject.geometries.torusKnots = [];
  67517. serializationObject.geometries.vertexData = [];
  67518. }
  67519. serializeGeometry(geometry, serializationObject.geometries);
  67520. }
  67521. // Skeletons
  67522. if (mesh.skeleton) {
  67523. serializationObject.skeletons = serializationObject.skeletons || [];
  67524. serializationObject.skeletons.push(mesh.skeleton.serialize());
  67525. }
  67526. //serialize the actual mesh
  67527. serializationObject.meshes = serializationObject.meshes || [];
  67528. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  67529. }
  67530. };
  67531. var SceneSerializer = (function () {
  67532. function SceneSerializer() {
  67533. }
  67534. SceneSerializer.ClearCache = function () {
  67535. serializedGeometries = [];
  67536. };
  67537. SceneSerializer.Serialize = function (scene) {
  67538. var serializationObject = {};
  67539. SceneSerializer.ClearCache();
  67540. // Scene
  67541. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  67542. serializationObject.autoClear = scene.autoClear;
  67543. serializationObject.clearColor = scene.clearColor.asArray();
  67544. serializationObject.ambientColor = scene.ambientColor.asArray();
  67545. serializationObject.gravity = scene.gravity.asArray();
  67546. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  67547. serializationObject.workerCollisions = scene.workerCollisions;
  67548. // Fog
  67549. if (scene.fogMode && scene.fogMode !== 0) {
  67550. serializationObject.fogMode = scene.fogMode;
  67551. serializationObject.fogColor = scene.fogColor.asArray();
  67552. serializationObject.fogStart = scene.fogStart;
  67553. serializationObject.fogEnd = scene.fogEnd;
  67554. serializationObject.fogDensity = scene.fogDensity;
  67555. }
  67556. //Physics
  67557. if (scene.isPhysicsEnabled()) {
  67558. serializationObject.physicsEnabled = true;
  67559. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  67560. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  67561. }
  67562. // Metadata
  67563. if (scene.metadata) {
  67564. serializationObject.metadata = scene.metadata;
  67565. }
  67566. // Morph targets
  67567. serializationObject.morphTargetManagers = [];
  67568. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  67569. var abstractMesh = _a[_i];
  67570. var manager = abstractMesh.morphTargetManager;
  67571. if (manager) {
  67572. serializationObject.morphTargetManagers.push(manager.serialize());
  67573. }
  67574. }
  67575. // Lights
  67576. serializationObject.lights = [];
  67577. var index;
  67578. var light;
  67579. for (index = 0; index < scene.lights.length; index++) {
  67580. light = scene.lights[index];
  67581. if (!light.doNotSerialize) {
  67582. serializationObject.lights.push(light.serialize());
  67583. }
  67584. }
  67585. // Cameras
  67586. serializationObject.cameras = [];
  67587. for (index = 0; index < scene.cameras.length; index++) {
  67588. var camera = scene.cameras[index];
  67589. if (!camera.doNotSerialize) {
  67590. serializationObject.cameras.push(camera.serialize());
  67591. }
  67592. }
  67593. if (scene.activeCamera) {
  67594. serializationObject.activeCameraID = scene.activeCamera.id;
  67595. }
  67596. // Animations
  67597. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  67598. // Materials
  67599. serializationObject.materials = [];
  67600. serializationObject.multiMaterials = [];
  67601. var material;
  67602. for (index = 0; index < scene.materials.length; index++) {
  67603. material = scene.materials[index];
  67604. if (!material.doNotSerialize) {
  67605. serializationObject.materials.push(material.serialize());
  67606. }
  67607. }
  67608. // MultiMaterials
  67609. serializationObject.multiMaterials = [];
  67610. for (index = 0; index < scene.multiMaterials.length; index++) {
  67611. var multiMaterial = scene.multiMaterials[index];
  67612. serializationObject.multiMaterials.push(multiMaterial.serialize());
  67613. }
  67614. // Skeletons
  67615. serializationObject.skeletons = [];
  67616. for (index = 0; index < scene.skeletons.length; index++) {
  67617. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  67618. }
  67619. // Geometries
  67620. serializationObject.geometries = {};
  67621. serializationObject.geometries.boxes = [];
  67622. serializationObject.geometries.spheres = [];
  67623. serializationObject.geometries.cylinders = [];
  67624. serializationObject.geometries.toruses = [];
  67625. serializationObject.geometries.grounds = [];
  67626. serializationObject.geometries.planes = [];
  67627. serializationObject.geometries.torusKnots = [];
  67628. serializationObject.geometries.vertexData = [];
  67629. serializedGeometries = [];
  67630. var geometries = scene.getGeometries();
  67631. for (index = 0; index < geometries.length; index++) {
  67632. var geometry = geometries[index];
  67633. if (geometry.isReady()) {
  67634. serializeGeometry(geometry, serializationObject.geometries);
  67635. }
  67636. }
  67637. // Meshes
  67638. serializationObject.meshes = [];
  67639. for (index = 0; index < scene.meshes.length; index++) {
  67640. var abstractMesh = scene.meshes[index];
  67641. if (abstractMesh instanceof BABYLON.Mesh) {
  67642. var mesh = abstractMesh;
  67643. if (!mesh.doNotSerialize) {
  67644. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  67645. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  67646. }
  67647. }
  67648. }
  67649. }
  67650. // Particles Systems
  67651. serializationObject.particleSystems = [];
  67652. for (index = 0; index < scene.particleSystems.length; index++) {
  67653. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  67654. }
  67655. // Lens flares
  67656. serializationObject.lensFlareSystems = [];
  67657. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  67658. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  67659. }
  67660. // Shadows
  67661. serializationObject.shadowGenerators = [];
  67662. for (index = 0; index < scene.lights.length; index++) {
  67663. light = scene.lights[index];
  67664. var shadowGenerator = light.getShadowGenerator();
  67665. if (shadowGenerator) {
  67666. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  67667. }
  67668. }
  67669. // Action Manager
  67670. if (scene.actionManager) {
  67671. serializationObject.actions = scene.actionManager.serialize("scene");
  67672. }
  67673. // Audio
  67674. serializationObject.sounds = [];
  67675. for (index = 0; index < scene.soundTracks.length; index++) {
  67676. var soundtrack = scene.soundTracks[index];
  67677. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  67678. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  67679. }
  67680. }
  67681. return serializationObject;
  67682. };
  67683. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  67684. if (withParents === void 0) { withParents = false; }
  67685. if (withChildren === void 0) { withChildren = false; }
  67686. var serializationObject = {};
  67687. SceneSerializer.ClearCache();
  67688. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  67689. if (withParents || withChildren) {
  67690. //deliberate for loop! not for each, appended should be processed as well.
  67691. for (var i = 0; i < toSerialize.length; ++i) {
  67692. if (withChildren) {
  67693. toSerialize[i].getDescendants().forEach(function (node) {
  67694. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  67695. toSerialize.push(node);
  67696. }
  67697. });
  67698. }
  67699. //make sure the array doesn't contain the object already
  67700. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  67701. toSerialize.push(toSerialize[i].parent);
  67702. }
  67703. }
  67704. }
  67705. toSerialize.forEach(function (mesh) {
  67706. finalizeSingleMesh(mesh, serializationObject);
  67707. });
  67708. return serializationObject;
  67709. };
  67710. return SceneSerializer;
  67711. }());
  67712. BABYLON.SceneSerializer = SceneSerializer;
  67713. })(BABYLON || (BABYLON = {}));
  67714. //# sourceMappingURL=babylon.sceneSerializer.js.map
  67715. var BABYLON;
  67716. (function (BABYLON) {
  67717. var ReflectionProbe = (function () {
  67718. function ReflectionProbe(name, size, scene, generateMipMaps) {
  67719. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67720. var _this = this;
  67721. this.name = name;
  67722. this._viewMatrix = BABYLON.Matrix.Identity();
  67723. this._target = BABYLON.Vector3.Zero();
  67724. this._add = BABYLON.Vector3.Zero();
  67725. this.invertYAxis = false;
  67726. this.position = BABYLON.Vector3.Zero();
  67727. this._scene = scene;
  67728. this._scene.reflectionProbes.push(this);
  67729. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  67730. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  67731. switch (faceIndex) {
  67732. case 0:
  67733. _this._add.copyFromFloats(1, 0, 0);
  67734. break;
  67735. case 1:
  67736. _this._add.copyFromFloats(-1, 0, 0);
  67737. break;
  67738. case 2:
  67739. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  67740. break;
  67741. case 3:
  67742. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  67743. break;
  67744. case 4:
  67745. _this._add.copyFromFloats(0, 0, 1);
  67746. break;
  67747. case 5:
  67748. _this._add.copyFromFloats(0, 0, -1);
  67749. break;
  67750. }
  67751. if (_this._attachedMesh) {
  67752. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  67753. }
  67754. _this.position.addToRef(_this._add, _this._target);
  67755. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  67756. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  67757. });
  67758. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  67759. scene.updateTransformMatrix(true);
  67760. });
  67761. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  67762. }
  67763. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  67764. get: function () {
  67765. return this._renderTargetTexture.samples;
  67766. },
  67767. set: function (value) {
  67768. this._renderTargetTexture.samples = value;
  67769. },
  67770. enumerable: true,
  67771. configurable: true
  67772. });
  67773. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  67774. get: function () {
  67775. return this._renderTargetTexture.refreshRate;
  67776. },
  67777. set: function (value) {
  67778. this._renderTargetTexture.refreshRate = value;
  67779. },
  67780. enumerable: true,
  67781. configurable: true
  67782. });
  67783. ReflectionProbe.prototype.getScene = function () {
  67784. return this._scene;
  67785. };
  67786. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  67787. get: function () {
  67788. return this._renderTargetTexture;
  67789. },
  67790. enumerable: true,
  67791. configurable: true
  67792. });
  67793. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  67794. get: function () {
  67795. return this._renderTargetTexture.renderList;
  67796. },
  67797. enumerable: true,
  67798. configurable: true
  67799. });
  67800. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  67801. this._attachedMesh = mesh;
  67802. };
  67803. /**
  67804. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67805. *
  67806. * @param renderingGroupId The rendering group id corresponding to its index
  67807. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67808. */
  67809. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67810. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67811. };
  67812. ReflectionProbe.prototype.dispose = function () {
  67813. var index = this._scene.reflectionProbes.indexOf(this);
  67814. if (index !== -1) {
  67815. // Remove from the scene if found
  67816. this._scene.reflectionProbes.splice(index, 1);
  67817. }
  67818. if (this._renderTargetTexture) {
  67819. this._renderTargetTexture.dispose();
  67820. this._renderTargetTexture = null;
  67821. }
  67822. };
  67823. return ReflectionProbe;
  67824. }());
  67825. BABYLON.ReflectionProbe = ReflectionProbe;
  67826. })(BABYLON || (BABYLON = {}));
  67827. //# sourceMappingURL=babylon.reflectionProbe.js.map
  67828. var BABYLON;
  67829. (function (BABYLON) {
  67830. var Layer = (function () {
  67831. function Layer(name, imgUrl, scene, isBackground, color) {
  67832. this.name = name;
  67833. this.scale = new BABYLON.Vector2(1, 1);
  67834. this.offset = new BABYLON.Vector2(0, 0);
  67835. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  67836. this.layerMask = 0x0FFFFFFF;
  67837. this._vertexBuffers = {};
  67838. // Events
  67839. /**
  67840. * An event triggered when the layer is disposed.
  67841. * @type {BABYLON.Observable}
  67842. */
  67843. this.onDisposeObservable = new BABYLON.Observable();
  67844. /**
  67845. * An event triggered before rendering the scene
  67846. * @type {BABYLON.Observable}
  67847. */
  67848. this.onBeforeRenderObservable = new BABYLON.Observable();
  67849. /**
  67850. * An event triggered after rendering the scene
  67851. * @type {BABYLON.Observable}
  67852. */
  67853. this.onAfterRenderObservable = new BABYLON.Observable();
  67854. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  67855. this.isBackground = isBackground === undefined ? true : isBackground;
  67856. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  67857. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67858. this._scene.layers.push(this);
  67859. var engine = this._scene.getEngine();
  67860. // VBO
  67861. var vertices = [];
  67862. vertices.push(1, 1);
  67863. vertices.push(-1, 1);
  67864. vertices.push(-1, -1);
  67865. vertices.push(1, -1);
  67866. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67867. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  67868. // Indices
  67869. var indices = [];
  67870. indices.push(0);
  67871. indices.push(1);
  67872. indices.push(2);
  67873. indices.push(0);
  67874. indices.push(2);
  67875. indices.push(3);
  67876. this._indexBuffer = engine.createIndexBuffer(indices);
  67877. // Effects
  67878. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  67879. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  67880. }
  67881. Object.defineProperty(Layer.prototype, "onDispose", {
  67882. set: function (callback) {
  67883. if (this._onDisposeObserver) {
  67884. this.onDisposeObservable.remove(this._onDisposeObserver);
  67885. }
  67886. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  67887. },
  67888. enumerable: true,
  67889. configurable: true
  67890. });
  67891. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  67892. set: function (callback) {
  67893. if (this._onBeforeRenderObserver) {
  67894. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67895. }
  67896. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67897. },
  67898. enumerable: true,
  67899. configurable: true
  67900. });
  67901. Object.defineProperty(Layer.prototype, "onAfterRender", {
  67902. set: function (callback) {
  67903. if (this._onAfterRenderObserver) {
  67904. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67905. }
  67906. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67907. },
  67908. enumerable: true,
  67909. configurable: true
  67910. });
  67911. Layer.prototype.render = function () {
  67912. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  67913. // Check
  67914. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  67915. return;
  67916. var engine = this._scene.getEngine();
  67917. this.onBeforeRenderObservable.notifyObservers(this);
  67918. // Render
  67919. engine.enableEffect(currentEffect);
  67920. engine.setState(false);
  67921. // Texture
  67922. currentEffect.setTexture("textureSampler", this.texture);
  67923. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  67924. // Color
  67925. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  67926. // Scale / offset
  67927. currentEffect.setVector2("offset", this.offset);
  67928. currentEffect.setVector2("scale", this.scale);
  67929. // VBOs
  67930. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  67931. // Draw order
  67932. if (!this.alphaTest) {
  67933. engine.setAlphaMode(this.alphaBlendingMode);
  67934. engine.draw(true, 0, 6);
  67935. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67936. }
  67937. else {
  67938. engine.draw(true, 0, 6);
  67939. }
  67940. this.onAfterRenderObservable.notifyObservers(this);
  67941. };
  67942. Layer.prototype.dispose = function () {
  67943. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67944. if (vertexBuffer) {
  67945. vertexBuffer.dispose();
  67946. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67947. }
  67948. if (this._indexBuffer) {
  67949. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67950. this._indexBuffer = null;
  67951. }
  67952. if (this.texture) {
  67953. this.texture.dispose();
  67954. this.texture = null;
  67955. }
  67956. // Remove from scene
  67957. var index = this._scene.layers.indexOf(this);
  67958. this._scene.layers.splice(index, 1);
  67959. // Callback
  67960. this.onDisposeObservable.notifyObservers(this);
  67961. this.onDisposeObservable.clear();
  67962. this.onAfterRenderObservable.clear();
  67963. this.onBeforeRenderObservable.clear();
  67964. };
  67965. return Layer;
  67966. }());
  67967. BABYLON.Layer = Layer;
  67968. })(BABYLON || (BABYLON = {}));
  67969. //# sourceMappingURL=babylon.layer.js.map
  67970. var BABYLON;
  67971. (function (BABYLON) {
  67972. var TextureTools = (function () {
  67973. function TextureTools() {
  67974. }
  67975. /**
  67976. * Uses the GPU to create a copy texture rescaled at a given size
  67977. * @param texture Texture to copy from
  67978. * @param width Desired width
  67979. * @param height Desired height
  67980. * @return Generated texture
  67981. */
  67982. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  67983. if (useBilinearMode === void 0) { useBilinearMode = true; }
  67984. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  67985. var scene = texture.getScene();
  67986. var engine = scene.getEngine();
  67987. rtt.wrapU = texture.wrapU;
  67988. rtt.wrapV = texture.wrapV;
  67989. rtt.uOffset = texture.uOffset;
  67990. rtt.vOffset = texture.vOffset;
  67991. rtt.uScale = texture.uScale;
  67992. rtt.vScale = texture.vScale;
  67993. rtt.uAng = texture.uAng;
  67994. rtt.vAng = texture.vAng;
  67995. rtt.wAng = texture.wAng;
  67996. rtt.coordinatesIndex = texture.coordinatesIndex;
  67997. rtt.level = texture.level;
  67998. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  67999. rtt._texture.isReady = false;
  68000. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68001. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68002. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68003. passPostProcess.getEffect().executeWhenCompiled(function () {
  68004. passPostProcess.onApply = function (effect) {
  68005. effect.setTexture("textureSampler", texture);
  68006. };
  68007. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  68008. engine.unBindFramebuffer(rtt.getInternalTexture());
  68009. rtt.disposeFramebufferObjects();
  68010. passPostProcess.dispose();
  68011. rtt._texture.isReady = true;
  68012. });
  68013. return rtt;
  68014. };
  68015. return TextureTools;
  68016. }());
  68017. BABYLON.TextureTools = TextureTools;
  68018. })(BABYLON || (BABYLON = {}));
  68019. //# sourceMappingURL=babylon.textureTools.js.map
  68020. 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}"};
  68021. 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};"};
  68022. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  68023. module.exports = BABYLON;
  68024. };