babylon.max.js 3.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = function (right) {
  417. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  418. };
  419. /**
  420. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2(1, 1)
  845. */
  846. Vector2.One = function () {
  847. return new Vector2(1, 1);
  848. };
  849. /**
  850. * Returns a new Vector2 set from the passed index element of the passed array.
  851. */
  852. Vector2.FromArray = function (array, offset) {
  853. if (offset === void 0) { offset = 0; }
  854. return new Vector2(array[offset], array[offset + 1]);
  855. };
  856. /**
  857. * Sets "result" from the passed index element of the passed array.
  858. */
  859. Vector2.FromArrayToRef = function (array, offset, result) {
  860. result.x = array[offset];
  861. result.y = array[offset + 1];
  862. };
  863. /**
  864. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  865. */
  866. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  867. var squared = amount * amount;
  868. var cubed = amount * squared;
  869. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  870. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  871. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  872. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  873. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  874. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  875. return new Vector2(x, y);
  876. };
  877. /**
  878. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  879. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  880. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  881. */
  882. Vector2.Clamp = function (value, min, max) {
  883. var x = value.x;
  884. x = (x > max.x) ? max.x : x;
  885. x = (x < min.x) ? min.x : x;
  886. var y = value.y;
  887. y = (y > max.y) ? max.y : y;
  888. y = (y < min.y) ? min.y : y;
  889. return new Vector2(x, y);
  890. };
  891. /**
  892. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  893. */
  894. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  895. var squared = amount * amount;
  896. var cubed = amount * squared;
  897. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  898. var part2 = (-2.0 * cubed) + (3.0 * squared);
  899. var part3 = (cubed - (2.0 * squared)) + amount;
  900. var part4 = cubed - squared;
  901. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  902. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  903. return new Vector2(x, y);
  904. };
  905. /**
  906. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  907. */
  908. Vector2.Lerp = function (start, end, amount) {
  909. var x = start.x + ((end.x - start.x) * amount);
  910. var y = start.y + ((end.y - start.y) * amount);
  911. return new Vector2(x, y);
  912. };
  913. /**
  914. * Returns the dot product (float) of the vector "left" and the vector "right".
  915. */
  916. Vector2.Dot = function (left, right) {
  917. return left.x * right.x + left.y * right.y;
  918. };
  919. /**
  920. * Returns a new Vector2 equal to the normalized passed vector.
  921. */
  922. Vector2.Normalize = function (vector) {
  923. var newVector = vector.clone();
  924. newVector.normalize();
  925. return newVector;
  926. };
  927. /**
  928. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  929. */
  930. Vector2.Minimize = function (left, right) {
  931. var x = (left.x < right.x) ? left.x : right.x;
  932. var y = (left.y < right.y) ? left.y : right.y;
  933. return new Vector2(x, y);
  934. };
  935. /**
  936. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  937. */
  938. Vector2.Maximize = function (left, right) {
  939. var x = (left.x > right.x) ? left.x : right.x;
  940. var y = (left.y > right.y) ? left.y : right.y;
  941. return new Vector2(x, y);
  942. };
  943. /**
  944. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  945. */
  946. Vector2.Transform = function (vector, transformation) {
  947. var r = Vector2.Zero();
  948. Vector2.TransformToRef(vector, transformation, r);
  949. return r;
  950. };
  951. /**
  952. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  953. */
  954. Vector2.TransformToRef = function (vector, transformation, result) {
  955. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  956. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  957. result.x = x;
  958. result.y = y;
  959. };
  960. /**
  961. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  962. */
  963. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  964. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  965. var sign = a < 0 ? -1 : 1;
  966. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  967. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  968. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  969. };
  970. /**
  971. * Returns the distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.Distance = function (value1, value2) {
  974. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  975. };
  976. /**
  977. * Returns the squared distance (float) between the vectors "value1" and "value2".
  978. */
  979. Vector2.DistanceSquared = function (value1, value2) {
  980. var x = value1.x - value2.x;
  981. var y = value1.y - value2.y;
  982. return (x * x) + (y * y);
  983. };
  984. /**
  985. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  986. */
  987. Vector2.Center = function (value1, value2) {
  988. var center = value1.add(value2);
  989. center.scaleInPlace(0.5);
  990. return center;
  991. };
  992. /**
  993. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  994. */
  995. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  996. var l2 = Vector2.DistanceSquared(segA, segB);
  997. if (l2 === 0.0) {
  998. return Vector2.Distance(p, segA);
  999. }
  1000. var v = segB.subtract(segA);
  1001. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1002. var proj = segA.add(v.multiplyByFloats(t, t));
  1003. return Vector2.Distance(p, proj);
  1004. };
  1005. return Vector2;
  1006. }());
  1007. BABYLON.Vector2 = Vector2;
  1008. var Vector3 = (function () {
  1009. /**
  1010. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1011. * A Vector3 is the main object used in 3D geometry.
  1012. * It can represent etiher the coordinates of a point the space, either a direction.
  1013. */
  1014. function Vector3(x, y, z) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. }
  1019. /**
  1020. * Returns a string with the Vector3 coordinates.
  1021. */
  1022. Vector3.prototype.toString = function () {
  1023. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1024. };
  1025. /**
  1026. * Returns the string "Vector3"
  1027. */
  1028. Vector3.prototype.getClassName = function () {
  1029. return "Vector3";
  1030. };
  1031. /**
  1032. * Returns the Vector hash code.
  1033. */
  1034. Vector3.prototype.getHashCode = function () {
  1035. var hash = this.x || 0;
  1036. hash = (hash * 397) ^ (this.y || 0);
  1037. hash = (hash * 397) ^ (this.z || 0);
  1038. return hash;
  1039. };
  1040. // Operators
  1041. /**
  1042. * Returns a new array with three elements : the coordinates the Vector3.
  1043. */
  1044. Vector3.prototype.asArray = function () {
  1045. var result = [];
  1046. this.toArray(result, 0);
  1047. return result;
  1048. };
  1049. /**
  1050. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1051. * Returns the Vector3.
  1052. */
  1053. Vector3.prototype.toArray = function (array, index) {
  1054. if (index === void 0) { index = 0; }
  1055. array[index] = this.x;
  1056. array[index + 1] = this.y;
  1057. array[index + 2] = this.z;
  1058. return this;
  1059. };
  1060. /**
  1061. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1062. */
  1063. Vector3.prototype.toQuaternion = function () {
  1064. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1065. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1066. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1067. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1068. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1069. var cosy = Math.cos(this.y * 0.5);
  1070. var siny = Math.sin(this.y * 0.5);
  1071. result.x = coszMinusx * siny;
  1072. result.y = -sinzMinusx * siny;
  1073. result.z = sinxPlusz * cosy;
  1074. result.w = cosxPlusz * cosy;
  1075. return result;
  1076. };
  1077. /**
  1078. * Adds the passed vector to the current Vector3.
  1079. * Returns the updated Vector3.
  1080. */
  1081. Vector3.prototype.addInPlace = function (otherVector) {
  1082. this.x += otherVector.x;
  1083. this.y += otherVector.y;
  1084. this.z += otherVector.z;
  1085. return this;
  1086. };
  1087. /**
  1088. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1089. */
  1090. Vector3.prototype.add = function (otherVector) {
  1091. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1092. };
  1093. /**
  1094. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1095. * Returns the current Vector3.
  1096. */
  1097. Vector3.prototype.addToRef = function (otherVector, result) {
  1098. result.x = this.x + otherVector.x;
  1099. result.y = this.y + otherVector.y;
  1100. result.z = this.z + otherVector.z;
  1101. return this;
  1102. };
  1103. /**
  1104. * Subtract the passed vector from the current Vector3.
  1105. * Returns the updated Vector3.
  1106. */
  1107. Vector3.prototype.subtractInPlace = function (otherVector) {
  1108. this.x -= otherVector.x;
  1109. this.y -= otherVector.y;
  1110. this.z -= otherVector.z;
  1111. return this;
  1112. };
  1113. /**
  1114. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1115. */
  1116. Vector3.prototype.subtract = function (otherVector) {
  1117. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1118. };
  1119. /**
  1120. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1121. * Returns the current Vector3.
  1122. */
  1123. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1124. result.x = this.x - otherVector.x;
  1125. result.y = this.y - otherVector.y;
  1126. result.z = this.z - otherVector.z;
  1127. return this;
  1128. };
  1129. /**
  1130. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1131. */
  1132. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1133. return new Vector3(this.x - x, this.y - y, this.z - z);
  1134. };
  1135. /**
  1136. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1137. * Returns the current Vector3.
  1138. */
  1139. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1140. result.x = this.x - x;
  1141. result.y = this.y - y;
  1142. result.z = this.z - z;
  1143. return this;
  1144. };
  1145. /**
  1146. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1147. */
  1148. Vector3.prototype.negate = function () {
  1149. return new Vector3(-this.x, -this.y, -this.z);
  1150. };
  1151. /**
  1152. * Multiplies the Vector3 coordinates by the float "scale".
  1153. * Returns the updated Vector3.
  1154. */
  1155. Vector3.prototype.scaleInPlace = function (scale) {
  1156. this.x *= scale;
  1157. this.y *= scale;
  1158. this.z *= scale;
  1159. return this;
  1160. };
  1161. /**
  1162. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1163. */
  1164. Vector3.prototype.scale = function (scale) {
  1165. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1166. };
  1167. /**
  1168. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1169. * Returns the current Vector3.
  1170. */
  1171. Vector3.prototype.scaleToRef = function (scale, result) {
  1172. result.x = this.x * scale;
  1173. result.y = this.y * scale;
  1174. result.z = this.z * scale;
  1175. return this;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1179. */
  1180. Vector3.prototype.equals = function (otherVector) {
  1181. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1182. };
  1183. /**
  1184. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1185. */
  1186. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1187. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1188. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1189. };
  1190. /**
  1191. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1192. */
  1193. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1194. return this.x === x && this.y === y && this.z === z;
  1195. };
  1196. /**
  1197. * Muliplies the current Vector3 coordinates by the passed ones.
  1198. * Returns the updated Vector3.
  1199. */
  1200. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1201. this.x *= otherVector.x;
  1202. this.y *= otherVector.y;
  1203. this.z *= otherVector.z;
  1204. return this;
  1205. };
  1206. /**
  1207. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1208. */
  1209. Vector3.prototype.multiply = function (otherVector) {
  1210. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1211. };
  1212. /**
  1213. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1214. * Returns the current Vector3.
  1215. */
  1216. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1217. result.x = this.x * otherVector.x;
  1218. result.y = this.y * otherVector.y;
  1219. result.z = this.z * otherVector.z;
  1220. return this;
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1224. */
  1225. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1226. return new Vector3(this.x * x, this.y * y, this.z * z);
  1227. };
  1228. /**
  1229. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1230. */
  1231. Vector3.prototype.divide = function (otherVector) {
  1232. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1233. };
  1234. /**
  1235. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1236. * Returns the current Vector3.
  1237. */
  1238. Vector3.prototype.divideToRef = function (otherVector, result) {
  1239. result.x = this.x / otherVector.x;
  1240. result.y = this.y / otherVector.y;
  1241. result.z = this.z / otherVector.z;
  1242. return this;
  1243. };
  1244. /**
  1245. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1246. * Returns the updated Vector3.
  1247. */
  1248. Vector3.prototype.MinimizeInPlace = function (other) {
  1249. if (other.x < this.x)
  1250. this.x = other.x;
  1251. if (other.y < this.y)
  1252. this.y = other.y;
  1253. if (other.z < this.z)
  1254. this.z = other.z;
  1255. return this;
  1256. };
  1257. /**
  1258. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1259. * Returns the updated Vector3.
  1260. */
  1261. Vector3.prototype.MaximizeInPlace = function (other) {
  1262. if (other.x > this.x)
  1263. this.x = other.x;
  1264. if (other.y > this.y)
  1265. this.y = other.y;
  1266. if (other.z > this.z)
  1267. this.z = other.z;
  1268. return this;
  1269. };
  1270. // Properties
  1271. /**
  1272. * Returns the length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.length = function () {
  1275. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. /**
  1278. * Returns the squared length of the Vector3 (float).
  1279. */
  1280. Vector3.prototype.lengthSquared = function () {
  1281. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1282. };
  1283. // Methods
  1284. /**
  1285. * Normalize the current Vector3.
  1286. * Returns the updated Vector3.
  1287. */
  1288. Vector3.prototype.normalize = function () {
  1289. var len = this.length();
  1290. if (len === 0 || len === 1.0)
  1291. return this;
  1292. var num = 1.0 / len;
  1293. this.x *= num;
  1294. this.y *= num;
  1295. this.z *= num;
  1296. return this;
  1297. };
  1298. /**
  1299. * Returns a new Vector3 copied from the current Vector3.
  1300. */
  1301. Vector3.prototype.clone = function () {
  1302. return new Vector3(this.x, this.y, this.z);
  1303. };
  1304. /**
  1305. * Copies the passed vector coordinates to the current Vector3 ones.
  1306. * Returns the updated Vector3.
  1307. */
  1308. Vector3.prototype.copyFrom = function (source) {
  1309. this.x = source.x;
  1310. this.y = source.y;
  1311. this.z = source.z;
  1312. return this;
  1313. };
  1314. /**
  1315. * Copies the passed floats to the current Vector3 coordinates.
  1316. * Returns the updated Vector3.
  1317. */
  1318. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1319. this.x = x;
  1320. this.y = y;
  1321. this.z = z;
  1322. return this;
  1323. };
  1324. /**
  1325. * Copies the passed floats to the current Vector3 coordinates.
  1326. * Returns the updated Vector3.
  1327. */
  1328. Vector3.prototype.set = function (x, y, z) {
  1329. return this.copyFromFloats(x, y, z);
  1330. };
  1331. // Statics
  1332. /**
  1333. *
  1334. */
  1335. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1336. var d0 = Vector3.Dot(vector0, axis) - size;
  1337. var d1 = Vector3.Dot(vector1, axis) - size;
  1338. var s = d0 / (d0 - d1);
  1339. return s;
  1340. };
  1341. /**
  1342. * Returns a new Vector3 set from the index "offset" of the passed array.
  1343. */
  1344. Vector3.FromArray = function (array, offset) {
  1345. if (!offset) {
  1346. offset = 0;
  1347. }
  1348. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1352. * This function is deprecated. Use FromArray instead.
  1353. */
  1354. Vector3.FromFloatArray = function (array, offset) {
  1355. return Vector3.FromArray(array, offset);
  1356. };
  1357. /**
  1358. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1359. */
  1360. Vector3.FromArrayToRef = function (array, offset, result) {
  1361. result.x = array[offset];
  1362. result.y = array[offset + 1];
  1363. result.z = array[offset + 2];
  1364. };
  1365. /**
  1366. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1367. * This function is deprecated. Use FromArrayToRef instead.
  1368. */
  1369. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1370. return Vector3.FromArrayToRef(array, offset, result);
  1371. };
  1372. /**
  1373. * Sets the passed vector "result" with the passed floats.
  1374. */
  1375. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1376. result.x = x;
  1377. result.y = y;
  1378. result.z = z;
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1382. */
  1383. Vector3.Zero = function () {
  1384. return new Vector3(0.0, 0.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1388. */
  1389. Vector3.One = function () {
  1390. return new Vector3(1.0, 1.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1394. */
  1395. Vector3.Up = function () {
  1396. return new Vector3(0.0, 1.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1400. */
  1401. Vector3.Forward = function () {
  1402. return new Vector3(0.0, 0.0, 1.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1406. */
  1407. Vector3.Right = function () {
  1408. return new Vector3(1.0, 0.0, 0.0);
  1409. };
  1410. /**
  1411. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1412. */
  1413. Vector3.Left = function () {
  1414. return new Vector3(-1.0, 0.0, 0.0);
  1415. };
  1416. /**
  1417. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1418. * This method computes tranformed coordinates only, not transformed direction vectors.
  1419. */
  1420. Vector3.TransformCoordinates = function (vector, transformation) {
  1421. var result = Vector3.Zero();
  1422. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1423. return result;
  1424. };
  1425. /**
  1426. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1427. * This method computes tranformed coordinates only, not transformed direction vectors.
  1428. */
  1429. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1430. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1431. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1432. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1433. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1434. result.x = x / w;
  1435. result.y = y / w;
  1436. result.z = z / w;
  1437. };
  1438. /**
  1439. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1440. * This method computes tranformed coordinates only, not transformed direction vectors.
  1441. */
  1442. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1443. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1444. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1445. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1446. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1447. result.x = rx / rw;
  1448. result.y = ry / rw;
  1449. result.z = rz / rw;
  1450. };
  1451. /**
  1452. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1453. * This methods computes transformed normalized direction vectors only.
  1454. */
  1455. Vector3.TransformNormal = function (vector, transformation) {
  1456. var result = Vector3.Zero();
  1457. Vector3.TransformNormalToRef(vector, transformation, result);
  1458. return result;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1467. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1468. result.x = x;
  1469. result.y = y;
  1470. result.z = z;
  1471. };
  1472. /**
  1473. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1474. * This methods computes transformed normalized direction vectors only.
  1475. */
  1476. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1477. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1478. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1479. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1480. };
  1481. /**
  1482. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1483. */
  1484. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1485. var squared = amount * amount;
  1486. var cubed = amount * squared;
  1487. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1488. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1489. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1490. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1491. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1492. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1493. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1494. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1495. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1496. return new Vector3(x, y, z);
  1497. };
  1498. /**
  1499. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1500. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1501. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1502. */
  1503. Vector3.Clamp = function (value, min, max) {
  1504. var x = value.x;
  1505. x = (x > max.x) ? max.x : x;
  1506. x = (x < min.x) ? min.x : x;
  1507. var y = value.y;
  1508. y = (y > max.y) ? max.y : y;
  1509. y = (y < min.y) ? min.y : y;
  1510. var z = value.z;
  1511. z = (z > max.z) ? max.z : z;
  1512. z = (z < min.z) ? min.z : z;
  1513. return new Vector3(x, y, z);
  1514. };
  1515. /**
  1516. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1517. */
  1518. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1519. var squared = amount * amount;
  1520. var cubed = amount * squared;
  1521. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1522. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1523. var part3 = (cubed - (2.0 * squared)) + amount;
  1524. var part4 = cubed - squared;
  1525. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1526. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1527. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1528. return new Vector3(x, y, z);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1532. */
  1533. Vector3.Lerp = function (start, end, amount) {
  1534. var result = new Vector3(0, 0, 0);
  1535. Vector3.LerpToRef(start, end, amount, result);
  1536. return result;
  1537. };
  1538. /**
  1539. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1540. */
  1541. Vector3.LerpToRef = function (start, end, amount, result) {
  1542. result.x = start.x + ((end.x - start.x) * amount);
  1543. result.y = start.y + ((end.y - start.y) * amount);
  1544. result.z = start.z + ((end.z - start.z) * amount);
  1545. };
  1546. /**
  1547. * Returns the dot product (float) between the vectors "left" and "right".
  1548. */
  1549. Vector3.Dot = function (left, right) {
  1550. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1551. };
  1552. /**
  1553. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1554. * The cross product is then orthogonal to both "left" and "right".
  1555. */
  1556. Vector3.Cross = function (left, right) {
  1557. var result = Vector3.Zero();
  1558. Vector3.CrossToRef(left, right, result);
  1559. return result;
  1560. };
  1561. /**
  1562. * Sets the passed vector "result" with the cross product of "left" and "right".
  1563. * The cross product is then orthogonal to both "left" and "right".
  1564. */
  1565. Vector3.CrossToRef = function (left, right, result) {
  1566. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1567. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1568. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1569. result.copyFrom(MathTmp.Vector3[0]);
  1570. };
  1571. /**
  1572. * Returns a new Vector3 as the normalization of the passed vector.
  1573. */
  1574. Vector3.Normalize = function (vector) {
  1575. var result = Vector3.Zero();
  1576. Vector3.NormalizeToRef(vector, result);
  1577. return result;
  1578. };
  1579. /**
  1580. * Sets the passed vector "result" with the normalization of the passed first vector.
  1581. */
  1582. Vector3.NormalizeToRef = function (vector, result) {
  1583. result.copyFrom(vector);
  1584. result.normalize();
  1585. };
  1586. Vector3.Project = function (vector, world, transform, viewport) {
  1587. var cw = viewport.width;
  1588. var ch = viewport.height;
  1589. var cx = viewport.x;
  1590. var cy = viewport.y;
  1591. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1592. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1593. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1594. world.multiplyToRef(transform, matrix);
  1595. matrix.multiplyToRef(viewportMatrix, matrix);
  1596. return Vector3.TransformCoordinates(vector, matrix);
  1597. };
  1598. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1599. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1600. world.multiplyToRef(transform, matrix);
  1601. matrix.invert();
  1602. source.x = source.x / viewportWidth * 2 - 1;
  1603. source.y = -(source.y / viewportHeight * 2 - 1);
  1604. var vector = Vector3.TransformCoordinates(source, matrix);
  1605. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1606. if (MathTools.WithinEpsilon(num, 1.0)) {
  1607. vector = vector.scale(1.0 / num);
  1608. }
  1609. return vector;
  1610. };
  1611. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1612. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1613. world.multiplyToRef(view, matrix);
  1614. matrix.multiplyToRef(projection, matrix);
  1615. matrix.invert();
  1616. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1617. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1618. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1619. if (MathTools.WithinEpsilon(num, 1.0)) {
  1620. vector = vector.scale(1.0 / num);
  1621. }
  1622. return vector;
  1623. };
  1624. Vector3.Minimize = function (left, right) {
  1625. var min = left.clone();
  1626. min.MinimizeInPlace(right);
  1627. return min;
  1628. };
  1629. Vector3.Maximize = function (left, right) {
  1630. var max = left.clone();
  1631. max.MaximizeInPlace(right);
  1632. return max;
  1633. };
  1634. /**
  1635. * Returns the distance (float) between the vectors "value1" and "value2".
  1636. */
  1637. Vector3.Distance = function (value1, value2) {
  1638. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1639. };
  1640. /**
  1641. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1642. */
  1643. Vector3.DistanceSquared = function (value1, value2) {
  1644. var x = value1.x - value2.x;
  1645. var y = value1.y - value2.y;
  1646. var z = value1.z - value2.z;
  1647. return (x * x) + (y * y) + (z * z);
  1648. };
  1649. /**
  1650. * Returns a new Vector3 located at the center between "value1" and "value2".
  1651. */
  1652. Vector3.Center = function (value1, value2) {
  1653. var center = value1.add(value2);
  1654. center.scaleInPlace(0.5);
  1655. return center;
  1656. };
  1657. /**
  1658. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1659. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1660. * to something in order to rotate it from its local system to the given target system.
  1661. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1662. * Returns a new Vector3.
  1663. */
  1664. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1665. var rotation = Vector3.Zero();
  1666. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1667. return rotation;
  1668. };
  1669. /**
  1670. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1671. */
  1672. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1673. var quat = MathTmp.Quaternion[0];
  1674. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1675. quat.toEulerAnglesToRef(ref);
  1676. };
  1677. return Vector3;
  1678. }());
  1679. BABYLON.Vector3 = Vector3;
  1680. //Vector4 class created for EulerAngle class conversion to Quaternion
  1681. var Vector4 = (function () {
  1682. /**
  1683. * Creates a Vector4 object from the passed floats.
  1684. */
  1685. function Vector4(x, y, z, w) {
  1686. this.x = x;
  1687. this.y = y;
  1688. this.z = z;
  1689. this.w = w;
  1690. }
  1691. /**
  1692. * Returns the string with the Vector4 coordinates.
  1693. */
  1694. Vector4.prototype.toString = function () {
  1695. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1696. };
  1697. /**
  1698. * Returns the string "Vector4".
  1699. */
  1700. Vector4.prototype.getClassName = function () {
  1701. return "Vector4";
  1702. };
  1703. /**
  1704. * Returns the Vector4 hash code.
  1705. */
  1706. Vector4.prototype.getHashCode = function () {
  1707. var hash = this.x || 0;
  1708. hash = (hash * 397) ^ (this.y || 0);
  1709. hash = (hash * 397) ^ (this.z || 0);
  1710. hash = (hash * 397) ^ (this.w || 0);
  1711. return hash;
  1712. };
  1713. // Operators
  1714. /**
  1715. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1716. */
  1717. Vector4.prototype.asArray = function () {
  1718. var result = [];
  1719. this.toArray(result, 0);
  1720. return result;
  1721. };
  1722. /**
  1723. * Populates the passed array from the passed index with the Vector4 coordinates.
  1724. * Returns the Vector4.
  1725. */
  1726. Vector4.prototype.toArray = function (array, index) {
  1727. if (index === undefined) {
  1728. index = 0;
  1729. }
  1730. array[index] = this.x;
  1731. array[index + 1] = this.y;
  1732. array[index + 2] = this.z;
  1733. array[index + 3] = this.w;
  1734. return this;
  1735. };
  1736. /**
  1737. * Adds the passed vector to the current Vector4.
  1738. * Returns the updated Vector4.
  1739. */
  1740. Vector4.prototype.addInPlace = function (otherVector) {
  1741. this.x += otherVector.x;
  1742. this.y += otherVector.y;
  1743. this.z += otherVector.z;
  1744. this.w += otherVector.w;
  1745. return this;
  1746. };
  1747. /**
  1748. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1749. */
  1750. Vector4.prototype.add = function (otherVector) {
  1751. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1752. };
  1753. /**
  1754. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1755. * Returns the current Vector4.
  1756. */
  1757. Vector4.prototype.addToRef = function (otherVector, result) {
  1758. result.x = this.x + otherVector.x;
  1759. result.y = this.y + otherVector.y;
  1760. result.z = this.z + otherVector.z;
  1761. result.w = this.w + otherVector.w;
  1762. return this;
  1763. };
  1764. /**
  1765. * Subtract in place the passed vector from the current Vector4.
  1766. * Returns the updated Vector4.
  1767. */
  1768. Vector4.prototype.subtractInPlace = function (otherVector) {
  1769. this.x -= otherVector.x;
  1770. this.y -= otherVector.y;
  1771. this.z -= otherVector.z;
  1772. this.w -= otherVector.w;
  1773. return this;
  1774. };
  1775. /**
  1776. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1777. */
  1778. Vector4.prototype.subtract = function (otherVector) {
  1779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1780. };
  1781. /**
  1782. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1783. * Returns the current Vector4.
  1784. */
  1785. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1786. result.x = this.x - otherVector.x;
  1787. result.y = this.y - otherVector.y;
  1788. result.z = this.z - otherVector.z;
  1789. result.w = this.w - otherVector.w;
  1790. return this;
  1791. };
  1792. /**
  1793. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1794. */
  1795. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1796. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1797. };
  1798. /**
  1799. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1800. * Returns the current Vector4.
  1801. */
  1802. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1803. result.x = this.x - x;
  1804. result.y = this.y - y;
  1805. result.z = this.z - z;
  1806. result.w = this.w - w;
  1807. return this;
  1808. };
  1809. /**
  1810. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1811. */
  1812. Vector4.prototype.negate = function () {
  1813. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1814. };
  1815. /**
  1816. * Multiplies the current Vector4 coordinates by scale (float).
  1817. * Returns the updated Vector4.
  1818. */
  1819. Vector4.prototype.scaleInPlace = function (scale) {
  1820. this.x *= scale;
  1821. this.y *= scale;
  1822. this.z *= scale;
  1823. this.w *= scale;
  1824. return this;
  1825. };
  1826. /**
  1827. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1828. */
  1829. Vector4.prototype.scale = function (scale) {
  1830. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1831. };
  1832. /**
  1833. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1834. * Returns the current Vector4.
  1835. */
  1836. Vector4.prototype.scaleToRef = function (scale, result) {
  1837. result.x = this.x * scale;
  1838. result.y = this.y * scale;
  1839. result.z = this.z * scale;
  1840. result.w = this.w * scale;
  1841. return this;
  1842. };
  1843. /**
  1844. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1845. */
  1846. Vector4.prototype.equals = function (otherVector) {
  1847. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1848. };
  1849. /**
  1850. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1851. */
  1852. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1853. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1854. return otherVector
  1855. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1856. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1857. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1858. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1859. };
  1860. /**
  1861. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1862. */
  1863. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1864. return this.x === x && this.y === y && this.z === z && this.w === w;
  1865. };
  1866. /**
  1867. * Multiplies in place the current Vector4 by the passed one.
  1868. * Returns the updated Vector4.
  1869. */
  1870. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1871. this.x *= otherVector.x;
  1872. this.y *= otherVector.y;
  1873. this.z *= otherVector.z;
  1874. this.w *= otherVector.w;
  1875. return this;
  1876. };
  1877. /**
  1878. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1879. */
  1880. Vector4.prototype.multiply = function (otherVector) {
  1881. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1882. };
  1883. /**
  1884. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1885. * Returns the current Vector4.
  1886. */
  1887. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1888. result.x = this.x * otherVector.x;
  1889. result.y = this.y * otherVector.y;
  1890. result.z = this.z * otherVector.z;
  1891. result.w = this.w * otherVector.w;
  1892. return this;
  1893. };
  1894. /**
  1895. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1896. */
  1897. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1898. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1899. };
  1900. /**
  1901. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1902. */
  1903. Vector4.prototype.divide = function (otherVector) {
  1904. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1905. };
  1906. /**
  1907. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1908. * Returns the current Vector4.
  1909. */
  1910. Vector4.prototype.divideToRef = function (otherVector, result) {
  1911. result.x = this.x / otherVector.x;
  1912. result.y = this.y / otherVector.y;
  1913. result.z = this.z / otherVector.z;
  1914. result.w = this.w / otherVector.w;
  1915. return this;
  1916. };
  1917. /**
  1918. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1919. */
  1920. Vector4.prototype.MinimizeInPlace = function (other) {
  1921. if (other.x < this.x)
  1922. this.x = other.x;
  1923. if (other.y < this.y)
  1924. this.y = other.y;
  1925. if (other.z < this.z)
  1926. this.z = other.z;
  1927. if (other.w < this.w)
  1928. this.w = other.w;
  1929. return this;
  1930. };
  1931. /**
  1932. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1933. */
  1934. Vector4.prototype.MaximizeInPlace = function (other) {
  1935. if (other.x > this.x)
  1936. this.x = other.x;
  1937. if (other.y > this.y)
  1938. this.y = other.y;
  1939. if (other.z > this.z)
  1940. this.z = other.z;
  1941. if (other.w > this.w)
  1942. this.w = other.w;
  1943. return this;
  1944. };
  1945. // Properties
  1946. /**
  1947. * Returns the Vector4 length (float).
  1948. */
  1949. Vector4.prototype.length = function () {
  1950. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1951. };
  1952. /**
  1953. * Returns the Vector4 squared length (float).
  1954. */
  1955. Vector4.prototype.lengthSquared = function () {
  1956. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1957. };
  1958. // Methods
  1959. /**
  1960. * Normalizes in place the Vector4.
  1961. * Returns the updated Vector4.
  1962. */
  1963. Vector4.prototype.normalize = function () {
  1964. var len = this.length();
  1965. if (len === 0)
  1966. return this;
  1967. var num = 1.0 / len;
  1968. this.x *= num;
  1969. this.y *= num;
  1970. this.z *= num;
  1971. this.w *= num;
  1972. return this;
  1973. };
  1974. /**
  1975. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1976. */
  1977. Vector4.prototype.toVector3 = function () {
  1978. return new Vector3(this.x, this.y, this.z);
  1979. };
  1980. /**
  1981. * Returns a new Vector4 copied from the current one.
  1982. */
  1983. Vector4.prototype.clone = function () {
  1984. return new Vector4(this.x, this.y, this.z, this.w);
  1985. };
  1986. /**
  1987. * Updates the current Vector4 with the passed one coordinates.
  1988. * Returns the updated Vector4.
  1989. */
  1990. Vector4.prototype.copyFrom = function (source) {
  1991. this.x = source.x;
  1992. this.y = source.y;
  1993. this.z = source.z;
  1994. this.w = source.w;
  1995. return this;
  1996. };
  1997. /**
  1998. * Updates the current Vector4 coordinates with the passed floats.
  1999. * Returns the updated Vector4.
  2000. */
  2001. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2002. this.x = x;
  2003. this.y = y;
  2004. this.z = z;
  2005. this.w = w;
  2006. return this;
  2007. };
  2008. /**
  2009. * Updates the current Vector4 coordinates with the passed floats.
  2010. * Returns the updated Vector4.
  2011. */
  2012. Vector4.prototype.set = function (x, y, z, w) {
  2013. return this.copyFromFloats(x, y, z, w);
  2014. };
  2015. // Statics
  2016. /**
  2017. * Returns a new Vector4 set from the starting index of the passed array.
  2018. */
  2019. Vector4.FromArray = function (array, offset) {
  2020. if (!offset) {
  2021. offset = 0;
  2022. }
  2023. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2024. };
  2025. /**
  2026. * Updates the passed vector "result" from the starting index of the passed array.
  2027. */
  2028. Vector4.FromArrayToRef = function (array, offset, result) {
  2029. result.x = array[offset];
  2030. result.y = array[offset + 1];
  2031. result.z = array[offset + 2];
  2032. result.w = array[offset + 3];
  2033. };
  2034. /**
  2035. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2036. */
  2037. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2038. Vector4.FromArrayToRef(array, offset, result);
  2039. };
  2040. /**
  2041. * Updates the passed vector "result" coordinates from the passed floats.
  2042. */
  2043. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2044. result.x = x;
  2045. result.y = y;
  2046. result.z = z;
  2047. result.w = w;
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2051. */
  2052. Vector4.Zero = function () {
  2053. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2054. };
  2055. /**
  2056. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2057. */
  2058. Vector4.One = function () {
  2059. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2060. };
  2061. /**
  2062. * Returns a new normalized Vector4 from the passed one.
  2063. */
  2064. Vector4.Normalize = function (vector) {
  2065. var result = Vector4.Zero();
  2066. Vector4.NormalizeToRef(vector, result);
  2067. return result;
  2068. };
  2069. /**
  2070. * Updates the passed vector "result" from the normalization of the passed one.
  2071. */
  2072. Vector4.NormalizeToRef = function (vector, result) {
  2073. result.copyFrom(vector);
  2074. result.normalize();
  2075. };
  2076. Vector4.Minimize = function (left, right) {
  2077. var min = left.clone();
  2078. min.MinimizeInPlace(right);
  2079. return min;
  2080. };
  2081. Vector4.Maximize = function (left, right) {
  2082. var max = left.clone();
  2083. max.MaximizeInPlace(right);
  2084. return max;
  2085. };
  2086. /**
  2087. * Returns the distance (float) between the vectors "value1" and "value2".
  2088. */
  2089. Vector4.Distance = function (value1, value2) {
  2090. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2091. };
  2092. /**
  2093. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2094. */
  2095. Vector4.DistanceSquared = function (value1, value2) {
  2096. var x = value1.x - value2.x;
  2097. var y = value1.y - value2.y;
  2098. var z = value1.z - value2.z;
  2099. var w = value1.w - value2.w;
  2100. return (x * x) + (y * y) + (z * z) + (w * w);
  2101. };
  2102. /**
  2103. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2104. */
  2105. Vector4.Center = function (value1, value2) {
  2106. var center = value1.add(value2);
  2107. center.scaleInPlace(0.5);
  2108. return center;
  2109. };
  2110. /**
  2111. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2112. * This methods computes transformed normalized direction vectors only.
  2113. */
  2114. Vector4.TransformNormal = function (vector, transformation) {
  2115. var result = Vector4.Zero();
  2116. Vector4.TransformNormalToRef(vector, transformation, result);
  2117. return result;
  2118. };
  2119. /**
  2120. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2121. * This methods computes transformed normalized direction vectors only.
  2122. */
  2123. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2124. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2125. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2126. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2127. result.x = x;
  2128. result.y = y;
  2129. result.z = z;
  2130. result.w = vector.w;
  2131. };
  2132. /**
  2133. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2134. * This methods computes transformed normalized direction vectors only.
  2135. */
  2136. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2137. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2138. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2139. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2140. result.w = w;
  2141. };
  2142. return Vector4;
  2143. }());
  2144. BABYLON.Vector4 = Vector4;
  2145. var Size = (function () {
  2146. /**
  2147. * Creates a Size object from the passed width and height (floats).
  2148. */
  2149. function Size(width, height) {
  2150. this.width = width;
  2151. this.height = height;
  2152. }
  2153. // Returns a string with the Size width and height.
  2154. Size.prototype.toString = function () {
  2155. return "{W: " + this.width + ", H: " + this.height + "}";
  2156. };
  2157. /**
  2158. * Returns the string "Size"
  2159. */
  2160. Size.prototype.getClassName = function () {
  2161. return "Size";
  2162. };
  2163. /**
  2164. * Returns the Size hash code.
  2165. */
  2166. Size.prototype.getHashCode = function () {
  2167. var hash = this.width || 0;
  2168. hash = (hash * 397) ^ (this.height || 0);
  2169. return hash;
  2170. };
  2171. /**
  2172. * Updates the current size from the passed one.
  2173. * Returns the updated Size.
  2174. */
  2175. Size.prototype.copyFrom = function (src) {
  2176. this.width = src.width;
  2177. this.height = src.height;
  2178. };
  2179. /**
  2180. * Updates in place the current Size from the passed floats.
  2181. * Returns the updated Size.
  2182. */
  2183. Size.prototype.copyFromFloats = function (width, height) {
  2184. this.width = width;
  2185. this.height = height;
  2186. return this;
  2187. };
  2188. /**
  2189. * Updates in place the current Size from the passed floats.
  2190. * Returns the updated Size.
  2191. */
  2192. Size.prototype.set = function (width, height) {
  2193. return this.copyFromFloats(width, height);
  2194. };
  2195. /**
  2196. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2197. */
  2198. Size.prototype.multiplyByFloats = function (w, h) {
  2199. return new Size(this.width * w, this.height * h);
  2200. };
  2201. /**
  2202. * Returns a new Size copied from the passed one.
  2203. */
  2204. Size.prototype.clone = function () {
  2205. return new Size(this.width, this.height);
  2206. };
  2207. /**
  2208. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2209. */
  2210. Size.prototype.equals = function (other) {
  2211. if (!other) {
  2212. return false;
  2213. }
  2214. return (this.width === other.width) && (this.height === other.height);
  2215. };
  2216. Object.defineProperty(Size.prototype, "surface", {
  2217. /**
  2218. * Returns the surface of the Size : width * height (float).
  2219. */
  2220. get: function () {
  2221. return this.width * this.height;
  2222. },
  2223. enumerable: true,
  2224. configurable: true
  2225. });
  2226. /**
  2227. * Returns a new Size set to (0.0, 0.0)
  2228. */
  2229. Size.Zero = function () {
  2230. return new Size(0.0, 0.0);
  2231. };
  2232. /**
  2233. * Returns a new Size set as the addition result of the current Size and the passed one.
  2234. */
  2235. Size.prototype.add = function (otherSize) {
  2236. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2237. return r;
  2238. };
  2239. /**
  2240. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2241. */
  2242. Size.prototype.subtract = function (otherSize) {
  2243. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2244. return r;
  2245. };
  2246. /**
  2247. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2248. */
  2249. Size.Lerp = function (start, end, amount) {
  2250. var w = start.width + ((end.width - start.width) * amount);
  2251. var h = start.height + ((end.height - start.height) * amount);
  2252. return new Size(w, h);
  2253. };
  2254. return Size;
  2255. }());
  2256. BABYLON.Size = Size;
  2257. var Quaternion = (function () {
  2258. /**
  2259. * Creates a new Quaternion from the passed floats.
  2260. */
  2261. function Quaternion(x, y, z, w) {
  2262. if (x === void 0) { x = 0.0; }
  2263. if (y === void 0) { y = 0.0; }
  2264. if (z === void 0) { z = 0.0; }
  2265. if (w === void 0) { w = 1.0; }
  2266. this.x = x;
  2267. this.y = y;
  2268. this.z = z;
  2269. this.w = w;
  2270. }
  2271. /**
  2272. * Returns a string with the Quaternion coordinates.
  2273. */
  2274. Quaternion.prototype.toString = function () {
  2275. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2276. };
  2277. /**
  2278. * Returns the string "Quaternion".
  2279. */
  2280. Quaternion.prototype.getClassName = function () {
  2281. return "Quaternion";
  2282. };
  2283. /**
  2284. * Returns the Quaternion hash code.
  2285. */
  2286. Quaternion.prototype.getHashCode = function () {
  2287. var hash = this.x || 0;
  2288. hash = (hash * 397) ^ (this.y || 0);
  2289. hash = (hash * 397) ^ (this.z || 0);
  2290. hash = (hash * 397) ^ (this.w || 0);
  2291. return hash;
  2292. };
  2293. /**
  2294. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2295. */
  2296. Quaternion.prototype.asArray = function () {
  2297. return [this.x, this.y, this.z, this.w];
  2298. };
  2299. /**
  2300. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2301. */
  2302. Quaternion.prototype.equals = function (otherQuaternion) {
  2303. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2304. };
  2305. /**
  2306. * Returns a new Quaternion copied from the current one.
  2307. */
  2308. Quaternion.prototype.clone = function () {
  2309. return new Quaternion(this.x, this.y, this.z, this.w);
  2310. };
  2311. /**
  2312. * Updates the current Quaternion from the passed one coordinates.
  2313. * Returns the updated Quaterion.
  2314. */
  2315. Quaternion.prototype.copyFrom = function (other) {
  2316. this.x = other.x;
  2317. this.y = other.y;
  2318. this.z = other.z;
  2319. this.w = other.w;
  2320. return this;
  2321. };
  2322. /**
  2323. * Updates the current Quaternion from the passed float coordinates.
  2324. * Returns the updated Quaterion.
  2325. */
  2326. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2327. this.x = x;
  2328. this.y = y;
  2329. this.z = z;
  2330. this.w = w;
  2331. return this;
  2332. };
  2333. /**
  2334. * Updates the current Quaternion from the passed float coordinates.
  2335. * Returns the updated Quaterion.
  2336. */
  2337. Quaternion.prototype.set = function (x, y, z, w) {
  2338. return this.copyFromFloats(x, y, z, w);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2342. */
  2343. Quaternion.prototype.add = function (other) {
  2344. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2345. };
  2346. /**
  2347. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2348. */
  2349. Quaternion.prototype.subtract = function (other) {
  2350. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2351. };
  2352. /**
  2353. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2354. */
  2355. Quaternion.prototype.scale = function (value) {
  2356. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2357. };
  2358. /**
  2359. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2360. */
  2361. Quaternion.prototype.multiply = function (q1) {
  2362. var result = new Quaternion(0, 0, 0, 1.0);
  2363. this.multiplyToRef(q1, result);
  2364. return result;
  2365. };
  2366. /**
  2367. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2368. * Returns the current Quaternion.
  2369. */
  2370. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2371. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2372. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2373. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2374. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2375. result.copyFromFloats(x, y, z, w);
  2376. return this;
  2377. };
  2378. /**
  2379. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2380. * Returns the updated Quaternion.
  2381. */
  2382. Quaternion.prototype.multiplyInPlace = function (q1) {
  2383. this.multiplyToRef(q1, this);
  2384. return this;
  2385. };
  2386. /**
  2387. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2388. * Returns the current Quaternion.
  2389. */
  2390. Quaternion.prototype.conjugateToRef = function (ref) {
  2391. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2392. return this;
  2393. };
  2394. /**
  2395. * Conjugates in place the current Quaternion.
  2396. * Returns the updated Quaternion.
  2397. */
  2398. Quaternion.prototype.conjugateInPlace = function () {
  2399. this.x *= -1;
  2400. this.y *= -1;
  2401. this.z *= -1;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2406. */
  2407. Quaternion.prototype.conjugate = function () {
  2408. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2409. return result;
  2410. };
  2411. /**
  2412. * Returns the Quaternion length (float).
  2413. */
  2414. Quaternion.prototype.length = function () {
  2415. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2416. };
  2417. /**
  2418. * Normalize in place the current Quaternion.
  2419. * Returns the updated Quaternion.
  2420. */
  2421. Quaternion.prototype.normalize = function () {
  2422. var length = 1.0 / this.length();
  2423. this.x *= length;
  2424. this.y *= length;
  2425. this.z *= length;
  2426. this.w *= length;
  2427. return this;
  2428. };
  2429. /**
  2430. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2431. */
  2432. Quaternion.prototype.toEulerAngles = function (order) {
  2433. if (order === void 0) { order = "YZX"; }
  2434. var result = Vector3.Zero();
  2435. this.toEulerAnglesToRef(result, order);
  2436. return result;
  2437. };
  2438. /**
  2439. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2440. * Returns the current Quaternion.
  2441. */
  2442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2443. if (order === void 0) { order = "YZX"; }
  2444. var qz = this.z;
  2445. var qx = this.x;
  2446. var qy = this.y;
  2447. var qw = this.w;
  2448. var sqw = qw * qw;
  2449. var sqz = qz * qz;
  2450. var sqx = qx * qx;
  2451. var sqy = qy * qy;
  2452. var zAxisY = qy * qz - qx * qw;
  2453. var limit = .4999999;
  2454. if (zAxisY < -limit) {
  2455. result.y = 2 * Math.atan2(qy, qw);
  2456. result.x = Math.PI / 2;
  2457. result.z = 0;
  2458. }
  2459. else if (zAxisY > limit) {
  2460. result.y = 2 * Math.atan2(qy, qw);
  2461. result.x = -Math.PI / 2;
  2462. result.z = 0;
  2463. }
  2464. else {
  2465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2468. }
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the passed rotation matrix with the current Quaternion values.
  2473. * Returns the current Quaternion.
  2474. */
  2475. Quaternion.prototype.toRotationMatrix = function (result) {
  2476. var xx = this.x * this.x;
  2477. var yy = this.y * this.y;
  2478. var zz = this.z * this.z;
  2479. var xy = this.x * this.y;
  2480. var zw = this.z * this.w;
  2481. var zx = this.z * this.x;
  2482. var yw = this.y * this.w;
  2483. var yz = this.y * this.z;
  2484. var xw = this.x * this.w;
  2485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2486. result.m[1] = 2.0 * (xy + zw);
  2487. result.m[2] = 2.0 * (zx - yw);
  2488. result.m[3] = 0;
  2489. result.m[4] = 2.0 * (xy - zw);
  2490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2491. result.m[6] = 2.0 * (yz + xw);
  2492. result.m[7] = 0;
  2493. result.m[8] = 2.0 * (zx + yw);
  2494. result.m[9] = 2.0 * (yz - xw);
  2495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2496. result.m[11] = 0;
  2497. result.m[12] = 0;
  2498. result.m[13] = 0;
  2499. result.m[14] = 0;
  2500. result.m[15] = 1.0;
  2501. result._markAsUpdated();
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion from the passed rotation matrix values.
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2509. Quaternion.FromRotationMatrixToRef(matrix, this);
  2510. return this;
  2511. };
  2512. // Statics
  2513. /**
  2514. * Returns a new Quaternion set from the passed rotation matrix values.
  2515. */
  2516. Quaternion.FromRotationMatrix = function (matrix) {
  2517. var result = new Quaternion();
  2518. Quaternion.FromRotationMatrixToRef(matrix, result);
  2519. return result;
  2520. };
  2521. /**
  2522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2523. */
  2524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2525. var data = matrix.m;
  2526. var m11 = data[0], m12 = data[4], m13 = data[8];
  2527. var m21 = data[1], m22 = data[5], m23 = data[9];
  2528. var m31 = data[2], m32 = data[6], m33 = data[10];
  2529. var trace = m11 + m22 + m33;
  2530. var s;
  2531. if (trace > 0) {
  2532. s = 0.5 / Math.sqrt(trace + 1.0);
  2533. result.w = 0.25 / s;
  2534. result.x = (m32 - m23) * s;
  2535. result.y = (m13 - m31) * s;
  2536. result.z = (m21 - m12) * s;
  2537. }
  2538. else if (m11 > m22 && m11 > m33) {
  2539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2540. result.w = (m32 - m23) / s;
  2541. result.x = 0.25 * s;
  2542. result.y = (m12 + m21) / s;
  2543. result.z = (m13 + m31) / s;
  2544. }
  2545. else if (m22 > m33) {
  2546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2547. result.w = (m13 - m31) / s;
  2548. result.x = (m12 + m21) / s;
  2549. result.y = 0.25 * s;
  2550. result.z = (m23 + m32) / s;
  2551. }
  2552. else {
  2553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2554. result.w = (m21 - m12) / s;
  2555. result.x = (m13 + m31) / s;
  2556. result.y = (m23 + m32) / s;
  2557. result.z = 0.25 * s;
  2558. }
  2559. };
  2560. /**
  2561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2562. */
  2563. Quaternion.Zero = function () {
  2564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2565. };
  2566. /**
  2567. * Returns a new Quaternion as the inverted current Quaternion.
  2568. */
  2569. Quaternion.Inverse = function (q) {
  2570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2571. };
  2572. /**
  2573. * Returns the identity Quaternion.
  2574. */
  2575. Quaternion.Identity = function () {
  2576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2577. };
  2578. Quaternion.IsIdentity = function (quaternion) {
  2579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2580. };
  2581. /**
  2582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2583. */
  2584. Quaternion.RotationAxis = function (axis, angle) {
  2585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2586. };
  2587. /**
  2588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2589. */
  2590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2591. var sin = Math.sin(angle / 2);
  2592. axis.normalize();
  2593. result.w = Math.cos(angle / 2);
  2594. result.x = axis.x * sin;
  2595. result.y = axis.y * sin;
  2596. result.z = axis.z * sin;
  2597. return result;
  2598. };
  2599. /**
  2600. * Retuns a new Quaternion set from the starting index of the passed array.
  2601. */
  2602. Quaternion.FromArray = function (array, offset) {
  2603. if (!offset) {
  2604. offset = 0;
  2605. }
  2606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2607. };
  2608. /**
  2609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2610. */
  2611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2612. var q = new Quaternion();
  2613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2614. return q;
  2615. };
  2616. /**
  2617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2618. */
  2619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2621. var halfRoll = roll * 0.5;
  2622. var halfPitch = pitch * 0.5;
  2623. var halfYaw = yaw * 0.5;
  2624. var sinRoll = Math.sin(halfRoll);
  2625. var cosRoll = Math.cos(halfRoll);
  2626. var sinPitch = Math.sin(halfPitch);
  2627. var cosPitch = Math.cos(halfPitch);
  2628. var sinYaw = Math.sin(halfYaw);
  2629. var cosYaw = Math.cos(halfYaw);
  2630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2634. };
  2635. /**
  2636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2637. */
  2638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2639. var result = new Quaternion();
  2640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2641. return result;
  2642. };
  2643. /**
  2644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2645. */
  2646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2647. // Produces a quaternion from Euler angles in the z-x-z orientation
  2648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2650. var halfBeta = beta * 0.5;
  2651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2655. };
  2656. /**
  2657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2658. * cf to Vector3.RotationFromAxis() documentation.
  2659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2660. */
  2661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2664. return quat;
  2665. };
  2666. /**
  2667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2668. * cf to Vector3.RotationFromAxis() documentation.
  2669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2670. */
  2671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2672. var rotMat = MathTmp.Matrix[0];
  2673. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2674. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2675. };
  2676. Quaternion.Slerp = function (left, right, amount) {
  2677. var result = Quaternion.Identity();
  2678. Quaternion.SlerpToRef(left, right, amount, result);
  2679. return result;
  2680. };
  2681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2682. var num2;
  2683. var num3;
  2684. var num = amount;
  2685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2686. var flag = false;
  2687. if (num4 < 0) {
  2688. flag = true;
  2689. num4 = -num4;
  2690. }
  2691. if (num4 > 0.999999) {
  2692. num3 = 1 - num;
  2693. num2 = flag ? -num : num;
  2694. }
  2695. else {
  2696. var num5 = Math.acos(num4);
  2697. var num6 = (1.0 / Math.sin(num5));
  2698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2700. }
  2701. result.x = (num3 * left.x) + (num2 * right.x);
  2702. result.y = (num3 * left.y) + (num2 * right.y);
  2703. result.z = (num3 * left.z) + (num2 * right.z);
  2704. result.w = (num3 * left.w) + (num2 * right.w);
  2705. };
  2706. /**
  2707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2708. */
  2709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2710. var squared = amount * amount;
  2711. var cubed = amount * squared;
  2712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2714. var part3 = (cubed - (2.0 * squared)) + amount;
  2715. var part4 = cubed - squared;
  2716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2720. return new Quaternion(x, y, z, w);
  2721. };
  2722. return Quaternion;
  2723. }());
  2724. BABYLON.Quaternion = Quaternion;
  2725. var Matrix = (function () {
  2726. function Matrix() {
  2727. this.m = new Float32Array(16);
  2728. this._markAsUpdated();
  2729. }
  2730. Matrix.prototype._markAsUpdated = function () {
  2731. this.updateFlag = Matrix._updateFlagSeed++;
  2732. };
  2733. // Properties
  2734. /**
  2735. * Boolean : True is the matrix is the identity matrix
  2736. */
  2737. Matrix.prototype.isIdentity = function () {
  2738. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2739. return false;
  2740. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2741. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2742. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2743. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2744. return false;
  2745. return true;
  2746. };
  2747. /**
  2748. * Returns the matrix determinant (float).
  2749. */
  2750. Matrix.prototype.determinant = function () {
  2751. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2752. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2753. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2754. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2755. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2756. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2757. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2758. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2759. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2760. };
  2761. // Methods
  2762. /**
  2763. * Returns the matrix underlying array.
  2764. */
  2765. Matrix.prototype.toArray = function () {
  2766. return this.m;
  2767. };
  2768. /**
  2769. * Returns the matrix underlying array.
  2770. */
  2771. Matrix.prototype.asArray = function () {
  2772. return this.toArray();
  2773. };
  2774. /**
  2775. * Inverts in place the Matrix.
  2776. * Returns the Matrix inverted.
  2777. */
  2778. Matrix.prototype.invert = function () {
  2779. this.invertToRef(this);
  2780. return this;
  2781. };
  2782. /**
  2783. * Sets all the matrix elements to zero.
  2784. * Returns the Matrix.
  2785. */
  2786. Matrix.prototype.reset = function () {
  2787. for (var index = 0; index < 16; index++) {
  2788. this.m[index] = 0.0;
  2789. }
  2790. this._markAsUpdated();
  2791. return this;
  2792. };
  2793. /**
  2794. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2795. */
  2796. Matrix.prototype.add = function (other) {
  2797. var result = new Matrix();
  2798. this.addToRef(other, result);
  2799. return result;
  2800. };
  2801. /**
  2802. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2803. * Returns the Matrix.
  2804. */
  2805. Matrix.prototype.addToRef = function (other, result) {
  2806. for (var index = 0; index < 16; index++) {
  2807. result.m[index] = this.m[index] + other.m[index];
  2808. }
  2809. result._markAsUpdated();
  2810. return this;
  2811. };
  2812. /**
  2813. * Adds in place the passed matrix to the current Matrix.
  2814. * Returns the updated Matrix.
  2815. */
  2816. Matrix.prototype.addToSelf = function (other) {
  2817. for (var index = 0; index < 16; index++) {
  2818. this.m[index] += other.m[index];
  2819. }
  2820. this._markAsUpdated();
  2821. return this;
  2822. };
  2823. /**
  2824. * Sets the passed matrix with the current inverted Matrix.
  2825. * Returns the unmodified current Matrix.
  2826. */
  2827. Matrix.prototype.invertToRef = function (other) {
  2828. var l1 = this.m[0];
  2829. var l2 = this.m[1];
  2830. var l3 = this.m[2];
  2831. var l4 = this.m[3];
  2832. var l5 = this.m[4];
  2833. var l6 = this.m[5];
  2834. var l7 = this.m[6];
  2835. var l8 = this.m[7];
  2836. var l9 = this.m[8];
  2837. var l10 = this.m[9];
  2838. var l11 = this.m[10];
  2839. var l12 = this.m[11];
  2840. var l13 = this.m[12];
  2841. var l14 = this.m[13];
  2842. var l15 = this.m[14];
  2843. var l16 = this.m[15];
  2844. var l17 = (l11 * l16) - (l12 * l15);
  2845. var l18 = (l10 * l16) - (l12 * l14);
  2846. var l19 = (l10 * l15) - (l11 * l14);
  2847. var l20 = (l9 * l16) - (l12 * l13);
  2848. var l21 = (l9 * l15) - (l11 * l13);
  2849. var l22 = (l9 * l14) - (l10 * l13);
  2850. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2851. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2852. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2853. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2854. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2855. var l28 = (l7 * l16) - (l8 * l15);
  2856. var l29 = (l6 * l16) - (l8 * l14);
  2857. var l30 = (l6 * l15) - (l7 * l14);
  2858. var l31 = (l5 * l16) - (l8 * l13);
  2859. var l32 = (l5 * l15) - (l7 * l13);
  2860. var l33 = (l5 * l14) - (l6 * l13);
  2861. var l34 = (l7 * l12) - (l8 * l11);
  2862. var l35 = (l6 * l12) - (l8 * l10);
  2863. var l36 = (l6 * l11) - (l7 * l10);
  2864. var l37 = (l5 * l12) - (l8 * l9);
  2865. var l38 = (l5 * l11) - (l7 * l9);
  2866. var l39 = (l5 * l10) - (l6 * l9);
  2867. other.m[0] = l23 * l27;
  2868. other.m[4] = l24 * l27;
  2869. other.m[8] = l25 * l27;
  2870. other.m[12] = l26 * l27;
  2871. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2872. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2873. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2874. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2875. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2876. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2877. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2878. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2879. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2880. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2881. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2882. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2883. other._markAsUpdated();
  2884. return this;
  2885. };
  2886. /**
  2887. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2888. * Returns the updated Matrix.
  2889. */
  2890. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2891. this.m[12] = x;
  2892. this.m[13] = y;
  2893. this.m[14] = z;
  2894. this._markAsUpdated();
  2895. return this;
  2896. };
  2897. /**
  2898. * Inserts the translation vector in the current Matrix.
  2899. * Returns the updated Matrix.
  2900. */
  2901. Matrix.prototype.setTranslation = function (vector3) {
  2902. this.m[12] = vector3.x;
  2903. this.m[13] = vector3.y;
  2904. this.m[14] = vector3.z;
  2905. this._markAsUpdated();
  2906. return this;
  2907. };
  2908. /**
  2909. * Returns a new Vector3 as the extracted translation from the Matrix.
  2910. */
  2911. Matrix.prototype.getTranslation = function () {
  2912. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2913. };
  2914. /**
  2915. * Fill a Vector3 with the extracted translation from the Matrix.
  2916. */
  2917. Matrix.prototype.getTranslationToRef = function (result) {
  2918. result.x = this.m[12];
  2919. result.y = this.m[13];
  2920. result.z = this.m[14];
  2921. return this;
  2922. };
  2923. /**
  2924. * Remove rotation and scaling part from the Matrix.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.removeRotationAndScaling = function () {
  2928. this.setRowFromFloats(0, 1, 0, 0, 0);
  2929. this.setRowFromFloats(1, 0, 1, 0, 0);
  2930. this.setRowFromFloats(2, 0, 0, 1, 0);
  2931. return this;
  2932. };
  2933. /**
  2934. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2935. */
  2936. Matrix.prototype.multiply = function (other) {
  2937. var result = new Matrix();
  2938. this.multiplyToRef(other, result);
  2939. return result;
  2940. };
  2941. /**
  2942. * Updates the current Matrix from the passed one values.
  2943. * Returns the updated Matrix.
  2944. */
  2945. Matrix.prototype.copyFrom = function (other) {
  2946. for (var index = 0; index < 16; index++) {
  2947. this.m[index] = other.m[index];
  2948. }
  2949. this._markAsUpdated();
  2950. return this;
  2951. };
  2952. /**
  2953. * Populates the passed array from the starting index with the Matrix values.
  2954. * Returns the Matrix.
  2955. */
  2956. Matrix.prototype.copyToArray = function (array, offset) {
  2957. if (offset === void 0) { offset = 0; }
  2958. for (var index = 0; index < 16; index++) {
  2959. array[offset + index] = this.m[index];
  2960. }
  2961. return this;
  2962. };
  2963. /**
  2964. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2965. */
  2966. Matrix.prototype.multiplyToRef = function (other, result) {
  2967. this.multiplyToArray(other, result.m, 0);
  2968. result._markAsUpdated();
  2969. return this;
  2970. };
  2971. /**
  2972. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2973. */
  2974. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2975. var tm0 = this.m[0];
  2976. var tm1 = this.m[1];
  2977. var tm2 = this.m[2];
  2978. var tm3 = this.m[3];
  2979. var tm4 = this.m[4];
  2980. var tm5 = this.m[5];
  2981. var tm6 = this.m[6];
  2982. var tm7 = this.m[7];
  2983. var tm8 = this.m[8];
  2984. var tm9 = this.m[9];
  2985. var tm10 = this.m[10];
  2986. var tm11 = this.m[11];
  2987. var tm12 = this.m[12];
  2988. var tm13 = this.m[13];
  2989. var tm14 = this.m[14];
  2990. var tm15 = this.m[15];
  2991. var om0 = other.m[0];
  2992. var om1 = other.m[1];
  2993. var om2 = other.m[2];
  2994. var om3 = other.m[3];
  2995. var om4 = other.m[4];
  2996. var om5 = other.m[5];
  2997. var om6 = other.m[6];
  2998. var om7 = other.m[7];
  2999. var om8 = other.m[8];
  3000. var om9 = other.m[9];
  3001. var om10 = other.m[10];
  3002. var om11 = other.m[11];
  3003. var om12 = other.m[12];
  3004. var om13 = other.m[13];
  3005. var om14 = other.m[14];
  3006. var om15 = other.m[15];
  3007. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3008. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3009. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3010. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3011. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3012. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3013. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3014. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3015. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3016. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3017. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3018. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3019. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3020. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3021. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3022. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3023. return this;
  3024. };
  3025. /**
  3026. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3027. */
  3028. Matrix.prototype.equals = function (value) {
  3029. return value &&
  3030. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3031. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3032. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3033. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3034. };
  3035. /**
  3036. * Returns a new Matrix from the current Matrix.
  3037. */
  3038. Matrix.prototype.clone = function () {
  3039. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3040. };
  3041. /**
  3042. * Returns the string "Matrix"
  3043. */
  3044. Matrix.prototype.getClassName = function () {
  3045. return "Matrix";
  3046. };
  3047. /**
  3048. * Returns the Matrix hash code.
  3049. */
  3050. Matrix.prototype.getHashCode = function () {
  3051. var hash = this.m[0] || 0;
  3052. for (var i = 1; i < 16; i++) {
  3053. hash = (hash * 397) ^ (this.m[i] || 0);
  3054. }
  3055. return hash;
  3056. };
  3057. /**
  3058. * Decomposes the current Matrix into :
  3059. * - a scale vector3 passed as a reference to update,
  3060. * - a rotation quaternion passed as a reference to update,
  3061. * - a translation vector3 passed as a reference to update.
  3062. * Returns the boolean `true`.
  3063. */
  3064. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3065. translation.x = this.m[12];
  3066. translation.y = this.m[13];
  3067. translation.z = this.m[14];
  3068. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3069. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3070. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3071. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3072. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3073. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3074. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3075. rotation.x = 0;
  3076. rotation.y = 0;
  3077. rotation.z = 0;
  3078. rotation.w = 1;
  3079. return false;
  3080. }
  3081. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3082. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3083. return true;
  3084. };
  3085. /**
  3086. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3087. */
  3088. Matrix.prototype.getRotationMatrix = function () {
  3089. var result = Matrix.Identity();
  3090. this.getRotationMatrixToRef(result);
  3091. return result;
  3092. };
  3093. /**
  3094. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3095. * Returns the current Matrix.
  3096. */
  3097. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3098. var m = this.m;
  3099. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3100. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3101. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3102. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3103. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3104. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3105. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3106. return this;
  3107. };
  3108. // Statics
  3109. /**
  3110. * Returns a new Matrix set from the starting index of the passed array.
  3111. */
  3112. Matrix.FromArray = function (array, offset) {
  3113. var result = new Matrix();
  3114. if (!offset) {
  3115. offset = 0;
  3116. }
  3117. Matrix.FromArrayToRef(array, offset, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed "result" matrix from the starting index of the passed array.
  3122. */
  3123. Matrix.FromArrayToRef = function (array, offset, result) {
  3124. for (var index = 0; index < 16; index++) {
  3125. result.m[index] = array[index + offset];
  3126. }
  3127. result._markAsUpdated();
  3128. };
  3129. /**
  3130. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3131. */
  3132. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3133. for (var index = 0; index < 16; index++) {
  3134. result.m[index] = array[index + offset] * scale;
  3135. }
  3136. result._markAsUpdated();
  3137. };
  3138. /**
  3139. * Sets the passed matrix "result" with the 16 passed floats.
  3140. */
  3141. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3142. result.m[0] = initialM11;
  3143. result.m[1] = initialM12;
  3144. result.m[2] = initialM13;
  3145. result.m[3] = initialM14;
  3146. result.m[4] = initialM21;
  3147. result.m[5] = initialM22;
  3148. result.m[6] = initialM23;
  3149. result.m[7] = initialM24;
  3150. result.m[8] = initialM31;
  3151. result.m[9] = initialM32;
  3152. result.m[10] = initialM33;
  3153. result.m[11] = initialM34;
  3154. result.m[12] = initialM41;
  3155. result.m[13] = initialM42;
  3156. result.m[14] = initialM43;
  3157. result.m[15] = initialM44;
  3158. result._markAsUpdated();
  3159. };
  3160. /**
  3161. * Returns the index-th row of the current matrix as a new Vector4.
  3162. */
  3163. Matrix.prototype.getRow = function (index) {
  3164. if (index < 0 || index > 3) {
  3165. return null;
  3166. }
  3167. var i = index * 4;
  3168. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3169. };
  3170. /**
  3171. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3172. * Returns the updated Matrix.
  3173. */
  3174. Matrix.prototype.setRow = function (index, row) {
  3175. if (index < 0 || index > 3) {
  3176. return this;
  3177. }
  3178. var i = index * 4;
  3179. this.m[i + 0] = row.x;
  3180. this.m[i + 1] = row.y;
  3181. this.m[i + 2] = row.z;
  3182. this.m[i + 3] = row.w;
  3183. this._markAsUpdated();
  3184. return this;
  3185. };
  3186. /**
  3187. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3188. * Returns the updated Matrix.
  3189. */
  3190. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3191. if (index < 0 || index > 3) {
  3192. return this;
  3193. }
  3194. var i = index * 4;
  3195. this.m[i + 0] = x;
  3196. this.m[i + 1] = y;
  3197. this.m[i + 2] = z;
  3198. this.m[i + 3] = w;
  3199. this._markAsUpdated();
  3200. return this;
  3201. };
  3202. /**
  3203. * Returns a new Matrix set from the 16 passed floats.
  3204. */
  3205. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3206. var result = new Matrix();
  3207. result.m[0] = initialM11;
  3208. result.m[1] = initialM12;
  3209. result.m[2] = initialM13;
  3210. result.m[3] = initialM14;
  3211. result.m[4] = initialM21;
  3212. result.m[5] = initialM22;
  3213. result.m[6] = initialM23;
  3214. result.m[7] = initialM24;
  3215. result.m[8] = initialM31;
  3216. result.m[9] = initialM32;
  3217. result.m[10] = initialM33;
  3218. result.m[11] = initialM34;
  3219. result.m[12] = initialM41;
  3220. result.m[13] = initialM42;
  3221. result.m[14] = initialM43;
  3222. result.m[15] = initialM44;
  3223. return result;
  3224. };
  3225. /**
  3226. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3227. */
  3228. Matrix.Compose = function (scale, rotation, translation) {
  3229. var result = Matrix.Identity();
  3230. Matrix.ComposeToRef(scale, rotation, translation, result);
  3231. return result;
  3232. };
  3233. /**
  3234. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3235. */
  3236. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3237. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3238. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3239. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3240. result.setTranslation(translation);
  3241. };
  3242. /**
  3243. * Returns a new indentity Matrix.
  3244. */
  3245. Matrix.Identity = function () {
  3246. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3247. };
  3248. /**
  3249. * Sets the passed "result" as an identity matrix.
  3250. */
  3251. Matrix.IdentityToRef = function (result) {
  3252. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3253. };
  3254. /**
  3255. * Returns a new zero Matrix.
  3256. */
  3257. Matrix.Zero = function () {
  3258. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3259. };
  3260. /**
  3261. * Returns a new rotation matrix for "angle" radians around the X axis.
  3262. */
  3263. Matrix.RotationX = function (angle) {
  3264. var result = new Matrix();
  3265. Matrix.RotationXToRef(angle, result);
  3266. return result;
  3267. };
  3268. /**
  3269. * Returns a new Matrix as the passed inverted one.
  3270. */
  3271. Matrix.Invert = function (source) {
  3272. var result = new Matrix();
  3273. source.invertToRef(result);
  3274. return result;
  3275. };
  3276. /**
  3277. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3278. */
  3279. Matrix.RotationXToRef = function (angle, result) {
  3280. var s = Math.sin(angle);
  3281. var c = Math.cos(angle);
  3282. result.m[0] = 1.0;
  3283. result.m[15] = 1.0;
  3284. result.m[5] = c;
  3285. result.m[10] = c;
  3286. result.m[9] = -s;
  3287. result.m[6] = s;
  3288. result.m[1] = 0.0;
  3289. result.m[2] = 0.0;
  3290. result.m[3] = 0.0;
  3291. result.m[4] = 0.0;
  3292. result.m[7] = 0.0;
  3293. result.m[8] = 0.0;
  3294. result.m[11] = 0.0;
  3295. result.m[12] = 0.0;
  3296. result.m[13] = 0.0;
  3297. result.m[14] = 0.0;
  3298. result._markAsUpdated();
  3299. };
  3300. /**
  3301. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3302. */
  3303. Matrix.RotationY = function (angle) {
  3304. var result = new Matrix();
  3305. Matrix.RotationYToRef(angle, result);
  3306. return result;
  3307. };
  3308. /**
  3309. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3310. */
  3311. Matrix.RotationYToRef = function (angle, result) {
  3312. var s = Math.sin(angle);
  3313. var c = Math.cos(angle);
  3314. result.m[5] = 1.0;
  3315. result.m[15] = 1.0;
  3316. result.m[0] = c;
  3317. result.m[2] = -s;
  3318. result.m[8] = s;
  3319. result.m[10] = c;
  3320. result.m[1] = 0.0;
  3321. result.m[3] = 0.0;
  3322. result.m[4] = 0.0;
  3323. result.m[6] = 0.0;
  3324. result.m[7] = 0.0;
  3325. result.m[9] = 0.0;
  3326. result.m[11] = 0.0;
  3327. result.m[12] = 0.0;
  3328. result.m[13] = 0.0;
  3329. result.m[14] = 0.0;
  3330. result._markAsUpdated();
  3331. };
  3332. /**
  3333. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3334. */
  3335. Matrix.RotationZ = function (angle) {
  3336. var result = new Matrix();
  3337. Matrix.RotationZToRef(angle, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3342. */
  3343. Matrix.RotationZToRef = function (angle, result) {
  3344. var s = Math.sin(angle);
  3345. var c = Math.cos(angle);
  3346. result.m[10] = 1.0;
  3347. result.m[15] = 1.0;
  3348. result.m[0] = c;
  3349. result.m[1] = s;
  3350. result.m[4] = -s;
  3351. result.m[5] = c;
  3352. result.m[2] = 0.0;
  3353. result.m[3] = 0.0;
  3354. result.m[6] = 0.0;
  3355. result.m[7] = 0.0;
  3356. result.m[8] = 0.0;
  3357. result.m[9] = 0.0;
  3358. result.m[11] = 0.0;
  3359. result.m[12] = 0.0;
  3360. result.m[13] = 0.0;
  3361. result.m[14] = 0.0;
  3362. result._markAsUpdated();
  3363. };
  3364. /**
  3365. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3366. */
  3367. Matrix.RotationAxis = function (axis, angle) {
  3368. var result = Matrix.Zero();
  3369. Matrix.RotationAxisToRef(axis, angle, result);
  3370. return result;
  3371. };
  3372. /**
  3373. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3374. */
  3375. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3376. var s = Math.sin(-angle);
  3377. var c = Math.cos(-angle);
  3378. var c1 = 1 - c;
  3379. axis.normalize();
  3380. result.m[0] = (axis.x * axis.x) * c1 + c;
  3381. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3382. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3383. result.m[3] = 0.0;
  3384. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3385. result.m[5] = (axis.y * axis.y) * c1 + c;
  3386. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3387. result.m[7] = 0.0;
  3388. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3389. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3390. result.m[10] = (axis.z * axis.z) * c1 + c;
  3391. result.m[11] = 0.0;
  3392. result.m[15] = 1.0;
  3393. result._markAsUpdated();
  3394. };
  3395. /**
  3396. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3397. */
  3398. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3399. var result = new Matrix();
  3400. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3401. return result;
  3402. };
  3403. /**
  3404. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3405. */
  3406. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3407. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3408. this._tempQuaternion.toRotationMatrix(result);
  3409. };
  3410. /**
  3411. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3412. */
  3413. Matrix.Scaling = function (x, y, z) {
  3414. var result = Matrix.Zero();
  3415. Matrix.ScalingToRef(x, y, z, result);
  3416. return result;
  3417. };
  3418. /**
  3419. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3420. */
  3421. Matrix.ScalingToRef = function (x, y, z, result) {
  3422. result.m[0] = x;
  3423. result.m[1] = 0.0;
  3424. result.m[2] = 0.0;
  3425. result.m[3] = 0.0;
  3426. result.m[4] = 0.0;
  3427. result.m[5] = y;
  3428. result.m[6] = 0.0;
  3429. result.m[7] = 0.0;
  3430. result.m[8] = 0.0;
  3431. result.m[9] = 0.0;
  3432. result.m[10] = z;
  3433. result.m[11] = 0.0;
  3434. result.m[12] = 0.0;
  3435. result.m[13] = 0.0;
  3436. result.m[14] = 0.0;
  3437. result.m[15] = 1.0;
  3438. result._markAsUpdated();
  3439. };
  3440. /**
  3441. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3442. */
  3443. Matrix.Translation = function (x, y, z) {
  3444. var result = Matrix.Identity();
  3445. Matrix.TranslationToRef(x, y, z, result);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3450. */
  3451. Matrix.TranslationToRef = function (x, y, z, result) {
  3452. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3453. };
  3454. /**
  3455. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3456. */
  3457. Matrix.Lerp = function (startValue, endValue, gradient) {
  3458. var result = Matrix.Zero();
  3459. for (var index = 0; index < 16; index++) {
  3460. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3461. }
  3462. result._markAsUpdated();
  3463. return result;
  3464. };
  3465. /**
  3466. * Returns a new Matrix whose values are computed by :
  3467. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3468. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3469. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3470. */
  3471. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3472. var startScale = new Vector3(0, 0, 0);
  3473. var startRotation = new Quaternion();
  3474. var startTranslation = new Vector3(0, 0, 0);
  3475. startValue.decompose(startScale, startRotation, startTranslation);
  3476. var endScale = new Vector3(0, 0, 0);
  3477. var endRotation = new Quaternion();
  3478. var endTranslation = new Vector3(0, 0, 0);
  3479. endValue.decompose(endScale, endRotation, endTranslation);
  3480. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3481. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3482. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3483. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3484. };
  3485. /**
  3486. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3487. * This methods works for a Left-Handed system.
  3488. */
  3489. Matrix.LookAtLH = function (eye, target, up) {
  3490. var result = Matrix.Zero();
  3491. Matrix.LookAtLHToRef(eye, target, up, result);
  3492. return result;
  3493. };
  3494. /**
  3495. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3496. * This methods works for a Left-Handed system.
  3497. */
  3498. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3499. // Z axis
  3500. target.subtractToRef(eye, this._zAxis);
  3501. this._zAxis.normalize();
  3502. // X axis
  3503. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3504. if (this._xAxis.lengthSquared() === 0) {
  3505. this._xAxis.x = 1.0;
  3506. }
  3507. else {
  3508. this._xAxis.normalize();
  3509. }
  3510. // Y axis
  3511. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3512. this._yAxis.normalize();
  3513. // Eye angles
  3514. var ex = -Vector3.Dot(this._xAxis, eye);
  3515. var ey = -Vector3.Dot(this._yAxis, eye);
  3516. var ez = -Vector3.Dot(this._zAxis, eye);
  3517. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3518. };
  3519. /**
  3520. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3521. * This methods works for a Right-Handed system.
  3522. */
  3523. Matrix.LookAtRH = function (eye, target, up) {
  3524. var result = Matrix.Zero();
  3525. Matrix.LookAtRHToRef(eye, target, up, result);
  3526. return result;
  3527. };
  3528. /**
  3529. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3530. * This methods works for a Left-Handed system.
  3531. */
  3532. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3533. // Z axis
  3534. eye.subtractToRef(target, this._zAxis);
  3535. this._zAxis.normalize();
  3536. // X axis
  3537. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3538. if (this._xAxis.lengthSquared() === 0) {
  3539. this._xAxis.x = 1.0;
  3540. }
  3541. else {
  3542. this._xAxis.normalize();
  3543. }
  3544. // Y axis
  3545. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3546. this._yAxis.normalize();
  3547. // Eye angles
  3548. var ex = -Vector3.Dot(this._xAxis, eye);
  3549. var ey = -Vector3.Dot(this._yAxis, eye);
  3550. var ez = -Vector3.Dot(this._zAxis, eye);
  3551. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3552. };
  3553. /**
  3554. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3555. */
  3556. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3557. var matrix = Matrix.Zero();
  3558. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3559. return matrix;
  3560. };
  3561. /**
  3562. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3563. */
  3564. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3565. var n = znear;
  3566. var f = zfar;
  3567. var a = 2.0 / width;
  3568. var b = 2.0 / height;
  3569. var c = 2.0 / (f - n);
  3570. var d = -(f + n) / (f - n);
  3571. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3572. };
  3573. /**
  3574. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3575. */
  3576. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3577. var matrix = Matrix.Zero();
  3578. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3579. return matrix;
  3580. };
  3581. /**
  3582. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3583. */
  3584. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3585. var n = znear;
  3586. var f = zfar;
  3587. var a = 2.0 / (right - left);
  3588. var b = 2.0 / (top - bottom);
  3589. var c = 2.0 / (f - n);
  3590. var d = -(f + n) / (f - n);
  3591. var i0 = (left + right) / (left - right);
  3592. var i1 = (top + bottom) / (bottom - top);
  3593. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3594. };
  3595. /**
  3596. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3597. */
  3598. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3599. var matrix = Matrix.Zero();
  3600. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3601. return matrix;
  3602. };
  3603. /**
  3604. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3605. */
  3606. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3607. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3608. result.m[10] *= -1.0;
  3609. };
  3610. /**
  3611. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3612. */
  3613. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3614. var matrix = Matrix.Zero();
  3615. var n = znear;
  3616. var f = zfar;
  3617. var a = 2.0 * n / width;
  3618. var b = 2.0 * n / height;
  3619. var c = (f + n) / (f - n);
  3620. var d = -2.0 * f * n / (f - n);
  3621. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3622. return matrix;
  3623. };
  3624. /**
  3625. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3626. */
  3627. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3628. var matrix = Matrix.Zero();
  3629. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3630. return matrix;
  3631. };
  3632. /**
  3633. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3634. */
  3635. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3636. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3637. var n = znear;
  3638. var f = zfar;
  3639. var t = 1.0 / (Math.tan(fov * 0.5));
  3640. var a = isVerticalFovFixed ? (t / aspect) : t;
  3641. var b = isVerticalFovFixed ? t : (t * aspect);
  3642. var c = (f + n) / (f - n);
  3643. var d = -2.0 * f * n / (f - n);
  3644. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3645. };
  3646. /**
  3647. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3648. */
  3649. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3650. var matrix = Matrix.Zero();
  3651. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3652. return matrix;
  3653. };
  3654. /**
  3655. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3656. */
  3657. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3658. //alternatively this could be expressed as:
  3659. // m = PerspectiveFovLHToRef
  3660. // m[10] *= -1.0;
  3661. // m[11] *= -1.0;
  3662. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3663. var n = znear;
  3664. var f = zfar;
  3665. var t = 1.0 / (Math.tan(fov * 0.5));
  3666. var a = isVerticalFovFixed ? (t / aspect) : t;
  3667. var b = isVerticalFovFixed ? t : (t * aspect);
  3668. var c = -(f + n) / (f - n);
  3669. var d = -2 * f * n / (f - n);
  3670. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3671. };
  3672. /**
  3673. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3674. */
  3675. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3676. if (rightHanded === void 0) { rightHanded = false; }
  3677. var rightHandedFactor = rightHanded ? -1 : 1;
  3678. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3679. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3680. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3681. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3682. var xScale = 2.0 / (leftTan + rightTan);
  3683. var yScale = 2.0 / (upTan + downTan);
  3684. result.m[0] = xScale;
  3685. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3686. result.m[5] = yScale;
  3687. result.m[6] = result.m[7] = 0.0;
  3688. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3689. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3690. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3691. result.m[10] = -zfar / (znear - zfar);
  3692. result.m[11] = 1.0 * rightHandedFactor;
  3693. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3694. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3695. // result.m[14] = (znear * zfar) / (znear - zfar);
  3696. result._markAsUpdated();
  3697. };
  3698. /**
  3699. * Returns the final transformation matrix : world * view * projection * viewport
  3700. */
  3701. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3702. var cw = viewport.width;
  3703. var ch = viewport.height;
  3704. var cx = viewport.x;
  3705. var cy = viewport.y;
  3706. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3707. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3708. };
  3709. /**
  3710. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3711. */
  3712. Matrix.GetAsMatrix2x2 = function (matrix) {
  3713. return new Float32Array([
  3714. matrix.m[0], matrix.m[1],
  3715. matrix.m[4], matrix.m[5]
  3716. ]);
  3717. };
  3718. /**
  3719. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3720. */
  3721. Matrix.GetAsMatrix3x3 = function (matrix) {
  3722. return new Float32Array([
  3723. matrix.m[0], matrix.m[1], matrix.m[2],
  3724. matrix.m[4], matrix.m[5], matrix.m[6],
  3725. matrix.m[8], matrix.m[9], matrix.m[10]
  3726. ]);
  3727. };
  3728. /**
  3729. * Compute the transpose of the passed Matrix.
  3730. * Returns a new Matrix.
  3731. */
  3732. Matrix.Transpose = function (matrix) {
  3733. var result = new Matrix();
  3734. result.m[0] = matrix.m[0];
  3735. result.m[1] = matrix.m[4];
  3736. result.m[2] = matrix.m[8];
  3737. result.m[3] = matrix.m[12];
  3738. result.m[4] = matrix.m[1];
  3739. result.m[5] = matrix.m[5];
  3740. result.m[6] = matrix.m[9];
  3741. result.m[7] = matrix.m[13];
  3742. result.m[8] = matrix.m[2];
  3743. result.m[9] = matrix.m[6];
  3744. result.m[10] = matrix.m[10];
  3745. result.m[11] = matrix.m[14];
  3746. result.m[12] = matrix.m[3];
  3747. result.m[13] = matrix.m[7];
  3748. result.m[14] = matrix.m[11];
  3749. result.m[15] = matrix.m[15];
  3750. return result;
  3751. };
  3752. /**
  3753. * Returns a new Matrix as the reflection matrix across the passed plane.
  3754. */
  3755. Matrix.Reflection = function (plane) {
  3756. var matrix = new Matrix();
  3757. Matrix.ReflectionToRef(plane, matrix);
  3758. return matrix;
  3759. };
  3760. /**
  3761. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3762. */
  3763. Matrix.ReflectionToRef = function (plane, result) {
  3764. plane.normalize();
  3765. var x = plane.normal.x;
  3766. var y = plane.normal.y;
  3767. var z = plane.normal.z;
  3768. var temp = -2 * x;
  3769. var temp2 = -2 * y;
  3770. var temp3 = -2 * z;
  3771. result.m[0] = (temp * x) + 1;
  3772. result.m[1] = temp2 * x;
  3773. result.m[2] = temp3 * x;
  3774. result.m[3] = 0.0;
  3775. result.m[4] = temp * y;
  3776. result.m[5] = (temp2 * y) + 1;
  3777. result.m[6] = temp3 * y;
  3778. result.m[7] = 0.0;
  3779. result.m[8] = temp * z;
  3780. result.m[9] = temp2 * z;
  3781. result.m[10] = (temp3 * z) + 1;
  3782. result.m[11] = 0.0;
  3783. result.m[12] = temp * plane.d;
  3784. result.m[13] = temp2 * plane.d;
  3785. result.m[14] = temp3 * plane.d;
  3786. result.m[15] = 1.0;
  3787. result._markAsUpdated();
  3788. };
  3789. /**
  3790. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3791. */
  3792. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3793. result.m[0] = xaxis.x;
  3794. result.m[1] = xaxis.y;
  3795. result.m[2] = xaxis.z;
  3796. result.m[3] = 0.0;
  3797. result.m[4] = yaxis.x;
  3798. result.m[5] = yaxis.y;
  3799. result.m[6] = yaxis.z;
  3800. result.m[7] = 0.0;
  3801. result.m[8] = zaxis.x;
  3802. result.m[9] = zaxis.y;
  3803. result.m[10] = zaxis.z;
  3804. result.m[11] = 0.0;
  3805. result.m[12] = 0.0;
  3806. result.m[13] = 0.0;
  3807. result.m[14] = 0.0;
  3808. result.m[15] = 1.0;
  3809. result._markAsUpdated();
  3810. };
  3811. /**
  3812. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3813. */
  3814. Matrix.FromQuaternionToRef = function (quat, result) {
  3815. var xx = quat.x * quat.x;
  3816. var yy = quat.y * quat.y;
  3817. var zz = quat.z * quat.z;
  3818. var xy = quat.x * quat.y;
  3819. var zw = quat.z * quat.w;
  3820. var zx = quat.z * quat.x;
  3821. var yw = quat.y * quat.w;
  3822. var yz = quat.y * quat.z;
  3823. var xw = quat.x * quat.w;
  3824. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3825. result.m[1] = 2.0 * (xy + zw);
  3826. result.m[2] = 2.0 * (zx - yw);
  3827. result.m[3] = 0.0;
  3828. result.m[4] = 2.0 * (xy - zw);
  3829. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3830. result.m[6] = 2.0 * (yz + xw);
  3831. result.m[7] = 0.0;
  3832. result.m[8] = 2.0 * (zx + yw);
  3833. result.m[9] = 2.0 * (yz - xw);
  3834. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3835. result.m[11] = 0.0;
  3836. result.m[12] = 0.0;
  3837. result.m[13] = 0.0;
  3838. result.m[14] = 0.0;
  3839. result.m[15] = 1.0;
  3840. result._markAsUpdated();
  3841. };
  3842. return Matrix;
  3843. }());
  3844. Matrix._tempQuaternion = new Quaternion();
  3845. Matrix._xAxis = Vector3.Zero();
  3846. Matrix._yAxis = Vector3.Zero();
  3847. Matrix._zAxis = Vector3.Zero();
  3848. Matrix._updateFlagSeed = 0;
  3849. BABYLON.Matrix = Matrix;
  3850. var Plane = (function () {
  3851. /**
  3852. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3853. */
  3854. function Plane(a, b, c, d) {
  3855. this.normal = new Vector3(a, b, c);
  3856. this.d = d;
  3857. }
  3858. /**
  3859. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3860. */
  3861. Plane.prototype.asArray = function () {
  3862. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3863. };
  3864. // Methods
  3865. /**
  3866. * Returns a new plane copied from the current Plane.
  3867. */
  3868. Plane.prototype.clone = function () {
  3869. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3870. };
  3871. /**
  3872. * Returns the string "Plane".
  3873. */
  3874. Plane.prototype.getClassName = function () {
  3875. return "Plane";
  3876. };
  3877. /**
  3878. * Returns the Plane hash code.
  3879. */
  3880. Plane.prototype.getHashCode = function () {
  3881. var hash = this.normal.getHashCode();
  3882. hash = (hash * 397) ^ (this.d || 0);
  3883. return hash;
  3884. };
  3885. /**
  3886. * Normalize the current Plane in place.
  3887. * Returns the updated Plane.
  3888. */
  3889. Plane.prototype.normalize = function () {
  3890. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3891. var magnitude = 0.0;
  3892. if (norm !== 0) {
  3893. magnitude = 1.0 / norm;
  3894. }
  3895. this.normal.x *= magnitude;
  3896. this.normal.y *= magnitude;
  3897. this.normal.z *= magnitude;
  3898. this.d *= magnitude;
  3899. return this;
  3900. };
  3901. /**
  3902. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3903. */
  3904. Plane.prototype.transform = function (transformation) {
  3905. var transposedMatrix = Matrix.Transpose(transformation);
  3906. var x = this.normal.x;
  3907. var y = this.normal.y;
  3908. var z = this.normal.z;
  3909. var d = this.d;
  3910. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3911. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3912. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3913. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3914. return new Plane(normalX, normalY, normalZ, finalD);
  3915. };
  3916. /**
  3917. * Returns the dot product (float) of the point coordinates and the plane normal.
  3918. */
  3919. Plane.prototype.dotCoordinate = function (point) {
  3920. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3921. };
  3922. /**
  3923. * Updates the current Plane from the plane defined by the three passed points.
  3924. * Returns the updated Plane.
  3925. */
  3926. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3927. var x1 = point2.x - point1.x;
  3928. var y1 = point2.y - point1.y;
  3929. var z1 = point2.z - point1.z;
  3930. var x2 = point3.x - point1.x;
  3931. var y2 = point3.y - point1.y;
  3932. var z2 = point3.z - point1.z;
  3933. var yz = (y1 * z2) - (z1 * y2);
  3934. var xz = (z1 * x2) - (x1 * z2);
  3935. var xy = (x1 * y2) - (y1 * x2);
  3936. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3937. var invPyth;
  3938. if (pyth !== 0) {
  3939. invPyth = 1.0 / pyth;
  3940. }
  3941. else {
  3942. invPyth = 0.0;
  3943. }
  3944. this.normal.x = yz * invPyth;
  3945. this.normal.y = xz * invPyth;
  3946. this.normal.z = xy * invPyth;
  3947. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3948. return this;
  3949. };
  3950. /**
  3951. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3952. */
  3953. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3954. var dot = Vector3.Dot(this.normal, direction);
  3955. return (dot <= epsilon);
  3956. };
  3957. /**
  3958. * Returns the signed distance (float) from the passed point to the Plane.
  3959. */
  3960. Plane.prototype.signedDistanceTo = function (point) {
  3961. return Vector3.Dot(point, this.normal) + this.d;
  3962. };
  3963. // Statics
  3964. /**
  3965. * Returns a new Plane from the passed array.
  3966. */
  3967. Plane.FromArray = function (array) {
  3968. return new Plane(array[0], array[1], array[2], array[3]);
  3969. };
  3970. /**
  3971. * Returns a new Plane defined by the three passed points.
  3972. */
  3973. Plane.FromPoints = function (point1, point2, point3) {
  3974. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3975. result.copyFromPoints(point1, point2, point3);
  3976. return result;
  3977. };
  3978. /**
  3979. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3980. * Note : the vector "normal" is updated because normalized.
  3981. */
  3982. Plane.FromPositionAndNormal = function (origin, normal) {
  3983. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3984. normal.normalize();
  3985. result.normal = normal;
  3986. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3987. return result;
  3988. };
  3989. /**
  3990. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3991. */
  3992. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3993. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3994. return Vector3.Dot(point, normal) + d;
  3995. };
  3996. return Plane;
  3997. }());
  3998. BABYLON.Plane = Plane;
  3999. var Viewport = (function () {
  4000. /**
  4001. * Creates a Viewport object located at (x, y) and sized (width, height).
  4002. */
  4003. function Viewport(x, y, width, height) {
  4004. this.x = x;
  4005. this.y = y;
  4006. this.width = width;
  4007. this.height = height;
  4008. }
  4009. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  4010. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4011. };
  4012. /**
  4013. * Returns a new Viewport copied from the current one.
  4014. */
  4015. Viewport.prototype.clone = function () {
  4016. return new Viewport(this.x, this.y, this.width, this.height);
  4017. };
  4018. return Viewport;
  4019. }());
  4020. BABYLON.Viewport = Viewport;
  4021. var Frustum = (function () {
  4022. function Frustum() {
  4023. }
  4024. /**
  4025. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4026. */
  4027. Frustum.GetPlanes = function (transform) {
  4028. var frustumPlanes = [];
  4029. for (var index = 0; index < 6; index++) {
  4030. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4031. }
  4032. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4033. return frustumPlanes;
  4034. };
  4035. /**
  4036. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4037. */
  4038. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4039. // Near
  4040. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4041. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4042. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4043. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4044. frustumPlanes[0].normalize();
  4045. // Far
  4046. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4047. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4048. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4049. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4050. frustumPlanes[1].normalize();
  4051. // Left
  4052. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4053. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4054. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4055. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4056. frustumPlanes[2].normalize();
  4057. // Right
  4058. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4059. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4060. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4061. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4062. frustumPlanes[3].normalize();
  4063. // Top
  4064. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4065. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4066. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4067. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4068. frustumPlanes[4].normalize();
  4069. // Bottom
  4070. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4071. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4072. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4073. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4074. frustumPlanes[5].normalize();
  4075. };
  4076. return Frustum;
  4077. }());
  4078. BABYLON.Frustum = Frustum;
  4079. var Space;
  4080. (function (Space) {
  4081. Space[Space["LOCAL"] = 0] = "LOCAL";
  4082. Space[Space["WORLD"] = 1] = "WORLD";
  4083. Space[Space["BONE"] = 2] = "BONE";
  4084. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4085. var Axis = (function () {
  4086. function Axis() {
  4087. }
  4088. return Axis;
  4089. }());
  4090. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4091. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4092. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4093. BABYLON.Axis = Axis;
  4094. ;
  4095. var BezierCurve = (function () {
  4096. function BezierCurve() {
  4097. }
  4098. /**
  4099. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4100. */
  4101. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4102. // Extract X (which is equal to time here)
  4103. var f0 = 1 - 3 * x2 + 3 * x1;
  4104. var f1 = 3 * x2 - 6 * x1;
  4105. var f2 = 3 * x1;
  4106. var refinedT = t;
  4107. for (var i = 0; i < 5; i++) {
  4108. var refinedT2 = refinedT * refinedT;
  4109. var refinedT3 = refinedT2 * refinedT;
  4110. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4111. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4112. refinedT -= (x - t) * slope;
  4113. refinedT = Math.min(1, Math.max(0, refinedT));
  4114. }
  4115. // Resolve cubic bezier for the given x
  4116. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4117. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4118. Math.pow(refinedT, 3);
  4119. };
  4120. return BezierCurve;
  4121. }());
  4122. BABYLON.BezierCurve = BezierCurve;
  4123. var Orientation;
  4124. (function (Orientation) {
  4125. Orientation[Orientation["CW"] = 0] = "CW";
  4126. Orientation[Orientation["CCW"] = 1] = "CCW";
  4127. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4128. var Angle = (function () {
  4129. /**
  4130. * Creates an Angle object of "radians" radians (float).
  4131. */
  4132. function Angle(radians) {
  4133. var _this = this;
  4134. /**
  4135. * Returns the Angle value in degrees (float).
  4136. */
  4137. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4138. /**
  4139. * Returns the Angle value in radians (float).
  4140. */
  4141. this.radians = function () { return _this._radians; };
  4142. this._radians = radians;
  4143. if (this._radians < 0.0)
  4144. this._radians += (2.0 * Math.PI);
  4145. }
  4146. /**
  4147. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4148. */
  4149. Angle.BetweenTwoPoints = function (a, b) {
  4150. var delta = b.subtract(a);
  4151. var theta = Math.atan2(delta.y, delta.x);
  4152. return new Angle(theta);
  4153. };
  4154. /**
  4155. * Returns a new Angle object from the passed float in radians.
  4156. */
  4157. Angle.FromRadians = function (radians) {
  4158. return new Angle(radians);
  4159. };
  4160. /**
  4161. * Returns a new Angle object from the passed float in degrees.
  4162. */
  4163. Angle.FromDegrees = function (degrees) {
  4164. return new Angle(degrees * Math.PI / 180.0);
  4165. };
  4166. return Angle;
  4167. }());
  4168. BABYLON.Angle = Angle;
  4169. var Arc2 = (function () {
  4170. /**
  4171. * Creates an Arc object from the three passed points : start, middle and end.
  4172. */
  4173. function Arc2(startPoint, midPoint, endPoint) {
  4174. this.startPoint = startPoint;
  4175. this.midPoint = midPoint;
  4176. this.endPoint = endPoint;
  4177. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4178. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4179. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4180. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4181. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4182. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4183. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4184. var a1 = this.startAngle.degrees();
  4185. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4186. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4187. // angles correction
  4188. if (a2 - a1 > +180.0)
  4189. a2 -= 360.0;
  4190. if (a2 - a1 < -180.0)
  4191. a2 += 360.0;
  4192. if (a3 - a2 > +180.0)
  4193. a3 -= 360.0;
  4194. if (a3 - a2 < -180.0)
  4195. a3 += 360.0;
  4196. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4197. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4198. }
  4199. return Arc2;
  4200. }());
  4201. BABYLON.Arc2 = Arc2;
  4202. var Path2 = (function () {
  4203. /**
  4204. * Creates a Path2 object from the starting 2D coordinates x and y.
  4205. */
  4206. function Path2(x, y) {
  4207. this._points = new Array();
  4208. this._length = 0.0;
  4209. this.closed = false;
  4210. this._points.push(new Vector2(x, y));
  4211. }
  4212. /**
  4213. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4214. * Returns the updated Path2.
  4215. */
  4216. Path2.prototype.addLineTo = function (x, y) {
  4217. if (closed) {
  4218. //Tools.Error("cannot add lines to closed paths");
  4219. return this;
  4220. }
  4221. var newPoint = new Vector2(x, y);
  4222. var previousPoint = this._points[this._points.length - 1];
  4223. this._points.push(newPoint);
  4224. this._length += newPoint.subtract(previousPoint).length();
  4225. return this;
  4226. };
  4227. /**
  4228. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4229. * Returns the updated Path2.
  4230. */
  4231. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4232. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4233. if (closed) {
  4234. //Tools.Error("cannot add arcs to closed paths");
  4235. return this;
  4236. }
  4237. var startPoint = this._points[this._points.length - 1];
  4238. var midPoint = new Vector2(midX, midY);
  4239. var endPoint = new Vector2(endX, endY);
  4240. var arc = new Arc2(startPoint, midPoint, endPoint);
  4241. var increment = arc.angle.radians() / numberOfSegments;
  4242. if (arc.orientation === Orientation.CW)
  4243. increment *= -1;
  4244. var currentAngle = arc.startAngle.radians() + increment;
  4245. for (var i = 0; i < numberOfSegments; i++) {
  4246. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4247. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4248. this.addLineTo(x, y);
  4249. currentAngle += increment;
  4250. }
  4251. return this;
  4252. };
  4253. /**
  4254. * Closes the Path2.
  4255. * Returns the Path2.
  4256. */
  4257. Path2.prototype.close = function () {
  4258. this.closed = true;
  4259. return this;
  4260. };
  4261. /**
  4262. * Returns the Path2 total length (float).
  4263. */
  4264. Path2.prototype.length = function () {
  4265. var result = this._length;
  4266. if (!this.closed) {
  4267. var lastPoint = this._points[this._points.length - 1];
  4268. var firstPoint = this._points[0];
  4269. result += (firstPoint.subtract(lastPoint).length());
  4270. }
  4271. return result;
  4272. };
  4273. /**
  4274. * Returns the Path2 internal array of points.
  4275. */
  4276. Path2.prototype.getPoints = function () {
  4277. return this._points;
  4278. };
  4279. /**
  4280. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4281. */
  4282. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4283. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4284. //Tools.Error("normalized length position should be between 0 and 1.");
  4285. return Vector2.Zero();
  4286. }
  4287. var lengthPosition = normalizedLengthPosition * this.length();
  4288. var previousOffset = 0;
  4289. for (var i = 0; i < this._points.length; i++) {
  4290. var j = (i + 1) % this._points.length;
  4291. var a = this._points[i];
  4292. var b = this._points[j];
  4293. var bToA = b.subtract(a);
  4294. var nextOffset = (bToA.length() + previousOffset);
  4295. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4296. var dir = bToA.normalize();
  4297. var localOffset = lengthPosition - previousOffset;
  4298. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4299. }
  4300. previousOffset = nextOffset;
  4301. }
  4302. //Tools.Error("internal error");
  4303. return Vector2.Zero();
  4304. };
  4305. /**
  4306. * Returns a new Path2 starting at the coordinates (x, y).
  4307. */
  4308. Path2.StartingAt = function (x, y) {
  4309. return new Path2(x, y);
  4310. };
  4311. return Path2;
  4312. }());
  4313. BABYLON.Path2 = Path2;
  4314. var Path3D = (function () {
  4315. /**
  4316. * new Path3D(path, normal, raw)
  4317. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4318. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4319. * path : an array of Vector3, the curve axis of the Path3D
  4320. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4321. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4322. */
  4323. function Path3D(path, firstNormal, raw) {
  4324. this.path = path;
  4325. this._curve = new Array();
  4326. this._distances = new Array();
  4327. this._tangents = new Array();
  4328. this._normals = new Array();
  4329. this._binormals = new Array();
  4330. for (var p = 0; p < path.length; p++) {
  4331. this._curve[p] = path[p].clone(); // hard copy
  4332. }
  4333. this._raw = raw || false;
  4334. this._compute(firstNormal);
  4335. }
  4336. /**
  4337. * Returns the Path3D array of successive Vector3 designing its curve.
  4338. */
  4339. Path3D.prototype.getCurve = function () {
  4340. return this._curve;
  4341. };
  4342. /**
  4343. * Returns an array populated with tangent vectors on each Path3D curve point.
  4344. */
  4345. Path3D.prototype.getTangents = function () {
  4346. return this._tangents;
  4347. };
  4348. /**
  4349. * Returns an array populated with normal vectors on each Path3D curve point.
  4350. */
  4351. Path3D.prototype.getNormals = function () {
  4352. return this._normals;
  4353. };
  4354. /**
  4355. * Returns an array populated with binormal vectors on each Path3D curve point.
  4356. */
  4357. Path3D.prototype.getBinormals = function () {
  4358. return this._binormals;
  4359. };
  4360. /**
  4361. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4362. */
  4363. Path3D.prototype.getDistances = function () {
  4364. return this._distances;
  4365. };
  4366. /**
  4367. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4368. * Returns the same object updated.
  4369. */
  4370. Path3D.prototype.update = function (path, firstNormal) {
  4371. for (var p = 0; p < path.length; p++) {
  4372. this._curve[p].x = path[p].x;
  4373. this._curve[p].y = path[p].y;
  4374. this._curve[p].z = path[p].z;
  4375. }
  4376. this._compute(firstNormal);
  4377. return this;
  4378. };
  4379. // private function compute() : computes tangents, normals and binormals
  4380. Path3D.prototype._compute = function (firstNormal) {
  4381. var l = this._curve.length;
  4382. // first and last tangents
  4383. this._tangents[0] = this._getFirstNonNullVector(0);
  4384. if (!this._raw) {
  4385. this._tangents[0].normalize();
  4386. }
  4387. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4388. if (!this._raw) {
  4389. this._tangents[l - 1].normalize();
  4390. }
  4391. // normals and binormals at first point : arbitrary vector with _normalVector()
  4392. var tg0 = this._tangents[0];
  4393. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4394. this._normals[0] = pp0;
  4395. if (!this._raw) {
  4396. this._normals[0].normalize();
  4397. }
  4398. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4399. if (!this._raw) {
  4400. this._binormals[0].normalize();
  4401. }
  4402. this._distances[0] = 0.0;
  4403. // normals and binormals : next points
  4404. var prev; // previous vector (segment)
  4405. var cur; // current vector (segment)
  4406. var curTang; // current tangent
  4407. // previous normal
  4408. var prevBinor; // previous binormal
  4409. for (var i = 1; i < l; i++) {
  4410. // tangents
  4411. prev = this._getLastNonNullVector(i);
  4412. if (i < l - 1) {
  4413. cur = this._getFirstNonNullVector(i);
  4414. this._tangents[i] = prev.add(cur);
  4415. this._tangents[i].normalize();
  4416. }
  4417. this._distances[i] = this._distances[i - 1] + prev.length();
  4418. // normals and binormals
  4419. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4420. curTang = this._tangents[i];
  4421. prevBinor = this._binormals[i - 1];
  4422. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4423. if (!this._raw) {
  4424. this._normals[i].normalize();
  4425. }
  4426. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4427. if (!this._raw) {
  4428. this._binormals[i].normalize();
  4429. }
  4430. }
  4431. };
  4432. // private function getFirstNonNullVector(index)
  4433. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4434. Path3D.prototype._getFirstNonNullVector = function (index) {
  4435. var i = 1;
  4436. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4437. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4438. i++;
  4439. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4440. }
  4441. return nNVector;
  4442. };
  4443. // private function getLastNonNullVector(index)
  4444. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4445. Path3D.prototype._getLastNonNullVector = function (index) {
  4446. var i = 1;
  4447. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4448. while (nLVector.length() === 0 && index > i + 1) {
  4449. i++;
  4450. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4451. }
  4452. return nLVector;
  4453. };
  4454. // private function normalVector(v0, vt, va) :
  4455. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4456. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4457. Path3D.prototype._normalVector = function (v0, vt, va) {
  4458. var normal0;
  4459. var tgl = vt.length();
  4460. if (tgl === 0.0) {
  4461. tgl = 1.0;
  4462. }
  4463. if (va === undefined || va === null) {
  4464. var point;
  4465. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4466. point = new Vector3(0.0, -1.0, 0.0);
  4467. }
  4468. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4469. point = new Vector3(1.0, 0.0, 0.0);
  4470. }
  4471. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4472. point = new Vector3(0.0, 0.0, 1.0);
  4473. }
  4474. normal0 = Vector3.Cross(vt, point);
  4475. }
  4476. else {
  4477. normal0 = Vector3.Cross(vt, va);
  4478. Vector3.CrossToRef(normal0, vt, normal0);
  4479. }
  4480. normal0.normalize();
  4481. return normal0;
  4482. };
  4483. return Path3D;
  4484. }());
  4485. BABYLON.Path3D = Path3D;
  4486. var Curve3 = (function () {
  4487. /**
  4488. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4489. * A Curve3 is designed from a series of successive Vector3.
  4490. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4491. */
  4492. function Curve3(points) {
  4493. this._length = 0.0;
  4494. this._points = points;
  4495. this._length = this._computeLength(points);
  4496. }
  4497. /**
  4498. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4499. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4500. * @param v1 (Vector3) the control point
  4501. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4502. * @param nbPoints (integer) the wanted number of points in the curve
  4503. */
  4504. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4505. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4506. var bez = new Array();
  4507. var equation = function (t, val0, val1, val2) {
  4508. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4509. return res;
  4510. };
  4511. for (var i = 0; i <= nbPoints; i++) {
  4512. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4513. }
  4514. return new Curve3(bez);
  4515. };
  4516. /**
  4517. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4518. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4519. * @param v1 (Vector3) the first control point
  4520. * @param v2 (Vector3) the second control point
  4521. * @param v3 (Vector3) the end point of the Cubic Bezier
  4522. * @param nbPoints (integer) the wanted number of points in the curve
  4523. */
  4524. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4525. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4526. var bez = new Array();
  4527. var equation = function (t, val0, val1, val2, val3) {
  4528. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4529. return res;
  4530. };
  4531. for (var i = 0; i <= nbPoints; i++) {
  4532. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4533. }
  4534. return new Curve3(bez);
  4535. };
  4536. /**
  4537. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4538. * @param p1 (Vector3) the origin point of the Hermite Spline
  4539. * @param t1 (Vector3) the tangent vector at the origin point
  4540. * @param p2 (Vector3) the end point of the Hermite Spline
  4541. * @param t2 (Vector3) the tangent vector at the end point
  4542. * @param nbPoints (integer) the wanted number of points in the curve
  4543. */
  4544. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4545. var hermite = new Array();
  4546. var step = 1.0 / nbPoints;
  4547. for (var i = 0; i <= nbPoints; i++) {
  4548. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4549. }
  4550. return new Curve3(hermite);
  4551. };
  4552. /**
  4553. * Returns a Curve3 object along a CatmullRom Spline curve :
  4554. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4555. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4556. */
  4557. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4558. var totalPoints = new Array();
  4559. totalPoints.push(points[0].clone());
  4560. Array.prototype.push.apply(totalPoints, points);
  4561. totalPoints.push(points[points.length - 1].clone());
  4562. var catmullRom = new Array();
  4563. var step = 1.0 / nbPoints;
  4564. for (var i = 0; i < totalPoints.length - 3; i++) {
  4565. var amount = 0.0;
  4566. for (var c = 0; c < nbPoints; c++) {
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. amount += step;
  4569. }
  4570. }
  4571. i--;
  4572. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4573. return new Curve3(catmullRom);
  4574. };
  4575. /**
  4576. * Returns the Curve3 stored array of successive Vector3
  4577. */
  4578. Curve3.prototype.getPoints = function () {
  4579. return this._points;
  4580. };
  4581. /**
  4582. * Returns the computed length (float) of the curve.
  4583. */
  4584. Curve3.prototype.length = function () {
  4585. return this._length;
  4586. };
  4587. /**
  4588. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4589. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4590. * curveA and curveB keep unchanged.
  4591. */
  4592. Curve3.prototype.continue = function (curve) {
  4593. var lastPoint = this._points[this._points.length - 1];
  4594. var continuedPoints = this._points.slice();
  4595. var curvePoints = curve.getPoints();
  4596. for (var i = 1; i < curvePoints.length; i++) {
  4597. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4598. }
  4599. var continuedCurve = new Curve3(continuedPoints);
  4600. return continuedCurve;
  4601. };
  4602. Curve3.prototype._computeLength = function (path) {
  4603. var l = 0;
  4604. for (var i = 1; i < path.length; i++) {
  4605. l += (path[i].subtract(path[i - 1])).length();
  4606. }
  4607. return l;
  4608. };
  4609. return Curve3;
  4610. }());
  4611. BABYLON.Curve3 = Curve3;
  4612. // SphericalHarmonics
  4613. var SphericalHarmonics = (function () {
  4614. function SphericalHarmonics() {
  4615. this.L00 = Vector3.Zero();
  4616. this.L1_1 = Vector3.Zero();
  4617. this.L10 = Vector3.Zero();
  4618. this.L11 = Vector3.Zero();
  4619. this.L2_2 = Vector3.Zero();
  4620. this.L2_1 = Vector3.Zero();
  4621. this.L20 = Vector3.Zero();
  4622. this.L21 = Vector3.Zero();
  4623. this.L22 = Vector3.Zero();
  4624. }
  4625. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4626. var colorVector = new Vector3(color.r, color.g, color.b);
  4627. var c = colorVector.scale(deltaSolidAngle);
  4628. this.L00 = this.L00.add(c.scale(0.282095));
  4629. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4630. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4631. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4632. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4633. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4634. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4635. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4636. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4637. };
  4638. SphericalHarmonics.prototype.scale = function (scale) {
  4639. this.L00 = this.L00.scale(scale);
  4640. this.L1_1 = this.L1_1.scale(scale);
  4641. this.L10 = this.L10.scale(scale);
  4642. this.L11 = this.L11.scale(scale);
  4643. this.L2_2 = this.L2_2.scale(scale);
  4644. this.L2_1 = this.L2_1.scale(scale);
  4645. this.L20 = this.L20.scale(scale);
  4646. this.L21 = this.L21.scale(scale);
  4647. this.L22 = this.L22.scale(scale);
  4648. };
  4649. return SphericalHarmonics;
  4650. }());
  4651. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4652. // SphericalPolynomial
  4653. var SphericalPolynomial = (function () {
  4654. function SphericalPolynomial() {
  4655. this.x = Vector3.Zero();
  4656. this.y = Vector3.Zero();
  4657. this.z = Vector3.Zero();
  4658. this.xx = Vector3.Zero();
  4659. this.yy = Vector3.Zero();
  4660. this.zz = Vector3.Zero();
  4661. this.xy = Vector3.Zero();
  4662. this.yz = Vector3.Zero();
  4663. this.zx = Vector3.Zero();
  4664. }
  4665. SphericalPolynomial.prototype.addAmbient = function (color) {
  4666. var colorVector = new Vector3(color.r, color.g, color.b);
  4667. this.xx = this.xx.add(colorVector);
  4668. this.yy = this.yy.add(colorVector);
  4669. this.zz = this.zz.add(colorVector);
  4670. };
  4671. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4672. var result = new SphericalPolynomial();
  4673. result.x = harmonics.L11.scale(1.02333);
  4674. result.y = harmonics.L1_1.scale(1.02333);
  4675. result.z = harmonics.L10.scale(1.02333);
  4676. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4677. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4678. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4679. result.yz = harmonics.L2_1.scale(0.858086);
  4680. result.zx = harmonics.L21.scale(0.858086);
  4681. result.xy = harmonics.L2_2.scale(0.858086);
  4682. return result;
  4683. };
  4684. return SphericalPolynomial;
  4685. }());
  4686. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4687. // Vertex formats
  4688. var PositionNormalVertex = (function () {
  4689. function PositionNormalVertex(position, normal) {
  4690. if (position === void 0) { position = Vector3.Zero(); }
  4691. if (normal === void 0) { normal = Vector3.Up(); }
  4692. this.position = position;
  4693. this.normal = normal;
  4694. }
  4695. PositionNormalVertex.prototype.clone = function () {
  4696. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4697. };
  4698. return PositionNormalVertex;
  4699. }());
  4700. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4701. var PositionNormalTextureVertex = (function () {
  4702. function PositionNormalTextureVertex(position, normal, uv) {
  4703. if (position === void 0) { position = Vector3.Zero(); }
  4704. if (normal === void 0) { normal = Vector3.Up(); }
  4705. if (uv === void 0) { uv = Vector2.Zero(); }
  4706. this.position = position;
  4707. this.normal = normal;
  4708. this.uv = uv;
  4709. }
  4710. PositionNormalTextureVertex.prototype.clone = function () {
  4711. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4712. };
  4713. return PositionNormalTextureVertex;
  4714. }());
  4715. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4716. // Temporary pre-allocated objects for engine internal use
  4717. // usage in any internal function :
  4718. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4719. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4720. var Tmp = (function () {
  4721. function Tmp() {
  4722. }
  4723. return Tmp;
  4724. }());
  4725. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4726. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4727. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4728. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4729. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4730. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4731. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4732. Matrix.Zero(), Matrix.Zero(),
  4733. Matrix.Zero(), Matrix.Zero(),
  4734. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4735. BABYLON.Tmp = Tmp;
  4736. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4737. var MathTmp = (function () {
  4738. function MathTmp() {
  4739. }
  4740. return MathTmp;
  4741. }());
  4742. MathTmp.Vector3 = [Vector3.Zero()];
  4743. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4744. MathTmp.Quaternion = [Quaternion.Zero()];
  4745. })(BABYLON || (BABYLON = {}));
  4746. //# sourceMappingURL=babylon.math.js.map
  4747. //# sourceMappingURL=babylon.mixins.js.map
  4748. var BABYLON;
  4749. (function (BABYLON) {
  4750. function generateSerializableMember(type, sourceName) {
  4751. return function (target, propertyKey) {
  4752. if (!target.__serializableMembers) {
  4753. target.__serializableMembers = {};
  4754. }
  4755. if (!target.__serializableMembers[propertyKey]) {
  4756. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4757. }
  4758. };
  4759. }
  4760. function generateExpandMember(setCallback, targetKey) {
  4761. return function (target, propertyKey) {
  4762. var key = targetKey || ("_" + propertyKey);
  4763. Object.defineProperty(target, propertyKey, {
  4764. get: function () {
  4765. return this[key];
  4766. },
  4767. set: function (value) {
  4768. if (this[key] === value) {
  4769. return;
  4770. }
  4771. this[key] = value;
  4772. target[setCallback].apply(this);
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. };
  4778. }
  4779. function expandToProperty(callback, targetKey) {
  4780. return generateExpandMember(callback, targetKey);
  4781. }
  4782. BABYLON.expandToProperty = expandToProperty;
  4783. function serialize(sourceName) {
  4784. return generateSerializableMember(0, sourceName); // value member
  4785. }
  4786. BABYLON.serialize = serialize;
  4787. function serializeAsTexture(sourceName) {
  4788. return generateSerializableMember(1, sourceName); // texture member
  4789. }
  4790. BABYLON.serializeAsTexture = serializeAsTexture;
  4791. function serializeAsColor3(sourceName) {
  4792. return generateSerializableMember(2, sourceName); // color3 member
  4793. }
  4794. BABYLON.serializeAsColor3 = serializeAsColor3;
  4795. function serializeAsFresnelParameters(sourceName) {
  4796. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4797. }
  4798. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4799. function serializeAsVector2(sourceName) {
  4800. return generateSerializableMember(4, sourceName); // vector2 member
  4801. }
  4802. BABYLON.serializeAsVector2 = serializeAsVector2;
  4803. function serializeAsVector3(sourceName) {
  4804. return generateSerializableMember(5, sourceName); // vector3 member
  4805. }
  4806. BABYLON.serializeAsVector3 = serializeAsVector3;
  4807. function serializeAsMeshReference(sourceName) {
  4808. return generateSerializableMember(6, sourceName); // mesh reference member
  4809. }
  4810. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4811. function serializeAsColorCurves(sourceName) {
  4812. return generateSerializableMember(7, sourceName); // color curves
  4813. }
  4814. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4815. function serializeAsColor4(sourceName) {
  4816. return generateSerializableMember(8, sourceName); // color 4
  4817. }
  4818. BABYLON.serializeAsColor4 = serializeAsColor4;
  4819. function serializeAsImageProcessingConfiguration(sourceName) {
  4820. return generateSerializableMember(9, sourceName); // image processing
  4821. }
  4822. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  4823. var SerializationHelper = (function () {
  4824. function SerializationHelper() {
  4825. }
  4826. SerializationHelper.Serialize = function (entity, serializationObject) {
  4827. if (!serializationObject) {
  4828. serializationObject = {};
  4829. }
  4830. // Tags
  4831. if (BABYLON.Tags) {
  4832. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4833. }
  4834. // Properties
  4835. for (var property in entity.__serializableMembers) {
  4836. var propertyDescriptor = entity.__serializableMembers[property];
  4837. var targetPropertyName = propertyDescriptor.sourceName || property;
  4838. var propertyType = propertyDescriptor.type;
  4839. var sourceProperty = entity[property];
  4840. if (sourceProperty !== undefined && sourceProperty !== null) {
  4841. switch (propertyType) {
  4842. case 0:
  4843. serializationObject[targetPropertyName] = sourceProperty;
  4844. break;
  4845. case 1:
  4846. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4847. break;
  4848. case 2:
  4849. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4850. break;
  4851. case 3:
  4852. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4853. break;
  4854. case 4:
  4855. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4856. break;
  4857. case 5:
  4858. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4859. break;
  4860. case 6:
  4861. serializationObject[targetPropertyName] = sourceProperty.id;
  4862. break;
  4863. case 7:
  4864. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4865. break;
  4866. case 8:
  4867. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4868. break;
  4869. case 9:
  4870. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4871. break;
  4872. }
  4873. }
  4874. }
  4875. return serializationObject;
  4876. };
  4877. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4878. var destination = creationFunction();
  4879. // Tags
  4880. if (BABYLON.Tags) {
  4881. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4882. }
  4883. // Properties
  4884. for (var property in destination.__serializableMembers) {
  4885. var propertyDescriptor = destination.__serializableMembers[property];
  4886. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4887. var propertyType = propertyDescriptor.type;
  4888. if (sourceProperty !== undefined && sourceProperty !== null) {
  4889. switch (propertyType) {
  4890. case 0:
  4891. destination[property] = sourceProperty;
  4892. break;
  4893. case 1:
  4894. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4895. break;
  4896. case 2:
  4897. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4898. break;
  4899. case 3:
  4900. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4901. break;
  4902. case 4:
  4903. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4904. break;
  4905. case 5:
  4906. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4907. break;
  4908. case 6:
  4909. destination[property] = scene.getLastMeshByID(sourceProperty);
  4910. break;
  4911. case 7:
  4912. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4913. break;
  4914. case 8:
  4915. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  4916. break;
  4917. case 9:
  4918. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  4919. break;
  4920. }
  4921. }
  4922. }
  4923. return destination;
  4924. };
  4925. SerializationHelper.Clone = function (creationFunction, source) {
  4926. var destination = creationFunction();
  4927. // Tags
  4928. if (BABYLON.Tags) {
  4929. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4930. }
  4931. // Properties
  4932. for (var property in destination.__serializableMembers) {
  4933. var propertyDescriptor = destination.__serializableMembers[property];
  4934. var sourceProperty = source[property];
  4935. var propertyType = propertyDescriptor.type;
  4936. if (sourceProperty !== undefined && sourceProperty !== null) {
  4937. switch (propertyType) {
  4938. case 0: // Value
  4939. case 6:
  4940. destination[property] = sourceProperty;
  4941. break;
  4942. case 1: // Texture
  4943. case 2: // Color3
  4944. case 3: // FresnelParameters
  4945. case 4: // Vector2
  4946. case 5: // Vector3
  4947. case 7:
  4948. destination[property] = sourceProperty.clone();
  4949. break;
  4950. }
  4951. }
  4952. }
  4953. return destination;
  4954. };
  4955. return SerializationHelper;
  4956. }());
  4957. BABYLON.SerializationHelper = SerializationHelper;
  4958. })(BABYLON || (BABYLON = {}));
  4959. //# sourceMappingURL=babylon.decorators.js.map
  4960. var BABYLON;
  4961. (function (BABYLON) {
  4962. /**
  4963. * A class serves as a medium between the observable and its observers
  4964. */
  4965. var EventState = (function () {
  4966. /**
  4967. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4968. */
  4969. function EventState(mask, skipNextObservers) {
  4970. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4971. this.initalize(mask, skipNextObservers);
  4972. }
  4973. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4974. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4975. this.mask = mask;
  4976. this.skipNextObservers = skipNextObservers;
  4977. return this;
  4978. };
  4979. return EventState;
  4980. }());
  4981. BABYLON.EventState = EventState;
  4982. /**
  4983. * Represent an Observer registered to a given Observable object.
  4984. */
  4985. var Observer = (function () {
  4986. function Observer(callback, mask) {
  4987. this.callback = callback;
  4988. this.mask = mask;
  4989. }
  4990. return Observer;
  4991. }());
  4992. BABYLON.Observer = Observer;
  4993. /**
  4994. * The Observable class is a simple implementation of the Observable pattern.
  4995. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  4996. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4997. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  4998. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  4999. */
  5000. var Observable = (function () {
  5001. function Observable() {
  5002. this._observers = new Array();
  5003. this._eventState = new EventState(0);
  5004. }
  5005. /**
  5006. * Create a new Observer with the specified callback
  5007. * @param callback the callback that will be executed for that Observer
  5008. * @param mask the mask used to filter observers
  5009. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5010. */
  5011. Observable.prototype.add = function (callback, mask, insertFirst) {
  5012. if (mask === void 0) { mask = -1; }
  5013. if (insertFirst === void 0) { insertFirst = false; }
  5014. if (!callback) {
  5015. return null;
  5016. }
  5017. var observer = new Observer(callback, mask);
  5018. if (insertFirst) {
  5019. this._observers.unshift(observer);
  5020. }
  5021. else {
  5022. this._observers.push(observer);
  5023. }
  5024. return observer;
  5025. };
  5026. /**
  5027. * Remove an Observer from the Observable object
  5028. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5029. */
  5030. Observable.prototype.remove = function (observer) {
  5031. var index = this._observers.indexOf(observer);
  5032. if (index !== -1) {
  5033. this._observers.splice(index, 1);
  5034. return true;
  5035. }
  5036. return false;
  5037. };
  5038. /**
  5039. * Remove a callback from the Observable object
  5040. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5041. */
  5042. Observable.prototype.removeCallback = function (callback) {
  5043. for (var index = 0; index < this._observers.length; index++) {
  5044. if (this._observers[index].callback === callback) {
  5045. this._observers.splice(index, 1);
  5046. return true;
  5047. }
  5048. }
  5049. return false;
  5050. };
  5051. /**
  5052. * Notify all Observers by calling their respective callback with the given data
  5053. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5054. * @param eventData
  5055. * @param mask
  5056. */
  5057. Observable.prototype.notifyObservers = function (eventData, mask) {
  5058. if (mask === void 0) { mask = -1; }
  5059. var state = this._eventState;
  5060. state.mask = mask;
  5061. state.skipNextObservers = false;
  5062. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5063. var obs = _a[_i];
  5064. if (obs.mask & mask) {
  5065. obs.callback(eventData, state);
  5066. }
  5067. if (state.skipNextObservers) {
  5068. return false;
  5069. }
  5070. }
  5071. return true;
  5072. };
  5073. /**
  5074. * return true is the Observable has at least one Observer registered
  5075. */
  5076. Observable.prototype.hasObservers = function () {
  5077. return this._observers.length > 0;
  5078. };
  5079. /**
  5080. * Clear the list of observers
  5081. */
  5082. Observable.prototype.clear = function () {
  5083. this._observers = new Array();
  5084. };
  5085. /**
  5086. * Clone the current observable
  5087. */
  5088. Observable.prototype.clone = function () {
  5089. var result = new Observable();
  5090. result._observers = this._observers.slice(0);
  5091. return result;
  5092. };
  5093. /**
  5094. * Does this observable handles observer registered with a given mask
  5095. * @param {number} trigger - the mask to be tested
  5096. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5097. **/
  5098. Observable.prototype.hasSpecificMask = function (mask) {
  5099. if (mask === void 0) { mask = -1; }
  5100. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5101. var obs = _a[_i];
  5102. if (obs.mask & mask && obs.mask === mask) {
  5103. return true;
  5104. }
  5105. }
  5106. return false;
  5107. };
  5108. return Observable;
  5109. }());
  5110. BABYLON.Observable = Observable;
  5111. })(BABYLON || (BABYLON = {}));
  5112. //# sourceMappingURL=babylon.observable.js.map
  5113. var BABYLON;
  5114. (function (BABYLON) {
  5115. var SmartArray = (function () {
  5116. function SmartArray(capacity) {
  5117. this.length = 0;
  5118. this._duplicateId = 0;
  5119. this.data = new Array(capacity);
  5120. this._id = SmartArray._GlobalId++;
  5121. }
  5122. SmartArray.prototype.push = function (value) {
  5123. this.data[this.length++] = value;
  5124. if (this.length > this.data.length) {
  5125. this.data.length *= 2;
  5126. }
  5127. if (!value.__smartArrayFlags) {
  5128. value.__smartArrayFlags = {};
  5129. }
  5130. value.__smartArrayFlags[this._id] = this._duplicateId;
  5131. };
  5132. SmartArray.prototype.forEach = function (func) {
  5133. for (var index = 0; index < this.length; index++) {
  5134. func(this.data[index]);
  5135. }
  5136. };
  5137. SmartArray.prototype.pushNoDuplicate = function (value) {
  5138. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5139. return false;
  5140. }
  5141. this.push(value);
  5142. return true;
  5143. };
  5144. SmartArray.prototype.sort = function (compareFn) {
  5145. this.data.sort(compareFn);
  5146. };
  5147. SmartArray.prototype.reset = function () {
  5148. this.length = 0;
  5149. this._duplicateId++;
  5150. };
  5151. SmartArray.prototype.dispose = function () {
  5152. this.reset();
  5153. this.data.length = 0;
  5154. };
  5155. SmartArray.prototype.concat = function (array) {
  5156. if (array.length === 0) {
  5157. return;
  5158. }
  5159. if (this.length + array.length > this.data.length) {
  5160. this.data.length = (this.length + array.length) * 2;
  5161. }
  5162. for (var index = 0; index < array.length; index++) {
  5163. this.data[this.length++] = (array.data || array)[index];
  5164. }
  5165. };
  5166. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5167. if (array.length === 0) {
  5168. return;
  5169. }
  5170. if (this.length + array.length > this.data.length) {
  5171. this.data.length = (this.length + array.length) * 2;
  5172. }
  5173. for (var index = 0; index < array.length; index++) {
  5174. var item = (array.data || array)[index];
  5175. this.pushNoDuplicate(item);
  5176. }
  5177. };
  5178. SmartArray.prototype.indexOf = function (value) {
  5179. var position = this.data.indexOf(value);
  5180. if (position >= this.length) {
  5181. return -1;
  5182. }
  5183. return position;
  5184. };
  5185. SmartArray.prototype.contains = function (value) {
  5186. return this.data.indexOf(value) !== -1;
  5187. };
  5188. return SmartArray;
  5189. }());
  5190. // Statics
  5191. SmartArray._GlobalId = 0;
  5192. BABYLON.SmartArray = SmartArray;
  5193. })(BABYLON || (BABYLON = {}));
  5194. //# sourceMappingURL=babylon.smartArray.js.map
  5195. var BABYLON;
  5196. (function (BABYLON) {
  5197. // Screenshots
  5198. var screenshotCanvas;
  5199. var cloneValue = function (source, destinationObject) {
  5200. if (!source)
  5201. return null;
  5202. if (source instanceof BABYLON.Mesh) {
  5203. return null;
  5204. }
  5205. if (source instanceof BABYLON.SubMesh) {
  5206. return source.clone(destinationObject);
  5207. }
  5208. else if (source.clone) {
  5209. return source.clone();
  5210. }
  5211. return null;
  5212. };
  5213. var Tools = (function () {
  5214. function Tools() {
  5215. }
  5216. ;
  5217. /**
  5218. * Interpolates between a and b via alpha
  5219. * @param a The lower value (returned when alpha = 0)
  5220. * @param b The upper value (returned when alpha = 1)
  5221. * @param alpha The interpolation-factor
  5222. * @return The mixed value
  5223. */
  5224. Tools.Mix = function (a, b, alpha) {
  5225. return a * (1 - alpha) + b * alpha;
  5226. };
  5227. Tools.Instantiate = function (className) {
  5228. var arr = className.split(".");
  5229. var fn = (window || this);
  5230. for (var i = 0, len = arr.length; i < len; i++) {
  5231. fn = fn[arr[i]];
  5232. }
  5233. if (typeof fn !== "function") {
  5234. return null;
  5235. }
  5236. return fn;
  5237. };
  5238. Tools.SetImmediate = function (action) {
  5239. if (window.setImmediate) {
  5240. window.setImmediate(action);
  5241. }
  5242. else {
  5243. setTimeout(action, 1);
  5244. }
  5245. };
  5246. Tools.IsExponentOfTwo = function (value) {
  5247. var count = 1;
  5248. do {
  5249. count *= 2;
  5250. } while (count < value);
  5251. return count === value;
  5252. };
  5253. /**
  5254. * Find the next highest power of two.
  5255. * @param x Number to start search from.
  5256. * @return Next highest power of two.
  5257. */
  5258. Tools.CeilingPOT = function (x) {
  5259. x--;
  5260. x |= x >> 1;
  5261. x |= x >> 2;
  5262. x |= x >> 4;
  5263. x |= x >> 8;
  5264. x |= x >> 16;
  5265. x++;
  5266. return x;
  5267. };
  5268. /**
  5269. * Find the next lowest power of two.
  5270. * @param x Number to start search from.
  5271. * @return Next lowest power of two.
  5272. */
  5273. Tools.FloorPOT = function (x) {
  5274. x = x | (x >> 1);
  5275. x = x | (x >> 2);
  5276. x = x | (x >> 4);
  5277. x = x | (x >> 8);
  5278. x = x | (x >> 16);
  5279. return x - (x >> 1);
  5280. };
  5281. /**
  5282. * Find the nearest power of two.
  5283. * @param x Number to start search from.
  5284. * @return Next nearest power of two.
  5285. */
  5286. Tools.NearestPOT = function (x) {
  5287. var c = Tools.CeilingPOT(x);
  5288. var f = Tools.FloorPOT(x);
  5289. return (c - x) > (x - f) ? f : c;
  5290. };
  5291. Tools.GetExponentOfTwo = function (value, max, mode) {
  5292. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5293. var pot;
  5294. switch (mode) {
  5295. case BABYLON.Engine.SCALEMODE_FLOOR:
  5296. pot = Tools.FloorPOT(value);
  5297. break;
  5298. case BABYLON.Engine.SCALEMODE_NEAREST:
  5299. pot = Tools.NearestPOT(value);
  5300. break;
  5301. case BABYLON.Engine.SCALEMODE_CEILING:
  5302. pot = Tools.CeilingPOT(value);
  5303. break;
  5304. }
  5305. return Math.min(pot, max);
  5306. };
  5307. Tools.GetFilename = function (path) {
  5308. var index = path.lastIndexOf("/");
  5309. if (index < 0)
  5310. return path;
  5311. return path.substring(index + 1);
  5312. };
  5313. Tools.GetDOMTextContent = function (element) {
  5314. var result = "";
  5315. var child = element.firstChild;
  5316. while (child) {
  5317. if (child.nodeType === 3) {
  5318. result += child.textContent;
  5319. }
  5320. child = child.nextSibling;
  5321. }
  5322. return result;
  5323. };
  5324. Tools.ToDegrees = function (angle) {
  5325. return angle * 180 / Math.PI;
  5326. };
  5327. Tools.ToRadians = function (angle) {
  5328. return angle * Math.PI / 180;
  5329. };
  5330. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5331. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5332. var output = "";
  5333. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5334. var i = 0;
  5335. var bytes = new Uint8Array(buffer);
  5336. while (i < bytes.length) {
  5337. chr1 = bytes[i++];
  5338. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5339. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5340. enc1 = chr1 >> 2;
  5341. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5342. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5343. enc4 = chr3 & 63;
  5344. if (isNaN(chr2)) {
  5345. enc3 = enc4 = 64;
  5346. }
  5347. else if (isNaN(chr3)) {
  5348. enc4 = 64;
  5349. }
  5350. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5351. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5352. }
  5353. return "data:image/png;base64," + output;
  5354. };
  5355. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5356. if (bias === void 0) { bias = null; }
  5357. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5358. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5359. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5360. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5361. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5362. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5363. }
  5364. if (bias) {
  5365. minimum.x -= minimum.x * bias.x + bias.y;
  5366. minimum.y -= minimum.y * bias.x + bias.y;
  5367. minimum.z -= minimum.z * bias.x + bias.y;
  5368. maximum.x += maximum.x * bias.x + bias.y;
  5369. maximum.y += maximum.y * bias.x + bias.y;
  5370. maximum.z += maximum.z * bias.x + bias.y;
  5371. }
  5372. return {
  5373. minimum: minimum,
  5374. maximum: maximum
  5375. };
  5376. };
  5377. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5378. if (bias === void 0) { bias = null; }
  5379. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5380. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5381. if (!stride) {
  5382. stride = 3;
  5383. }
  5384. for (var index = start; index < start + count; index++) {
  5385. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5386. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5387. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5388. }
  5389. if (bias) {
  5390. minimum.x -= minimum.x * bias.x + bias.y;
  5391. minimum.y -= minimum.y * bias.x + bias.y;
  5392. minimum.z -= minimum.z * bias.x + bias.y;
  5393. maximum.x += maximum.x * bias.x + bias.y;
  5394. maximum.y += maximum.y * bias.x + bias.y;
  5395. maximum.z += maximum.z * bias.x + bias.y;
  5396. }
  5397. return {
  5398. minimum: minimum,
  5399. maximum: maximum
  5400. };
  5401. };
  5402. Tools.Vector2ArrayFeeder = function (array) {
  5403. return function (index) {
  5404. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5405. var length = isFloatArray ? array.length / 2 : array.length;
  5406. if (index >= length) {
  5407. return null;
  5408. }
  5409. if (isFloatArray) {
  5410. var fa = array;
  5411. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5412. }
  5413. var a = array;
  5414. return a[index];
  5415. };
  5416. };
  5417. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5418. if (bias === void 0) { bias = null; }
  5419. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5420. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5421. var i = 0;
  5422. var cur = feeder(i++);
  5423. while (cur) {
  5424. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5425. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5426. cur = feeder(i++);
  5427. }
  5428. if (bias) {
  5429. minimum.x -= minimum.x * bias.x + bias.y;
  5430. minimum.y -= minimum.y * bias.x + bias.y;
  5431. maximum.x += maximum.x * bias.x + bias.y;
  5432. maximum.y += maximum.y * bias.x + bias.y;
  5433. }
  5434. return {
  5435. minimum: minimum,
  5436. maximum: maximum
  5437. };
  5438. };
  5439. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5440. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5441. return undefined;
  5442. return Array.isArray(obj) ? obj : [obj];
  5443. };
  5444. // Misc.
  5445. Tools.GetPointerPrefix = function () {
  5446. var eventPrefix = "pointer";
  5447. // Check if pointer events are supported
  5448. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5449. eventPrefix = "mouse";
  5450. }
  5451. return eventPrefix;
  5452. };
  5453. /**
  5454. * @param func - the function to be called
  5455. * @param requester - the object that will request the next frame. Falls back to window.
  5456. */
  5457. Tools.QueueNewFrame = function (func, requester) {
  5458. if (requester === void 0) { requester = window; }
  5459. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5460. /*if(requester.isPresenting) {
  5461. return;
  5462. } else*/ if (requester.requestAnimationFrame)
  5463. requester.requestAnimationFrame(func);
  5464. else if (requester.msRequestAnimationFrame)
  5465. requester.msRequestAnimationFrame(func);
  5466. else if (requester.webkitRequestAnimationFrame)
  5467. requester.webkitRequestAnimationFrame(func);
  5468. else if (requester.mozRequestAnimationFrame)
  5469. requester.mozRequestAnimationFrame(func);
  5470. else if (requester.oRequestAnimationFrame)
  5471. requester.oRequestAnimationFrame(func);
  5472. else {
  5473. window.setTimeout(func, 16);
  5474. }
  5475. };
  5476. Tools.RequestFullscreen = function (element) {
  5477. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5478. if (!requestFunction)
  5479. return;
  5480. requestFunction.call(element);
  5481. };
  5482. Tools.ExitFullscreen = function () {
  5483. if (document.exitFullscreen) {
  5484. document.exitFullscreen();
  5485. }
  5486. else if (document.mozCancelFullScreen) {
  5487. document.mozCancelFullScreen();
  5488. }
  5489. else if (document.webkitCancelFullScreen) {
  5490. document.webkitCancelFullScreen();
  5491. }
  5492. else if (document.msCancelFullScreen) {
  5493. document.msCancelFullScreen();
  5494. }
  5495. };
  5496. Tools.SetCorsBehavior = function (url, img) {
  5497. if (Tools.CorsBehavior) {
  5498. switch (typeof (Tools.CorsBehavior)) {
  5499. case "function":
  5500. var result = Tools.CorsBehavior(url);
  5501. if (result) {
  5502. img.crossOrigin = result;
  5503. }
  5504. break;
  5505. case "string":
  5506. default:
  5507. img.crossOrigin = Tools.CorsBehavior;
  5508. break;
  5509. }
  5510. }
  5511. };
  5512. // External files
  5513. Tools.CleanUrl = function (url) {
  5514. url = url.replace(/#/mg, "%23");
  5515. return url;
  5516. };
  5517. Tools.LoadImage = function (url, onload, onerror, database) {
  5518. if (url instanceof ArrayBuffer) {
  5519. url = Tools.EncodeArrayBufferTobase64(url);
  5520. }
  5521. url = Tools.CleanUrl(url);
  5522. var img = new Image();
  5523. if (url.substr(0, 5) !== "data:") {
  5524. Tools.SetCorsBehavior(url, img);
  5525. }
  5526. img.onload = function () {
  5527. onload(img);
  5528. };
  5529. img.onerror = function (err) {
  5530. Tools.Error("Error while trying to load image: " + url);
  5531. if (Tools.UseFallbackTexture) {
  5532. img.src = Tools.fallbackTexture;
  5533. onload(img);
  5534. }
  5535. else {
  5536. onerror();
  5537. }
  5538. };
  5539. var noIndexedDB = function () {
  5540. img.src = url;
  5541. };
  5542. var loadFromIndexedDB = function () {
  5543. database.loadImageFromDB(url, img);
  5544. };
  5545. //ANY database to do!
  5546. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5547. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5548. }
  5549. else {
  5550. if (url.indexOf("file:") !== 0) {
  5551. noIndexedDB();
  5552. }
  5553. else {
  5554. var textureName = url.substring(5).toLowerCase();
  5555. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5556. try {
  5557. var blobURL;
  5558. try {
  5559. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5560. }
  5561. catch (ex) {
  5562. // Chrome doesn't support oneTimeOnly parameter
  5563. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5564. }
  5565. img.src = blobURL;
  5566. }
  5567. catch (e) {
  5568. img.src = null;
  5569. }
  5570. }
  5571. else {
  5572. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5573. img.src = Tools.fallbackTexture;
  5574. }
  5575. }
  5576. }
  5577. return img;
  5578. };
  5579. //ANY
  5580. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5581. url = Tools.CleanUrl(url);
  5582. var noIndexedDB = function () {
  5583. var request = new XMLHttpRequest();
  5584. var loadUrl = Tools.BaseUrl + url;
  5585. request.open('GET', loadUrl, true);
  5586. if (useArrayBuffer) {
  5587. request.responseType = "arraybuffer";
  5588. }
  5589. request.onprogress = progressCallBack;
  5590. request.onreadystatechange = function () {
  5591. // In case of undefined state in some browsers.
  5592. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5593. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5594. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5595. callback(!useArrayBuffer ? request.responseText : request.response);
  5596. }
  5597. else {
  5598. if (onError) {
  5599. onError(request);
  5600. }
  5601. else {
  5602. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5603. }
  5604. }
  5605. }
  5606. };
  5607. request.send(null);
  5608. };
  5609. var loadFromIndexedDB = function () {
  5610. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5611. };
  5612. if (url.indexOf("file:") !== -1) {
  5613. var fileName = url.substring(5).toLowerCase();
  5614. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5615. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5616. }
  5617. else {
  5618. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5619. }
  5620. }
  5621. else {
  5622. // Caching all files
  5623. if (database && database.enableSceneOffline) {
  5624. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5625. }
  5626. else {
  5627. noIndexedDB();
  5628. }
  5629. }
  5630. };
  5631. /**
  5632. * Load a script (identified by an url). When the url returns, the
  5633. * content of this file is added into a new script element, attached to the DOM (body element)
  5634. */
  5635. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5636. var head = document.getElementsByTagName('head')[0];
  5637. var script = document.createElement('script');
  5638. script.type = 'text/javascript';
  5639. script.src = scriptUrl;
  5640. var self = this;
  5641. script.onload = function () {
  5642. if (onSuccess) {
  5643. onSuccess();
  5644. }
  5645. };
  5646. script.onerror = function () {
  5647. if (onError) {
  5648. onError();
  5649. }
  5650. };
  5651. head.appendChild(script);
  5652. };
  5653. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5654. var reader = new FileReader();
  5655. reader.onload = function (e) {
  5656. //target doesn't have result from ts 1.3
  5657. callback(e.target['result']);
  5658. };
  5659. reader.onprogress = progressCallback;
  5660. reader.readAsDataURL(fileToLoad);
  5661. };
  5662. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5663. var reader = new FileReader();
  5664. reader.onerror = function (e) {
  5665. Tools.Log("Error while reading file: " + fileToLoad.name);
  5666. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5667. };
  5668. reader.onload = function (e) {
  5669. //target doesn't have result from ts 1.3
  5670. callback(e.target['result']);
  5671. };
  5672. reader.onprogress = progressCallBack;
  5673. if (!useArrayBuffer) {
  5674. // Asynchronous read
  5675. reader.readAsText(fileToLoad);
  5676. }
  5677. else {
  5678. reader.readAsArrayBuffer(fileToLoad);
  5679. }
  5680. };
  5681. //returns a downloadable url to a file content.
  5682. Tools.FileAsURL = function (content) {
  5683. var fileBlob = new Blob([content]);
  5684. var url = window.URL || window.webkitURL;
  5685. var link = url.createObjectURL(fileBlob);
  5686. return link;
  5687. };
  5688. // Misc.
  5689. Tools.Format = function (value, decimals) {
  5690. if (decimals === void 0) { decimals = 2; }
  5691. return value.toFixed(decimals);
  5692. };
  5693. Tools.CheckExtends = function (v, min, max) {
  5694. if (v.x < min.x)
  5695. min.x = v.x;
  5696. if (v.y < min.y)
  5697. min.y = v.y;
  5698. if (v.z < min.z)
  5699. min.z = v.z;
  5700. if (v.x > max.x)
  5701. max.x = v.x;
  5702. if (v.y > max.y)
  5703. max.y = v.y;
  5704. if (v.z > max.z)
  5705. max.z = v.z;
  5706. };
  5707. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5708. for (var prop in source) {
  5709. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5710. continue;
  5711. }
  5712. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5713. continue;
  5714. }
  5715. var sourceValue = source[prop];
  5716. var typeOfSourceValue = typeof sourceValue;
  5717. if (typeOfSourceValue === "function") {
  5718. continue;
  5719. }
  5720. if (typeOfSourceValue === "object") {
  5721. if (sourceValue instanceof Array) {
  5722. destination[prop] = [];
  5723. if (sourceValue.length > 0) {
  5724. if (typeof sourceValue[0] == "object") {
  5725. for (var index = 0; index < sourceValue.length; index++) {
  5726. var clonedValue = cloneValue(sourceValue[index], destination);
  5727. if (destination[prop].indexOf(clonedValue) === -1) {
  5728. destination[prop].push(clonedValue);
  5729. }
  5730. }
  5731. }
  5732. else {
  5733. destination[prop] = sourceValue.slice(0);
  5734. }
  5735. }
  5736. }
  5737. else {
  5738. destination[prop] = cloneValue(sourceValue, destination);
  5739. }
  5740. }
  5741. else {
  5742. destination[prop] = sourceValue;
  5743. }
  5744. }
  5745. };
  5746. Tools.IsEmpty = function (obj) {
  5747. for (var i in obj) {
  5748. return false;
  5749. }
  5750. return true;
  5751. };
  5752. Tools.RegisterTopRootEvents = function (events) {
  5753. for (var index = 0; index < events.length; index++) {
  5754. var event = events[index];
  5755. window.addEventListener(event.name, event.handler, false);
  5756. try {
  5757. if (window.parent) {
  5758. window.parent.addEventListener(event.name, event.handler, false);
  5759. }
  5760. }
  5761. catch (e) {
  5762. // Silently fails...
  5763. }
  5764. }
  5765. };
  5766. Tools.UnregisterTopRootEvents = function (events) {
  5767. for (var index = 0; index < events.length; index++) {
  5768. var event = events[index];
  5769. window.removeEventListener(event.name, event.handler);
  5770. try {
  5771. if (window.parent) {
  5772. window.parent.removeEventListener(event.name, event.handler);
  5773. }
  5774. }
  5775. catch (e) {
  5776. // Silently fails...
  5777. }
  5778. }
  5779. };
  5780. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5781. if (mimeType === void 0) { mimeType = "image/png"; }
  5782. // Read the contents of the framebuffer
  5783. var numberOfChannelsByLine = width * 4;
  5784. var halfHeight = height / 2;
  5785. //Reading datas from WebGL
  5786. var data = engine.readPixels(0, 0, width, height);
  5787. //To flip image on Y axis.
  5788. for (var i = 0; i < halfHeight; i++) {
  5789. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5790. var currentCell = j + i * numberOfChannelsByLine;
  5791. var targetLine = height - i - 1;
  5792. var targetCell = j + targetLine * numberOfChannelsByLine;
  5793. var temp = data[currentCell];
  5794. data[currentCell] = data[targetCell];
  5795. data[targetCell] = temp;
  5796. }
  5797. }
  5798. // Create a 2D canvas to store the result
  5799. if (!screenshotCanvas) {
  5800. screenshotCanvas = document.createElement('canvas');
  5801. }
  5802. screenshotCanvas.width = width;
  5803. screenshotCanvas.height = height;
  5804. var context = screenshotCanvas.getContext('2d');
  5805. // Copy the pixels to a 2D canvas
  5806. var imageData = context.createImageData(width, height);
  5807. var castData = (imageData.data);
  5808. castData.set(data);
  5809. context.putImageData(imageData, 0, 0);
  5810. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5811. };
  5812. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5813. if (mimeType === void 0) { mimeType = "image/png"; }
  5814. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5815. if (successCallback) {
  5816. successCallback(base64Image);
  5817. }
  5818. else {
  5819. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5820. if (("download" in document.createElement("a"))) {
  5821. var a = window.document.createElement("a");
  5822. a.href = base64Image;
  5823. var date = new Date();
  5824. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5825. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5826. window.document.body.appendChild(a);
  5827. a.addEventListener("click", function () {
  5828. a.parentElement.removeChild(a);
  5829. });
  5830. a.click();
  5831. //Or opening a new tab with the image if it is not possible to automatically start download.
  5832. }
  5833. else {
  5834. var newWindow = window.open("");
  5835. var img = newWindow.document.createElement("img");
  5836. img.src = base64Image;
  5837. newWindow.document.body.appendChild(img);
  5838. }
  5839. }
  5840. };
  5841. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5842. if (mimeType === void 0) { mimeType = "image/png"; }
  5843. var width;
  5844. var height;
  5845. // If a precision value is specified
  5846. if (size.precision) {
  5847. width = Math.round(engine.getRenderWidth() * size.precision);
  5848. height = Math.round(width / engine.getAspectRatio(camera));
  5849. }
  5850. else if (size.width && size.height) {
  5851. width = size.width;
  5852. height = size.height;
  5853. }
  5854. else if (size.width && !size.height) {
  5855. width = size.width;
  5856. height = Math.round(width / engine.getAspectRatio(camera));
  5857. }
  5858. else if (size.height && !size.width) {
  5859. height = size.height;
  5860. width = Math.round(height * engine.getAspectRatio(camera));
  5861. }
  5862. else if (!isNaN(size)) {
  5863. height = size;
  5864. width = size;
  5865. }
  5866. else {
  5867. Tools.Error("Invalid 'size' parameter !");
  5868. return;
  5869. }
  5870. if (!screenshotCanvas) {
  5871. screenshotCanvas = document.createElement('canvas');
  5872. }
  5873. screenshotCanvas.width = width;
  5874. screenshotCanvas.height = height;
  5875. var renderContext = screenshotCanvas.getContext("2d");
  5876. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5877. var newWidth = width;
  5878. var newHeight = newWidth / ratio;
  5879. if (newHeight > height) {
  5880. newHeight = height;
  5881. newWidth = newHeight * ratio;
  5882. }
  5883. var offsetX = Math.max(0, width - newWidth) / 2;
  5884. var offsetY = Math.max(0, height - newHeight) / 2;
  5885. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5886. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5887. };
  5888. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5889. if (mimeType === void 0) { mimeType = "image/png"; }
  5890. if (samples === void 0) { samples = 1; }
  5891. var width;
  5892. var height;
  5893. //If a precision value is specified
  5894. if (size.precision) {
  5895. width = Math.round(engine.getRenderWidth() * size.precision);
  5896. height = Math.round(width / engine.getAspectRatio(camera));
  5897. size = { width: width, height: height };
  5898. }
  5899. else if (size.width && size.height) {
  5900. width = size.width;
  5901. height = size.height;
  5902. }
  5903. else if (size.width && !size.height) {
  5904. width = size.width;
  5905. height = Math.round(width / engine.getAspectRatio(camera));
  5906. size = { width: width, height: height };
  5907. }
  5908. else if (size.height && !size.width) {
  5909. height = size.height;
  5910. width = Math.round(height * engine.getAspectRatio(camera));
  5911. size = { width: width, height: height };
  5912. }
  5913. else if (!isNaN(size)) {
  5914. height = size;
  5915. width = size;
  5916. }
  5917. else {
  5918. Tools.Error("Invalid 'size' parameter !");
  5919. return;
  5920. }
  5921. var scene = camera.getScene();
  5922. var previousCamera = null;
  5923. if (scene.activeCamera !== camera) {
  5924. previousCamera = scene.activeCamera;
  5925. scene.activeCamera = camera;
  5926. }
  5927. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5928. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5929. texture.renderList = scene.meshes;
  5930. texture.samples = samples;
  5931. texture.onAfterRenderObservable.add(function () {
  5932. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5933. });
  5934. scene.incrementRenderId();
  5935. scene.resetCachedMaterial();
  5936. texture.render(true);
  5937. texture.dispose();
  5938. if (previousCamera) {
  5939. scene.activeCamera = previousCamera;
  5940. }
  5941. camera.getProjectionMatrix(true); // Force cache refresh;
  5942. };
  5943. // XHR response validator for local file scenario
  5944. Tools.ValidateXHRData = function (xhr, dataType) {
  5945. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5946. if (dataType === void 0) { dataType = 7; }
  5947. try {
  5948. if (dataType & 1) {
  5949. if (xhr.responseText && xhr.responseText.length > 0) {
  5950. return true;
  5951. }
  5952. else if (dataType === 1) {
  5953. return false;
  5954. }
  5955. }
  5956. if (dataType & 2) {
  5957. // Check header width and height since there is no "TGA" magic number
  5958. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5959. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5960. return true;
  5961. }
  5962. else if (dataType === 2) {
  5963. return false;
  5964. }
  5965. }
  5966. if (dataType & 4) {
  5967. // Check for the "DDS" magic number
  5968. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5969. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5970. return true;
  5971. }
  5972. else {
  5973. return false;
  5974. }
  5975. }
  5976. }
  5977. catch (e) {
  5978. // Global protection
  5979. }
  5980. return false;
  5981. };
  5982. /**
  5983. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5984. * Be aware Math.random() could cause collisions, but:
  5985. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  5986. */
  5987. Tools.RandomId = function () {
  5988. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5989. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5990. return v.toString(16);
  5991. });
  5992. };
  5993. Object.defineProperty(Tools, "NoneLogLevel", {
  5994. get: function () {
  5995. return Tools._NoneLogLevel;
  5996. },
  5997. enumerable: true,
  5998. configurable: true
  5999. });
  6000. Object.defineProperty(Tools, "MessageLogLevel", {
  6001. get: function () {
  6002. return Tools._MessageLogLevel;
  6003. },
  6004. enumerable: true,
  6005. configurable: true
  6006. });
  6007. Object.defineProperty(Tools, "WarningLogLevel", {
  6008. get: function () {
  6009. return Tools._WarningLogLevel;
  6010. },
  6011. enumerable: true,
  6012. configurable: true
  6013. });
  6014. Object.defineProperty(Tools, "ErrorLogLevel", {
  6015. get: function () {
  6016. return Tools._ErrorLogLevel;
  6017. },
  6018. enumerable: true,
  6019. configurable: true
  6020. });
  6021. Object.defineProperty(Tools, "AllLogLevel", {
  6022. get: function () {
  6023. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6024. },
  6025. enumerable: true,
  6026. configurable: true
  6027. });
  6028. Tools._AddLogEntry = function (entry) {
  6029. Tools._LogCache = entry + Tools._LogCache;
  6030. if (Tools.OnNewCacheEntry) {
  6031. Tools.OnNewCacheEntry(entry);
  6032. }
  6033. };
  6034. Tools._FormatMessage = function (message) {
  6035. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6036. var date = new Date();
  6037. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6038. };
  6039. Tools._LogDisabled = function (message) {
  6040. // nothing to do
  6041. };
  6042. Tools._LogEnabled = function (message) {
  6043. var formattedMessage = Tools._FormatMessage(message);
  6044. console.log("BJS - " + formattedMessage);
  6045. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6046. Tools._AddLogEntry(entry);
  6047. };
  6048. Tools._WarnDisabled = function (message) {
  6049. // nothing to do
  6050. };
  6051. Tools._WarnEnabled = function (message) {
  6052. var formattedMessage = Tools._FormatMessage(message);
  6053. console.warn("BJS - " + formattedMessage);
  6054. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6055. Tools._AddLogEntry(entry);
  6056. };
  6057. Tools._ErrorDisabled = function (message) {
  6058. // nothing to do
  6059. };
  6060. Tools._ErrorEnabled = function (message) {
  6061. Tools.errorsCount++;
  6062. var formattedMessage = Tools._FormatMessage(message);
  6063. console.error("BJS - " + formattedMessage);
  6064. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6065. Tools._AddLogEntry(entry);
  6066. };
  6067. Object.defineProperty(Tools, "LogCache", {
  6068. get: function () {
  6069. return Tools._LogCache;
  6070. },
  6071. enumerable: true,
  6072. configurable: true
  6073. });
  6074. Tools.ClearLogCache = function () {
  6075. Tools._LogCache = "";
  6076. Tools.errorsCount = 0;
  6077. };
  6078. Object.defineProperty(Tools, "LogLevels", {
  6079. set: function (level) {
  6080. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6081. Tools.Log = Tools._LogEnabled;
  6082. }
  6083. else {
  6084. Tools.Log = Tools._LogDisabled;
  6085. }
  6086. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6087. Tools.Warn = Tools._WarnEnabled;
  6088. }
  6089. else {
  6090. Tools.Warn = Tools._WarnDisabled;
  6091. }
  6092. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6093. Tools.Error = Tools._ErrorEnabled;
  6094. }
  6095. else {
  6096. Tools.Error = Tools._ErrorDisabled;
  6097. }
  6098. },
  6099. enumerable: true,
  6100. configurable: true
  6101. });
  6102. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6103. get: function () {
  6104. return Tools._PerformanceNoneLogLevel;
  6105. },
  6106. enumerable: true,
  6107. configurable: true
  6108. });
  6109. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6110. get: function () {
  6111. return Tools._PerformanceUserMarkLogLevel;
  6112. },
  6113. enumerable: true,
  6114. configurable: true
  6115. });
  6116. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6117. get: function () {
  6118. return Tools._PerformanceConsoleLogLevel;
  6119. },
  6120. enumerable: true,
  6121. configurable: true
  6122. });
  6123. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6124. set: function (level) {
  6125. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6126. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6127. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6128. return;
  6129. }
  6130. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6131. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6132. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6133. return;
  6134. }
  6135. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6136. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6137. },
  6138. enumerable: true,
  6139. configurable: true
  6140. });
  6141. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6142. };
  6143. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6144. };
  6145. Tools._StartUserMark = function (counterName, condition) {
  6146. if (condition === void 0) { condition = true; }
  6147. if (!condition || !Tools._performance.mark) {
  6148. return;
  6149. }
  6150. Tools._performance.mark(counterName + "-Begin");
  6151. };
  6152. Tools._EndUserMark = function (counterName, condition) {
  6153. if (condition === void 0) { condition = true; }
  6154. if (!condition || !Tools._performance.mark) {
  6155. return;
  6156. }
  6157. Tools._performance.mark(counterName + "-End");
  6158. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6159. };
  6160. Tools._StartPerformanceConsole = function (counterName, condition) {
  6161. if (condition === void 0) { condition = true; }
  6162. if (!condition) {
  6163. return;
  6164. }
  6165. Tools._StartUserMark(counterName, condition);
  6166. if (console.time) {
  6167. console.time(counterName);
  6168. }
  6169. };
  6170. Tools._EndPerformanceConsole = function (counterName, condition) {
  6171. if (condition === void 0) { condition = true; }
  6172. if (!condition) {
  6173. return;
  6174. }
  6175. Tools._EndUserMark(counterName, condition);
  6176. if (console.time) {
  6177. console.timeEnd(counterName);
  6178. }
  6179. };
  6180. Object.defineProperty(Tools, "Now", {
  6181. get: function () {
  6182. if (window.performance && window.performance.now) {
  6183. return window.performance.now();
  6184. }
  6185. return new Date().getTime();
  6186. },
  6187. enumerable: true,
  6188. configurable: true
  6189. });
  6190. /**
  6191. * This method will return the name of the class used to create the instance of the given object.
  6192. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6193. * @param object the object to get the class name from
  6194. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6195. */
  6196. Tools.getClassName = function (object, isType) {
  6197. if (isType === void 0) { isType = false; }
  6198. var name = null;
  6199. if (!isType && object.getClassName) {
  6200. name = object.getClassName();
  6201. }
  6202. else {
  6203. if (object instanceof Object) {
  6204. var classObj = isType ? object : Object.getPrototypeOf(object);
  6205. name = classObj.constructor["__bjsclassName__"];
  6206. }
  6207. if (!name) {
  6208. name = typeof object;
  6209. }
  6210. }
  6211. return name;
  6212. };
  6213. Tools.first = function (array, predicate) {
  6214. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6215. var el = array_1[_i];
  6216. if (predicate(el)) {
  6217. return el;
  6218. }
  6219. }
  6220. };
  6221. /**
  6222. * This method will return the name of the full name of the class, including its owning module (if any).
  6223. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6224. * @param object the object to get the class name from
  6225. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6226. */
  6227. Tools.getFullClassName = function (object, isType) {
  6228. if (isType === void 0) { isType = false; }
  6229. var className = null;
  6230. var moduleName = null;
  6231. if (!isType && object.getClassName) {
  6232. className = object.getClassName();
  6233. }
  6234. else {
  6235. if (object instanceof Object) {
  6236. var classObj = isType ? object : Object.getPrototypeOf(object);
  6237. className = classObj.constructor["__bjsclassName__"];
  6238. moduleName = classObj.constructor["__bjsmoduleName__"];
  6239. }
  6240. if (!className) {
  6241. className = typeof object;
  6242. }
  6243. }
  6244. if (!className) {
  6245. return null;
  6246. }
  6247. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6248. };
  6249. /**
  6250. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6251. * @param array
  6252. */
  6253. Tools.arrayOrStringFeeder = function (array) {
  6254. return function (index) {
  6255. if (index >= array.length) {
  6256. return null;
  6257. }
  6258. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6259. if (val && val.getHashCode) {
  6260. val = val.getHashCode();
  6261. }
  6262. if (typeof val === "string") {
  6263. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6264. }
  6265. return val;
  6266. };
  6267. };
  6268. /**
  6269. * Compute the hashCode of a stream of number
  6270. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6271. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6272. * @return the hash code computed
  6273. */
  6274. Tools.hashCodeFromStream = function (feeder) {
  6275. // Based from here: http://stackoverflow.com/a/7616484/802124
  6276. var hash = 0;
  6277. var index = 0;
  6278. var chr = feeder(index++);
  6279. while (chr != null) {
  6280. hash = ((hash << 5) - hash) + chr;
  6281. hash |= 0; // Convert to 32bit integer
  6282. chr = feeder(index++);
  6283. }
  6284. return hash;
  6285. };
  6286. return Tools;
  6287. }());
  6288. Tools.BaseUrl = "";
  6289. Tools.CorsBehavior = "anonymous";
  6290. Tools.UseFallbackTexture = true;
  6291. // Used in case of a texture loading problem
  6292. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  6293. // Logs
  6294. Tools._NoneLogLevel = 0;
  6295. Tools._MessageLogLevel = 1;
  6296. Tools._WarningLogLevel = 2;
  6297. Tools._ErrorLogLevel = 4;
  6298. Tools._LogCache = "";
  6299. Tools.errorsCount = 0;
  6300. Tools.Log = Tools._LogEnabled;
  6301. Tools.Warn = Tools._WarnEnabled;
  6302. Tools.Error = Tools._ErrorEnabled;
  6303. // Performances
  6304. Tools._PerformanceNoneLogLevel = 0;
  6305. Tools._PerformanceUserMarkLogLevel = 1;
  6306. Tools._PerformanceConsoleLogLevel = 2;
  6307. Tools._performance = window.performance;
  6308. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6309. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6310. BABYLON.Tools = Tools;
  6311. /**
  6312. * This class is used to track a performance counter which is number based.
  6313. * The user has access to many properties which give statistics of different nature
  6314. *
  6315. * The implementer can track two kinds of Performance Counter: time and count
  6316. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6317. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6318. */
  6319. var PerfCounter = (function () {
  6320. function PerfCounter() {
  6321. this._startMonitoringTime = 0;
  6322. this._min = 0;
  6323. this._max = 0;
  6324. this._average = 0;
  6325. this._lastSecAverage = 0;
  6326. this._current = 0;
  6327. this._totalValueCount = 0;
  6328. this._totalAccumulated = 0;
  6329. this._lastSecAccumulated = 0;
  6330. this._lastSecTime = 0;
  6331. this._lastSecValueCount = 0;
  6332. }
  6333. Object.defineProperty(PerfCounter.prototype, "min", {
  6334. /**
  6335. * Returns the smallest value ever
  6336. */
  6337. get: function () {
  6338. return this._min;
  6339. },
  6340. enumerable: true,
  6341. configurable: true
  6342. });
  6343. Object.defineProperty(PerfCounter.prototype, "max", {
  6344. /**
  6345. * Returns the biggest value ever
  6346. */
  6347. get: function () {
  6348. return this._max;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(PerfCounter.prototype, "average", {
  6354. /**
  6355. * Returns the average value since the performance counter is running
  6356. */
  6357. get: function () {
  6358. return this._average;
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6364. /**
  6365. * Returns the average value of the last second the counter was monitored
  6366. */
  6367. get: function () {
  6368. return this._lastSecAverage;
  6369. },
  6370. enumerable: true,
  6371. configurable: true
  6372. });
  6373. Object.defineProperty(PerfCounter.prototype, "current", {
  6374. /**
  6375. * Returns the current value
  6376. */
  6377. get: function () {
  6378. return this._current;
  6379. },
  6380. enumerable: true,
  6381. configurable: true
  6382. });
  6383. Object.defineProperty(PerfCounter.prototype, "total", {
  6384. get: function () {
  6385. return this._totalAccumulated;
  6386. },
  6387. enumerable: true,
  6388. configurable: true
  6389. });
  6390. /**
  6391. * Call this method to start monitoring a new frame.
  6392. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6393. */
  6394. PerfCounter.prototype.fetchNewFrame = function () {
  6395. this._totalValueCount++;
  6396. this._current = 0;
  6397. this._lastSecValueCount++;
  6398. };
  6399. /**
  6400. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6401. * @param newCount the count value to add to the monitored count
  6402. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6403. */
  6404. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6405. if (!PerfCounter.Enabled) {
  6406. return;
  6407. }
  6408. this._current += newCount;
  6409. if (fetchResult) {
  6410. this._fetchResult();
  6411. }
  6412. };
  6413. /**
  6414. * Start monitoring this performance counter
  6415. */
  6416. PerfCounter.prototype.beginMonitoring = function () {
  6417. if (!PerfCounter.Enabled) {
  6418. return;
  6419. }
  6420. this._startMonitoringTime = Tools.Now;
  6421. };
  6422. /**
  6423. * Compute the time lapsed since the previous beginMonitoring() call.
  6424. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  6425. */
  6426. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6427. if (newFrame === void 0) { newFrame = true; }
  6428. if (!PerfCounter.Enabled) {
  6429. return;
  6430. }
  6431. if (newFrame) {
  6432. this.fetchNewFrame();
  6433. }
  6434. var currentTime = Tools.Now;
  6435. this._current = currentTime - this._startMonitoringTime;
  6436. if (newFrame) {
  6437. this._fetchResult();
  6438. }
  6439. };
  6440. PerfCounter.prototype._fetchResult = function () {
  6441. this._totalAccumulated += this._current;
  6442. this._lastSecAccumulated += this._current;
  6443. // Min/Max update
  6444. this._min = Math.min(this._min, this._current);
  6445. this._max = Math.max(this._max, this._current);
  6446. this._average = this._totalAccumulated / this._totalValueCount;
  6447. // Reset last sec?
  6448. var now = Tools.Now;
  6449. if ((now - this._lastSecTime) > 1000) {
  6450. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6451. this._lastSecTime = now;
  6452. this._lastSecAccumulated = 0;
  6453. this._lastSecValueCount = 0;
  6454. }
  6455. };
  6456. return PerfCounter;
  6457. }());
  6458. PerfCounter.Enabled = true;
  6459. BABYLON.PerfCounter = PerfCounter;
  6460. /**
  6461. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6462. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6463. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6464. * @param name The name of the class, case should be preserved
  6465. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6466. */
  6467. function className(name, module) {
  6468. return function (target) {
  6469. target["__bjsclassName__"] = name;
  6470. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6471. };
  6472. }
  6473. BABYLON.className = className;
  6474. /**
  6475. * An implementation of a loop for asynchronous functions.
  6476. */
  6477. var AsyncLoop = (function () {
  6478. /**
  6479. * Constroctor.
  6480. * @param iterations the number of iterations.
  6481. * @param _fn the function to run each iteration
  6482. * @param _successCallback the callback that will be called upon succesful execution
  6483. * @param offset starting offset.
  6484. */
  6485. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6486. if (offset === void 0) { offset = 0; }
  6487. this.iterations = iterations;
  6488. this._fn = _fn;
  6489. this._successCallback = _successCallback;
  6490. this.index = offset - 1;
  6491. this._done = false;
  6492. }
  6493. /**
  6494. * Execute the next iteration. Must be called after the last iteration was finished.
  6495. */
  6496. AsyncLoop.prototype.executeNext = function () {
  6497. if (!this._done) {
  6498. if (this.index + 1 < this.iterations) {
  6499. ++this.index;
  6500. this._fn(this);
  6501. }
  6502. else {
  6503. this.breakLoop();
  6504. }
  6505. }
  6506. };
  6507. /**
  6508. * Break the loop and run the success callback.
  6509. */
  6510. AsyncLoop.prototype.breakLoop = function () {
  6511. this._done = true;
  6512. this._successCallback();
  6513. };
  6514. /**
  6515. * Helper function
  6516. */
  6517. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6518. if (offset === void 0) { offset = 0; }
  6519. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6520. loop.executeNext();
  6521. return loop;
  6522. };
  6523. /**
  6524. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6525. * @param iterations total number of iterations
  6526. * @param syncedIterations number of synchronous iterations in each async iteration.
  6527. * @param fn the function to call each iteration.
  6528. * @param callback a success call back that will be called when iterating stops.
  6529. * @param breakFunction a break condition (optional)
  6530. * @param timeout timeout settings for the setTimeout function. default - 0.
  6531. * @constructor
  6532. */
  6533. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6534. if (timeout === void 0) { timeout = 0; }
  6535. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6536. if (breakFunction && breakFunction())
  6537. loop.breakLoop();
  6538. else {
  6539. setTimeout(function () {
  6540. for (var i = 0; i < syncedIterations; ++i) {
  6541. var iteration = (loop.index * syncedIterations) + i;
  6542. if (iteration >= iterations)
  6543. break;
  6544. fn(iteration);
  6545. if (breakFunction && breakFunction()) {
  6546. loop.breakLoop();
  6547. break;
  6548. }
  6549. }
  6550. loop.executeNext();
  6551. }, timeout);
  6552. }
  6553. }, callback);
  6554. };
  6555. return AsyncLoop;
  6556. }());
  6557. BABYLON.AsyncLoop = AsyncLoop;
  6558. })(BABYLON || (BABYLON = {}));
  6559. //# sourceMappingURL=babylon.tools.js.map
  6560. var BABYLON;
  6561. (function (BABYLON) {
  6562. var Internals;
  6563. (function (Internals) {
  6564. var _AlphaState = (function () {
  6565. /**
  6566. * Initializes the state.
  6567. */
  6568. function _AlphaState() {
  6569. this._isAlphaBlendDirty = false;
  6570. this._isBlendFunctionParametersDirty = false;
  6571. this._isBlendEquationParametersDirty = false;
  6572. this._isBlendConstantsDirty = false;
  6573. this._alphaBlend = false;
  6574. this._blendFunctionParameters = new Array(4);
  6575. this._blendEquationParameters = new Array(2);
  6576. this._blendConstants = new Array(4);
  6577. this.reset();
  6578. }
  6579. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6580. get: function () {
  6581. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6582. },
  6583. enumerable: true,
  6584. configurable: true
  6585. });
  6586. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6587. get: function () {
  6588. return this._alphaBlend;
  6589. },
  6590. set: function (value) {
  6591. if (this._alphaBlend === value) {
  6592. return;
  6593. }
  6594. this._alphaBlend = value;
  6595. this._isAlphaBlendDirty = true;
  6596. },
  6597. enumerable: true,
  6598. configurable: true
  6599. });
  6600. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6601. if (this._blendConstants[0] === r &&
  6602. this._blendConstants[1] === g &&
  6603. this._blendConstants[2] === b &&
  6604. this._blendConstants[3] === a) {
  6605. return;
  6606. }
  6607. this._blendConstants[0] = r;
  6608. this._blendConstants[1] = g;
  6609. this._blendConstants[2] = b;
  6610. this._blendConstants[3] = a;
  6611. this._isBlendConstantsDirty = true;
  6612. };
  6613. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6614. if (this._blendFunctionParameters[0] === value0 &&
  6615. this._blendFunctionParameters[1] === value1 &&
  6616. this._blendFunctionParameters[2] === value2 &&
  6617. this._blendFunctionParameters[3] === value3) {
  6618. return;
  6619. }
  6620. this._blendFunctionParameters[0] = value0;
  6621. this._blendFunctionParameters[1] = value1;
  6622. this._blendFunctionParameters[2] = value2;
  6623. this._blendFunctionParameters[3] = value3;
  6624. this._isBlendFunctionParametersDirty = true;
  6625. };
  6626. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6627. if (this._blendEquationParameters[0] === rgb &&
  6628. this._blendEquationParameters[1] === alpha) {
  6629. return;
  6630. }
  6631. this._blendEquationParameters[0] = rgb;
  6632. this._blendEquationParameters[1] = alpha;
  6633. this._isBlendEquationParametersDirty = true;
  6634. };
  6635. _AlphaState.prototype.reset = function () {
  6636. this._alphaBlend = false;
  6637. this._blendFunctionParameters[0] = null;
  6638. this._blendFunctionParameters[1] = null;
  6639. this._blendFunctionParameters[2] = null;
  6640. this._blendFunctionParameters[3] = null;
  6641. this._blendEquationParameters[0] = null;
  6642. this._blendEquationParameters[1] = null;
  6643. this._blendConstants[0] = null;
  6644. this._blendConstants[1] = null;
  6645. this._blendConstants[2] = null;
  6646. this._blendConstants[3] = null;
  6647. this._isAlphaBlendDirty = true;
  6648. this._isBlendFunctionParametersDirty = false;
  6649. this._isBlendEquationParametersDirty = false;
  6650. this._isBlendConstantsDirty = false;
  6651. };
  6652. _AlphaState.prototype.apply = function (gl) {
  6653. if (!this.isDirty) {
  6654. return;
  6655. }
  6656. // Alpha blend
  6657. if (this._isAlphaBlendDirty) {
  6658. if (this._alphaBlend) {
  6659. gl.enable(gl.BLEND);
  6660. }
  6661. else {
  6662. gl.disable(gl.BLEND);
  6663. }
  6664. this._isAlphaBlendDirty = false;
  6665. }
  6666. // Alpha function
  6667. if (this._isBlendFunctionParametersDirty) {
  6668. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6669. this._isBlendFunctionParametersDirty = false;
  6670. }
  6671. // Alpha equation
  6672. if (this._isBlendEquationParametersDirty) {
  6673. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6674. this._isBlendEquationParametersDirty = false;
  6675. }
  6676. // Constants
  6677. if (this._isBlendConstantsDirty) {
  6678. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6679. this._isBlendConstantsDirty = false;
  6680. }
  6681. };
  6682. return _AlphaState;
  6683. }());
  6684. Internals._AlphaState = _AlphaState;
  6685. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6686. })(BABYLON || (BABYLON = {}));
  6687. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6688. var BABYLON;
  6689. (function (BABYLON) {
  6690. var Internals;
  6691. (function (Internals) {
  6692. var _DepthCullingState = (function () {
  6693. /**
  6694. * Initializes the state.
  6695. */
  6696. function _DepthCullingState() {
  6697. this._isDepthTestDirty = false;
  6698. this._isDepthMaskDirty = false;
  6699. this._isDepthFuncDirty = false;
  6700. this._isCullFaceDirty = false;
  6701. this._isCullDirty = false;
  6702. this._isZOffsetDirty = false;
  6703. this.reset();
  6704. }
  6705. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6706. get: function () {
  6707. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6708. },
  6709. enumerable: true,
  6710. configurable: true
  6711. });
  6712. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6713. get: function () {
  6714. return this._zOffset;
  6715. },
  6716. set: function (value) {
  6717. if (this._zOffset === value) {
  6718. return;
  6719. }
  6720. this._zOffset = value;
  6721. this._isZOffsetDirty = true;
  6722. },
  6723. enumerable: true,
  6724. configurable: true
  6725. });
  6726. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6727. get: function () {
  6728. return this._cullFace;
  6729. },
  6730. set: function (value) {
  6731. if (this._cullFace === value) {
  6732. return;
  6733. }
  6734. this._cullFace = value;
  6735. this._isCullFaceDirty = true;
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6741. get: function () {
  6742. return this._cull;
  6743. },
  6744. set: function (value) {
  6745. if (this._cull === value) {
  6746. return;
  6747. }
  6748. this._cull = value;
  6749. this._isCullDirty = true;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6755. get: function () {
  6756. return this._depthFunc;
  6757. },
  6758. set: function (value) {
  6759. if (this._depthFunc === value) {
  6760. return;
  6761. }
  6762. this._depthFunc = value;
  6763. this._isDepthFuncDirty = true;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6769. get: function () {
  6770. return this._depthMask;
  6771. },
  6772. set: function (value) {
  6773. if (this._depthMask === value) {
  6774. return;
  6775. }
  6776. this._depthMask = value;
  6777. this._isDepthMaskDirty = true;
  6778. },
  6779. enumerable: true,
  6780. configurable: true
  6781. });
  6782. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6783. get: function () {
  6784. return this._depthTest;
  6785. },
  6786. set: function (value) {
  6787. if (this._depthTest === value) {
  6788. return;
  6789. }
  6790. this._depthTest = value;
  6791. this._isDepthTestDirty = true;
  6792. },
  6793. enumerable: true,
  6794. configurable: true
  6795. });
  6796. _DepthCullingState.prototype.reset = function () {
  6797. this._depthMask = true;
  6798. this._depthTest = true;
  6799. this._depthFunc = null;
  6800. this._cullFace = null;
  6801. this._cull = null;
  6802. this._zOffset = 0;
  6803. this._isDepthTestDirty = true;
  6804. this._isDepthMaskDirty = true;
  6805. this._isDepthFuncDirty = false;
  6806. this._isCullFaceDirty = false;
  6807. this._isCullDirty = false;
  6808. this._isZOffsetDirty = false;
  6809. };
  6810. _DepthCullingState.prototype.apply = function (gl) {
  6811. if (!this.isDirty) {
  6812. return;
  6813. }
  6814. // Cull
  6815. if (this._isCullDirty) {
  6816. if (this.cull) {
  6817. gl.enable(gl.CULL_FACE);
  6818. }
  6819. else {
  6820. gl.disable(gl.CULL_FACE);
  6821. }
  6822. this._isCullDirty = false;
  6823. }
  6824. // Cull face
  6825. if (this._isCullFaceDirty) {
  6826. gl.cullFace(this.cullFace);
  6827. this._isCullFaceDirty = false;
  6828. }
  6829. // Depth mask
  6830. if (this._isDepthMaskDirty) {
  6831. gl.depthMask(this.depthMask);
  6832. this._isDepthMaskDirty = false;
  6833. }
  6834. // Depth test
  6835. if (this._isDepthTestDirty) {
  6836. if (this.depthTest) {
  6837. gl.enable(gl.DEPTH_TEST);
  6838. }
  6839. else {
  6840. gl.disable(gl.DEPTH_TEST);
  6841. }
  6842. this._isDepthTestDirty = false;
  6843. }
  6844. // Depth func
  6845. if (this._isDepthFuncDirty) {
  6846. gl.depthFunc(this.depthFunc);
  6847. this._isDepthFuncDirty = false;
  6848. }
  6849. // zOffset
  6850. if (this._isZOffsetDirty) {
  6851. if (this.zOffset) {
  6852. gl.enable(gl.POLYGON_OFFSET_FILL);
  6853. gl.polygonOffset(this.zOffset, 0);
  6854. }
  6855. else {
  6856. gl.disable(gl.POLYGON_OFFSET_FILL);
  6857. }
  6858. this._isZOffsetDirty = false;
  6859. }
  6860. };
  6861. return _DepthCullingState;
  6862. }());
  6863. Internals._DepthCullingState = _DepthCullingState;
  6864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6865. })(BABYLON || (BABYLON = {}));
  6866. //# sourceMappingURL=babylon.depthCullingState.js.map
  6867. var BABYLON;
  6868. (function (BABYLON) {
  6869. var Internals;
  6870. (function (Internals) {
  6871. var _StencilState = (function () {
  6872. function _StencilState() {
  6873. this._isStencilTestDirty = false;
  6874. this._isStencilMaskDirty = false;
  6875. this._isStencilFuncDirty = false;
  6876. this._isStencilOpDirty = false;
  6877. this.reset();
  6878. }
  6879. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6880. get: function () {
  6881. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6882. },
  6883. enumerable: true,
  6884. configurable: true
  6885. });
  6886. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6887. get: function () {
  6888. return this._stencilFunc;
  6889. },
  6890. set: function (value) {
  6891. if (this._stencilFunc === value) {
  6892. return;
  6893. }
  6894. this._stencilFunc = value;
  6895. this._isStencilFuncDirty = true;
  6896. },
  6897. enumerable: true,
  6898. configurable: true
  6899. });
  6900. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6901. get: function () {
  6902. return this._stencilFuncRef;
  6903. },
  6904. set: function (value) {
  6905. if (this._stencilFuncRef === value) {
  6906. return;
  6907. }
  6908. this._stencilFuncRef = value;
  6909. this._isStencilFuncDirty = true;
  6910. },
  6911. enumerable: true,
  6912. configurable: true
  6913. });
  6914. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6915. get: function () {
  6916. return this._stencilFuncMask;
  6917. },
  6918. set: function (value) {
  6919. if (this._stencilFuncMask === value) {
  6920. return;
  6921. }
  6922. this._stencilFuncMask = value;
  6923. this._isStencilFuncDirty = true;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6929. get: function () {
  6930. return this._stencilOpStencilFail;
  6931. },
  6932. set: function (value) {
  6933. if (this._stencilOpStencilFail === value) {
  6934. return;
  6935. }
  6936. this._stencilOpStencilFail = value;
  6937. this._isStencilOpDirty = true;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6943. get: function () {
  6944. return this._stencilOpDepthFail;
  6945. },
  6946. set: function (value) {
  6947. if (this._stencilOpDepthFail === value) {
  6948. return;
  6949. }
  6950. this._stencilOpDepthFail = value;
  6951. this._isStencilOpDirty = true;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6957. get: function () {
  6958. return this._stencilOpStencilDepthPass;
  6959. },
  6960. set: function (value) {
  6961. if (this._stencilOpStencilDepthPass === value) {
  6962. return;
  6963. }
  6964. this._stencilOpStencilDepthPass = value;
  6965. this._isStencilOpDirty = true;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6971. get: function () {
  6972. return this._stencilMask;
  6973. },
  6974. set: function (value) {
  6975. if (this._stencilMask === value) {
  6976. return;
  6977. }
  6978. this._stencilMask = value;
  6979. this._isStencilMaskDirty = true;
  6980. },
  6981. enumerable: true,
  6982. configurable: true
  6983. });
  6984. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6985. get: function () {
  6986. return this._stencilTest;
  6987. },
  6988. set: function (value) {
  6989. if (this._stencilTest === value) {
  6990. return;
  6991. }
  6992. this._stencilTest = value;
  6993. this._isStencilTestDirty = true;
  6994. },
  6995. enumerable: true,
  6996. configurable: true
  6997. });
  6998. _StencilState.prototype.reset = function () {
  6999. this._stencilTest = false;
  7000. this._stencilMask = 0xFF;
  7001. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7002. this._stencilFuncRef = 1;
  7003. this._stencilFuncMask = 0xFF;
  7004. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7005. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7006. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7007. this._isStencilTestDirty = true;
  7008. this._isStencilMaskDirty = true;
  7009. this._isStencilFuncDirty = true;
  7010. this._isStencilOpDirty = true;
  7011. };
  7012. _StencilState.prototype.apply = function (gl) {
  7013. if (!this.isDirty) {
  7014. return;
  7015. }
  7016. // Stencil test
  7017. if (this._isStencilTestDirty) {
  7018. if (this.stencilTest) {
  7019. gl.enable(gl.STENCIL_TEST);
  7020. }
  7021. else {
  7022. gl.disable(gl.STENCIL_TEST);
  7023. }
  7024. this._isStencilTestDirty = false;
  7025. }
  7026. // Stencil mask
  7027. if (this._isStencilMaskDirty) {
  7028. gl.stencilMask(this.stencilMask);
  7029. this._isStencilMaskDirty = false;
  7030. }
  7031. // Stencil func
  7032. if (this._isStencilFuncDirty) {
  7033. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7034. this._isStencilFuncDirty = false;
  7035. }
  7036. // Stencil op
  7037. if (this._isStencilOpDirty) {
  7038. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7039. this._isStencilOpDirty = false;
  7040. }
  7041. };
  7042. return _StencilState;
  7043. }());
  7044. Internals._StencilState = _StencilState;
  7045. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7046. })(BABYLON || (BABYLON = {}));
  7047. //# sourceMappingURL=babylon.stencilState.js.map
  7048. var BABYLON;
  7049. (function (BABYLON) {
  7050. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7051. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7052. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7053. gl.compileShader(shader);
  7054. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7055. throw new Error(gl.getShaderInfoLog(shader));
  7056. }
  7057. return shader;
  7058. };
  7059. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7060. var magFilter = gl.NEAREST;
  7061. var minFilter = gl.NEAREST;
  7062. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7063. magFilter = gl.LINEAR;
  7064. if (generateMipMaps) {
  7065. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7066. }
  7067. else {
  7068. minFilter = gl.LINEAR;
  7069. }
  7070. }
  7071. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7072. magFilter = gl.LINEAR;
  7073. if (generateMipMaps) {
  7074. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7075. }
  7076. else {
  7077. minFilter = gl.LINEAR;
  7078. }
  7079. }
  7080. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7081. magFilter = gl.NEAREST;
  7082. if (generateMipMaps) {
  7083. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7084. }
  7085. else {
  7086. minFilter = gl.NEAREST;
  7087. }
  7088. }
  7089. return {
  7090. min: minFilter,
  7091. mag: magFilter
  7092. };
  7093. };
  7094. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7096. var engine = scene.getEngine();
  7097. if (!engine) {
  7098. return;
  7099. }
  7100. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7101. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7102. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7103. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7104. texture._baseWidth = width;
  7105. texture._baseHeight = height;
  7106. texture._width = potWidth;
  7107. texture._height = potHeight;
  7108. texture.isReady = true;
  7109. processFunction(potWidth, potHeight);
  7110. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7113. if (!noMipmap && !isCompressed) {
  7114. gl.generateMipmap(gl.TEXTURE_2D);
  7115. }
  7116. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7117. engine.resetTextureCache();
  7118. scene._removePendingData(texture);
  7119. texture.onLoadedCallbacks.forEach(function (callback) {
  7120. callback();
  7121. });
  7122. texture.onLoadedCallbacks = [];
  7123. };
  7124. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7125. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7126. var img;
  7127. var onload = function () {
  7128. loadedImages[index] = img;
  7129. loadedImages._internalCount++;
  7130. scene._removePendingData(img);
  7131. if (loadedImages._internalCount === 6) {
  7132. onfinish(loadedImages);
  7133. }
  7134. };
  7135. var onerror = function () {
  7136. scene._removePendingData(img);
  7137. if (onErrorCallBack) {
  7138. onErrorCallBack();
  7139. }
  7140. };
  7141. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7142. scene._addPendingData(img);
  7143. };
  7144. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7145. if (onError === void 0) { onError = null; }
  7146. var loadedImages = [];
  7147. loadedImages._internalCount = 0;
  7148. for (var index = 0; index < 6; index++) {
  7149. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7150. }
  7151. };
  7152. var InstancingAttributeInfo = (function () {
  7153. function InstancingAttributeInfo() {
  7154. }
  7155. return InstancingAttributeInfo;
  7156. }());
  7157. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7158. var EngineCapabilities = (function () {
  7159. function EngineCapabilities() {
  7160. }
  7161. return EngineCapabilities;
  7162. }());
  7163. BABYLON.EngineCapabilities = EngineCapabilities;
  7164. /**
  7165. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7166. */
  7167. var Engine = (function () {
  7168. /**
  7169. * @constructor
  7170. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7171. * @param {boolean} [antialias] - enable antialias
  7172. * @param options - further options to be sent to the getContext function
  7173. */
  7174. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7175. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7176. var _this = this;
  7177. // Public members
  7178. this.isFullscreen = false;
  7179. this.isPointerLock = false;
  7180. this.cullBackFaces = true;
  7181. this.renderEvenInBackground = true;
  7182. this.preventCacheWipeBetweenFrames = false;
  7183. // To enable/disable IDB support and avoid XHR on .manifest
  7184. this.enableOfflineSupport = BABYLON.Database;
  7185. this.scenes = new Array();
  7186. // Observables
  7187. /**
  7188. * Observable event triggered each time the rendering canvas is resized
  7189. */
  7190. this.onResizeObservable = new BABYLON.Observable();
  7191. /**
  7192. * Observable event triggered each time the canvas lost focus
  7193. */
  7194. this.onCanvasBlurObservable = new BABYLON.Observable();
  7195. this._windowIsBackground = false;
  7196. this._webGLVersion = 1.0;
  7197. this._badOS = false;
  7198. this._drawCalls = new BABYLON.PerfCounter();
  7199. this._renderingQueueLaunched = false;
  7200. this._activeRenderLoops = [];
  7201. // FPS
  7202. this.fpsRange = 60;
  7203. this.previousFramesDuration = [];
  7204. this.fps = 60;
  7205. this.deltaTime = 0;
  7206. // States
  7207. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7208. this._stencilState = new BABYLON.Internals._StencilState();
  7209. this._alphaState = new BABYLON.Internals._AlphaState();
  7210. this._alphaMode = Engine.ALPHA_DISABLE;
  7211. // Cache
  7212. this._loadedTexturesCache = new Array();
  7213. this._maxTextureChannels = 16;
  7214. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7215. this._compiledEffects = {};
  7216. this._vertexAttribArraysEnabled = [];
  7217. this._uintIndicesCurrentlySet = false;
  7218. this._currentBoundBuffer = new Array();
  7219. this._currentBufferPointers = [];
  7220. this._currentInstanceLocations = new Array();
  7221. this._currentInstanceBuffers = new Array();
  7222. this._vaoRecordInProgress = false;
  7223. this._mustWipeVertexAttributes = false;
  7224. // Hardware supported Compressed Textures
  7225. this._texturesSupported = new Array();
  7226. this._onVRFullScreenTriggered = function () {
  7227. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7228. //get the old size before we change
  7229. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7230. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7231. //get the width and height, change the render size
  7232. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7233. var width, height;
  7234. _this.setHardwareScalingLevel(1);
  7235. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7236. }
  7237. else {
  7238. //When the specs are implemented, need to uncomment this.
  7239. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7240. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7241. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7242. _this._vrDisplayEnabled = undefined;
  7243. }
  7244. };
  7245. this._renderingCanvas = canvas;
  7246. Engine.Instances.push(this);
  7247. options = options || {};
  7248. if (antialias != null) {
  7249. options.antialias = antialias;
  7250. }
  7251. if (options.preserveDrawingBuffer === undefined) {
  7252. options.preserveDrawingBuffer = false;
  7253. }
  7254. if (options.audioEngine === undefined) {
  7255. options.audioEngine = true;
  7256. }
  7257. if (options.stencil === undefined) {
  7258. options.stencil = true;
  7259. }
  7260. // GL
  7261. if (!options.disableWebGL2Support) {
  7262. try {
  7263. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7264. if (this._gl) {
  7265. this._webGLVersion = 2.0;
  7266. }
  7267. }
  7268. catch (e) {
  7269. // Do nothing
  7270. }
  7271. }
  7272. if (!this._gl) {
  7273. if (!canvas) {
  7274. throw new Error("The provided canvas is null or undefined.");
  7275. }
  7276. try {
  7277. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7278. }
  7279. catch (e) {
  7280. throw new Error("WebGL not supported");
  7281. }
  7282. }
  7283. if (!this._gl) {
  7284. throw new Error("WebGL not supported");
  7285. }
  7286. this._onBlur = function () {
  7287. _this._windowIsBackground = true;
  7288. };
  7289. this._onFocus = function () {
  7290. _this._windowIsBackground = false;
  7291. };
  7292. this._onCanvasBlur = function () {
  7293. _this.onCanvasBlurObservable.notifyObservers(_this);
  7294. };
  7295. window.addEventListener("blur", this._onBlur);
  7296. window.addEventListener("focus", this._onFocus);
  7297. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7298. // Viewport
  7299. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7300. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7301. this.resize();
  7302. // Caps
  7303. this._isStencilEnable = options.stencil;
  7304. this._caps = new EngineCapabilities();
  7305. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7306. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7307. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7308. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7309. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7310. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7311. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7312. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7313. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7314. // Infos
  7315. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7316. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7317. if (rendererInfo != null) {
  7318. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7319. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7320. }
  7321. if (!this._glVendor) {
  7322. this._glVendor = "Unknown vendor";
  7323. }
  7324. if (!this._glRenderer) {
  7325. this._glRenderer = "Unknown renderer";
  7326. }
  7327. // Constants
  7328. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  7329. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  7330. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  7331. // Extensions
  7332. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7333. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7334. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7335. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7336. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7337. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7338. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7339. 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');
  7340. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7341. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7342. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7343. this._caps.highPrecisionShaderSupported = true;
  7344. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7345. // Checks if some of the format renders first to allow the use of webgl inspector.
  7346. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7347. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7348. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7349. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7350. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7351. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7352. if (this._webGLVersion > 1) {
  7353. this._gl.HALF_FLOAT_OES = 0x140B;
  7354. }
  7355. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7356. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7357. // Vertex array object
  7358. if (this._webGLVersion > 1) {
  7359. this._caps.vertexArrayObject = true;
  7360. }
  7361. else {
  7362. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7363. if (vertexArrayObjectExtension != null) {
  7364. this._caps.vertexArrayObject = true;
  7365. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7366. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7367. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7368. }
  7369. else {
  7370. this._caps.vertexArrayObject = false;
  7371. }
  7372. }
  7373. // Instances count
  7374. if (this._webGLVersion > 1) {
  7375. this._caps.instancedArrays = true;
  7376. }
  7377. else {
  7378. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7379. if (instanceExtension != null) {
  7380. this._caps.instancedArrays = true;
  7381. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7382. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7383. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7384. }
  7385. else {
  7386. this._caps.instancedArrays = false;
  7387. }
  7388. }
  7389. // Intelligently add supported compressed formats in order to check for.
  7390. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7391. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7392. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7393. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7394. if (this._caps.astc)
  7395. this.texturesSupported.push('-astc.ktx');
  7396. if (this._caps.s3tc)
  7397. this.texturesSupported.push('-dxt.ktx');
  7398. if (this._caps.pvrtc)
  7399. this.texturesSupported.push('-pvrtc.ktx');
  7400. if (this._caps.etc2)
  7401. this.texturesSupported.push('-etc2.ktx');
  7402. if (this._caps.etc1)
  7403. this.texturesSupported.push('-etc1.ktx');
  7404. if (this._gl.getShaderPrecisionFormat) {
  7405. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7406. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7407. }
  7408. // Depth buffer
  7409. this.setDepthBuffer(true);
  7410. this.setDepthFunctionToLessOrEqual();
  7411. this.setDepthWrite(true);
  7412. // Fullscreen
  7413. this._onFullscreenChange = function () {
  7414. if (document.fullscreen !== undefined) {
  7415. _this.isFullscreen = document.fullscreen;
  7416. }
  7417. else if (document.mozFullScreen !== undefined) {
  7418. _this.isFullscreen = document.mozFullScreen;
  7419. }
  7420. else if (document.webkitIsFullScreen !== undefined) {
  7421. _this.isFullscreen = document.webkitIsFullScreen;
  7422. }
  7423. else if (document.msIsFullScreen !== undefined) {
  7424. _this.isFullscreen = document.msIsFullScreen;
  7425. }
  7426. // Pointer lock
  7427. if (_this.isFullscreen && _this._pointerLockRequested) {
  7428. canvas.requestPointerLock = canvas.requestPointerLock ||
  7429. canvas.msRequestPointerLock ||
  7430. canvas.mozRequestPointerLock ||
  7431. canvas.webkitRequestPointerLock;
  7432. if (canvas.requestPointerLock) {
  7433. canvas.requestPointerLock();
  7434. }
  7435. }
  7436. };
  7437. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7438. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7439. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7440. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7441. // Pointer lock
  7442. this._onPointerLockChange = function () {
  7443. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7444. document.webkitPointerLockElement === canvas ||
  7445. document.msPointerLockElement === canvas ||
  7446. document.pointerLockElement === canvas);
  7447. };
  7448. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7449. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7450. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7451. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7452. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7453. Engine.audioEngine = new BABYLON.AudioEngine();
  7454. }
  7455. //Load WebVR Devices
  7456. if (options.autoEnableWebVR) {
  7457. this.initWebVR();
  7458. }
  7459. //Detect if we are running on a faulty buggy OS.
  7460. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7461. //ua sniffing is the tool of the devil.
  7462. this._badOS = regexp.test(navigator.userAgent);
  7463. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7464. }
  7465. Object.defineProperty(Engine, "LastCreatedEngine", {
  7466. get: function () {
  7467. if (Engine.Instances.length === 0) {
  7468. return null;
  7469. }
  7470. return Engine.Instances[Engine.Instances.length - 1];
  7471. },
  7472. enumerable: true,
  7473. configurable: true
  7474. });
  7475. Object.defineProperty(Engine, "LastCreatedScene", {
  7476. get: function () {
  7477. var lastCreatedEngine = Engine.LastCreatedEngine;
  7478. if (!lastCreatedEngine) {
  7479. return null;
  7480. }
  7481. if (lastCreatedEngine.scenes.length === 0) {
  7482. return null;
  7483. }
  7484. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7485. },
  7486. enumerable: true,
  7487. configurable: true
  7488. });
  7489. /**
  7490. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7491. */
  7492. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7493. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7494. var engine = Engine.Instances[engineIndex];
  7495. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7496. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7497. }
  7498. }
  7499. };
  7500. Object.defineProperty(Engine, "NEVER", {
  7501. get: function () {
  7502. return Engine._NEVER;
  7503. },
  7504. enumerable: true,
  7505. configurable: true
  7506. });
  7507. Object.defineProperty(Engine, "ALWAYS", {
  7508. get: function () {
  7509. return Engine._ALWAYS;
  7510. },
  7511. enumerable: true,
  7512. configurable: true
  7513. });
  7514. Object.defineProperty(Engine, "LESS", {
  7515. get: function () {
  7516. return Engine._LESS;
  7517. },
  7518. enumerable: true,
  7519. configurable: true
  7520. });
  7521. Object.defineProperty(Engine, "EQUAL", {
  7522. get: function () {
  7523. return Engine._EQUAL;
  7524. },
  7525. enumerable: true,
  7526. configurable: true
  7527. });
  7528. Object.defineProperty(Engine, "LEQUAL", {
  7529. get: function () {
  7530. return Engine._LEQUAL;
  7531. },
  7532. enumerable: true,
  7533. configurable: true
  7534. });
  7535. Object.defineProperty(Engine, "GREATER", {
  7536. get: function () {
  7537. return Engine._GREATER;
  7538. },
  7539. enumerable: true,
  7540. configurable: true
  7541. });
  7542. Object.defineProperty(Engine, "GEQUAL", {
  7543. get: function () {
  7544. return Engine._GEQUAL;
  7545. },
  7546. enumerable: true,
  7547. configurable: true
  7548. });
  7549. Object.defineProperty(Engine, "NOTEQUAL", {
  7550. get: function () {
  7551. return Engine._NOTEQUAL;
  7552. },
  7553. enumerable: true,
  7554. configurable: true
  7555. });
  7556. Object.defineProperty(Engine, "KEEP", {
  7557. get: function () {
  7558. return Engine._KEEP;
  7559. },
  7560. enumerable: true,
  7561. configurable: true
  7562. });
  7563. Object.defineProperty(Engine, "REPLACE", {
  7564. get: function () {
  7565. return Engine._REPLACE;
  7566. },
  7567. enumerable: true,
  7568. configurable: true
  7569. });
  7570. Object.defineProperty(Engine, "INCR", {
  7571. get: function () {
  7572. return Engine._INCR;
  7573. },
  7574. enumerable: true,
  7575. configurable: true
  7576. });
  7577. Object.defineProperty(Engine, "DECR", {
  7578. get: function () {
  7579. return Engine._DECR;
  7580. },
  7581. enumerable: true,
  7582. configurable: true
  7583. });
  7584. Object.defineProperty(Engine, "INVERT", {
  7585. get: function () {
  7586. return Engine._INVERT;
  7587. },
  7588. enumerable: true,
  7589. configurable: true
  7590. });
  7591. Object.defineProperty(Engine, "INCR_WRAP", {
  7592. get: function () {
  7593. return Engine._INCR_WRAP;
  7594. },
  7595. enumerable: true,
  7596. configurable: true
  7597. });
  7598. Object.defineProperty(Engine, "DECR_WRAP", {
  7599. get: function () {
  7600. return Engine._DECR_WRAP;
  7601. },
  7602. enumerable: true,
  7603. configurable: true
  7604. });
  7605. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7606. get: function () {
  7607. return Engine._ALPHA_DISABLE;
  7608. },
  7609. enumerable: true,
  7610. configurable: true
  7611. });
  7612. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7613. get: function () {
  7614. return Engine._ALPHA_ONEONE;
  7615. },
  7616. enumerable: true,
  7617. configurable: true
  7618. });
  7619. Object.defineProperty(Engine, "ALPHA_ADD", {
  7620. get: function () {
  7621. return Engine._ALPHA_ADD;
  7622. },
  7623. enumerable: true,
  7624. configurable: true
  7625. });
  7626. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7627. get: function () {
  7628. return Engine._ALPHA_COMBINE;
  7629. },
  7630. enumerable: true,
  7631. configurable: true
  7632. });
  7633. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7634. get: function () {
  7635. return Engine._ALPHA_SUBTRACT;
  7636. },
  7637. enumerable: true,
  7638. configurable: true
  7639. });
  7640. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7641. get: function () {
  7642. return Engine._ALPHA_MULTIPLY;
  7643. },
  7644. enumerable: true,
  7645. configurable: true
  7646. });
  7647. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7648. get: function () {
  7649. return Engine._ALPHA_MAXIMIZED;
  7650. },
  7651. enumerable: true,
  7652. configurable: true
  7653. });
  7654. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7655. get: function () {
  7656. return Engine._ALPHA_PREMULTIPLIED;
  7657. },
  7658. enumerable: true,
  7659. configurable: true
  7660. });
  7661. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7662. get: function () {
  7663. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7664. },
  7665. enumerable: true,
  7666. configurable: true
  7667. });
  7668. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7669. get: function () {
  7670. return Engine._ALPHA_INTERPOLATE;
  7671. },
  7672. enumerable: true,
  7673. configurable: true
  7674. });
  7675. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7676. get: function () {
  7677. return Engine._ALPHA_SCREENMODE;
  7678. },
  7679. enumerable: true,
  7680. configurable: true
  7681. });
  7682. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7683. get: function () {
  7684. return Engine._DELAYLOADSTATE_NONE;
  7685. },
  7686. enumerable: true,
  7687. configurable: true
  7688. });
  7689. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7690. get: function () {
  7691. return Engine._DELAYLOADSTATE_LOADED;
  7692. },
  7693. enumerable: true,
  7694. configurable: true
  7695. });
  7696. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7697. get: function () {
  7698. return Engine._DELAYLOADSTATE_LOADING;
  7699. },
  7700. enumerable: true,
  7701. configurable: true
  7702. });
  7703. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7704. get: function () {
  7705. return Engine._DELAYLOADSTATE_NOTLOADED;
  7706. },
  7707. enumerable: true,
  7708. configurable: true
  7709. });
  7710. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7711. get: function () {
  7712. return Engine._TEXTUREFORMAT_ALPHA;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7718. get: function () {
  7719. return Engine._TEXTUREFORMAT_LUMINANCE;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7725. get: function () {
  7726. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7727. },
  7728. enumerable: true,
  7729. configurable: true
  7730. });
  7731. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7732. get: function () {
  7733. return Engine._TEXTUREFORMAT_RGB;
  7734. },
  7735. enumerable: true,
  7736. configurable: true
  7737. });
  7738. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7739. get: function () {
  7740. return Engine._TEXTUREFORMAT_RGBA;
  7741. },
  7742. enumerable: true,
  7743. configurable: true
  7744. });
  7745. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7746. get: function () {
  7747. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7748. },
  7749. enumerable: true,
  7750. configurable: true
  7751. });
  7752. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7753. get: function () {
  7754. return Engine._TEXTURETYPE_FLOAT;
  7755. },
  7756. enumerable: true,
  7757. configurable: true
  7758. });
  7759. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7760. get: function () {
  7761. return Engine._TEXTURETYPE_HALF_FLOAT;
  7762. },
  7763. enumerable: true,
  7764. configurable: true
  7765. });
  7766. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7767. get: function () {
  7768. return Engine._SCALEMODE_FLOOR;
  7769. },
  7770. enumerable: true,
  7771. configurable: true
  7772. });
  7773. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7774. get: function () {
  7775. return Engine._SCALEMODE_NEAREST;
  7776. },
  7777. enumerable: true,
  7778. configurable: true
  7779. });
  7780. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7781. get: function () {
  7782. return Engine._SCALEMODE_CEILING;
  7783. },
  7784. enumerable: true,
  7785. configurable: true
  7786. });
  7787. Object.defineProperty(Engine, "Version", {
  7788. get: function () {
  7789. return "3.0-rc";
  7790. },
  7791. enumerable: true,
  7792. configurable: true
  7793. });
  7794. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7795. get: function () {
  7796. return this._texturesSupported;
  7797. },
  7798. enumerable: true,
  7799. configurable: true
  7800. });
  7801. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7802. get: function () {
  7803. return this._textureFormatInUse;
  7804. },
  7805. enumerable: true,
  7806. configurable: true
  7807. });
  7808. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7809. // Empty texture
  7810. get: function () {
  7811. if (!this._emptyTexture) {
  7812. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7813. }
  7814. return this._emptyTexture;
  7815. },
  7816. enumerable: true,
  7817. configurable: true
  7818. });
  7819. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7820. get: function () {
  7821. if (!this._emptyCubeTexture) {
  7822. var faceData = new Uint8Array(4);
  7823. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7824. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7825. }
  7826. return this._emptyCubeTexture;
  7827. },
  7828. enumerable: true,
  7829. configurable: true
  7830. });
  7831. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7832. get: function () {
  7833. return this._webGLVersion;
  7834. },
  7835. enumerable: true,
  7836. configurable: true
  7837. });
  7838. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7839. /**
  7840. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7841. */
  7842. get: function () {
  7843. return this._isStencilEnable;
  7844. },
  7845. enumerable: true,
  7846. configurable: true
  7847. });
  7848. Engine.prototype._prepareWorkingCanvas = function () {
  7849. if (this._workingCanvas) {
  7850. return;
  7851. }
  7852. this._workingCanvas = document.createElement("canvas");
  7853. this._workingContext = this._workingCanvas.getContext("2d");
  7854. };
  7855. Engine.prototype.resetTextureCache = function () {
  7856. for (var index = 0; index < this._maxTextureChannels; index++) {
  7857. this._activeTexturesCache[index] = null;
  7858. }
  7859. };
  7860. Engine.prototype.getGlInfo = function () {
  7861. return {
  7862. vendor: this._glVendor,
  7863. renderer: this._glRenderer,
  7864. version: this._glVersion
  7865. };
  7866. };
  7867. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7868. if (useScreen === void 0) { useScreen = false; }
  7869. var viewport = camera.viewport;
  7870. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7871. };
  7872. Engine.prototype.getRenderWidth = function (useScreen) {
  7873. if (useScreen === void 0) { useScreen = false; }
  7874. if (!useScreen && this._currentRenderTarget) {
  7875. return this._currentRenderTarget._width;
  7876. }
  7877. return this._renderingCanvas.width;
  7878. };
  7879. Engine.prototype.getRenderHeight = function (useScreen) {
  7880. if (useScreen === void 0) { useScreen = false; }
  7881. if (!useScreen && this._currentRenderTarget) {
  7882. return this._currentRenderTarget._height;
  7883. }
  7884. return this._renderingCanvas.height;
  7885. };
  7886. Engine.prototype.getRenderingCanvas = function () {
  7887. return this._renderingCanvas;
  7888. };
  7889. Engine.prototype.getRenderingCanvasClientRect = function () {
  7890. return this._renderingCanvas.getBoundingClientRect();
  7891. };
  7892. Engine.prototype.setHardwareScalingLevel = function (level) {
  7893. this._hardwareScalingLevel = level;
  7894. this.resize();
  7895. };
  7896. Engine.prototype.getHardwareScalingLevel = function () {
  7897. return this._hardwareScalingLevel;
  7898. };
  7899. Engine.prototype.getLoadedTexturesCache = function () {
  7900. return this._loadedTexturesCache;
  7901. };
  7902. Engine.prototype.getCaps = function () {
  7903. return this._caps;
  7904. };
  7905. Object.defineProperty(Engine.prototype, "drawCalls", {
  7906. get: function () {
  7907. return this._drawCalls.current;
  7908. },
  7909. enumerable: true,
  7910. configurable: true
  7911. });
  7912. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7913. get: function () {
  7914. return this._drawCalls;
  7915. },
  7916. enumerable: true,
  7917. configurable: true
  7918. });
  7919. Engine.prototype.getDepthFunction = function () {
  7920. return this._depthCullingState.depthFunc;
  7921. };
  7922. Engine.prototype.setDepthFunction = function (depthFunc) {
  7923. this._depthCullingState.depthFunc = depthFunc;
  7924. };
  7925. Engine.prototype.setDepthFunctionToGreater = function () {
  7926. this._depthCullingState.depthFunc = this._gl.GREATER;
  7927. };
  7928. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7929. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7930. };
  7931. Engine.prototype.setDepthFunctionToLess = function () {
  7932. this._depthCullingState.depthFunc = this._gl.LESS;
  7933. };
  7934. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7935. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7936. };
  7937. Engine.prototype.getStencilBuffer = function () {
  7938. return this._stencilState.stencilTest;
  7939. };
  7940. Engine.prototype.setStencilBuffer = function (enable) {
  7941. this._stencilState.stencilTest = enable;
  7942. };
  7943. Engine.prototype.getStencilMask = function () {
  7944. return this._stencilState.stencilMask;
  7945. };
  7946. Engine.prototype.setStencilMask = function (mask) {
  7947. this._stencilState.stencilMask = mask;
  7948. };
  7949. Engine.prototype.getStencilFunction = function () {
  7950. return this._stencilState.stencilFunc;
  7951. };
  7952. Engine.prototype.getStencilFunctionReference = function () {
  7953. return this._stencilState.stencilFuncRef;
  7954. };
  7955. Engine.prototype.getStencilFunctionMask = function () {
  7956. return this._stencilState.stencilFuncMask;
  7957. };
  7958. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7959. this._stencilState.stencilFunc = stencilFunc;
  7960. };
  7961. Engine.prototype.setStencilFunctionReference = function (reference) {
  7962. this._stencilState.stencilFuncRef = reference;
  7963. };
  7964. Engine.prototype.setStencilFunctionMask = function (mask) {
  7965. this._stencilState.stencilFuncMask = mask;
  7966. };
  7967. Engine.prototype.getStencilOperationFail = function () {
  7968. return this._stencilState.stencilOpStencilFail;
  7969. };
  7970. Engine.prototype.getStencilOperationDepthFail = function () {
  7971. return this._stencilState.stencilOpDepthFail;
  7972. };
  7973. Engine.prototype.getStencilOperationPass = function () {
  7974. return this._stencilState.stencilOpStencilDepthPass;
  7975. };
  7976. Engine.prototype.setStencilOperationFail = function (operation) {
  7977. this._stencilState.stencilOpStencilFail = operation;
  7978. };
  7979. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7980. this._stencilState.stencilOpDepthFail = operation;
  7981. };
  7982. Engine.prototype.setStencilOperationPass = function (operation) {
  7983. this._stencilState.stencilOpStencilDepthPass = operation;
  7984. };
  7985. Engine.prototype.setDitheringState = function (value) {
  7986. if (value) {
  7987. this._gl.enable(this._gl.DITHER);
  7988. }
  7989. else {
  7990. this._gl.disable(this._gl.DITHER);
  7991. }
  7992. };
  7993. /**
  7994. * stop executing a render loop function and remove it from the execution array
  7995. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7996. */
  7997. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7998. if (!renderFunction) {
  7999. this._activeRenderLoops = [];
  8000. return;
  8001. }
  8002. var index = this._activeRenderLoops.indexOf(renderFunction);
  8003. if (index >= 0) {
  8004. this._activeRenderLoops.splice(index, 1);
  8005. }
  8006. };
  8007. Engine.prototype._renderLoop = function () {
  8008. var shouldRender = true;
  8009. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8010. shouldRender = false;
  8011. }
  8012. if (shouldRender) {
  8013. // Start new frame
  8014. this.beginFrame();
  8015. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8016. var renderFunction = this._activeRenderLoops[index];
  8017. renderFunction();
  8018. }
  8019. // Present
  8020. this.endFrame();
  8021. }
  8022. if (this._activeRenderLoops.length > 0) {
  8023. // Register new frame
  8024. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8025. }
  8026. else {
  8027. this._renderingQueueLaunched = false;
  8028. }
  8029. };
  8030. /**
  8031. * Register and execute a render loop. The engine can have more than one render function.
  8032. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8033. * @example
  8034. * engine.runRenderLoop(function () {
  8035. * scene.render()
  8036. * })
  8037. */
  8038. Engine.prototype.runRenderLoop = function (renderFunction) {
  8039. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8040. return;
  8041. }
  8042. this._activeRenderLoops.push(renderFunction);
  8043. if (!this._renderingQueueLaunched) {
  8044. this._renderingQueueLaunched = true;
  8045. this._bindedRenderFunction = this._renderLoop.bind(this);
  8046. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8047. }
  8048. };
  8049. /**
  8050. * Toggle full screen mode.
  8051. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8052. * @param {any} options - an options object to be sent to the requestFullscreen function
  8053. */
  8054. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8055. if (this.isFullscreen) {
  8056. BABYLON.Tools.ExitFullscreen();
  8057. }
  8058. else {
  8059. this._pointerLockRequested = requestPointerLock;
  8060. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8061. }
  8062. };
  8063. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8064. if (stencil === void 0) { stencil = false; }
  8065. this.applyStates();
  8066. var mode = 0;
  8067. if (backBuffer && color) {
  8068. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8069. mode |= this._gl.COLOR_BUFFER_BIT;
  8070. }
  8071. if (depth) {
  8072. this._gl.clearDepth(1.0);
  8073. mode |= this._gl.DEPTH_BUFFER_BIT;
  8074. }
  8075. if (stencil) {
  8076. this._gl.clearStencil(0);
  8077. mode |= this._gl.STENCIL_BUFFER_BIT;
  8078. }
  8079. this._gl.clear(mode);
  8080. };
  8081. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8082. var gl = this._gl;
  8083. // Save state
  8084. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8085. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8086. // Change state
  8087. gl.enable(gl.SCISSOR_TEST);
  8088. gl.scissor(x, y, width, height);
  8089. // Clear
  8090. this.clear(clearColor, true, true, true);
  8091. // Restore state
  8092. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8093. if (curScissor === true) {
  8094. gl.enable(gl.SCISSOR_TEST);
  8095. }
  8096. else {
  8097. gl.disable(gl.SCISSOR_TEST);
  8098. }
  8099. };
  8100. /**
  8101. * Set the WebGL's viewport
  8102. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8103. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8104. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8105. */
  8106. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8107. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8108. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8109. var x = viewport.x || 0;
  8110. var y = viewport.y || 0;
  8111. this._cachedViewport = viewport;
  8112. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8113. };
  8114. /**
  8115. * Directly set the WebGL Viewport
  8116. * The x, y, width & height are directly passed to the WebGL call
  8117. * @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.
  8118. */
  8119. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8120. var currentViewport = this._cachedViewport;
  8121. this._cachedViewport = null;
  8122. this._gl.viewport(x, y, width, height);
  8123. return currentViewport;
  8124. };
  8125. Engine.prototype.beginFrame = function () {
  8126. this._measureFps();
  8127. };
  8128. Engine.prototype.endFrame = function () {
  8129. //force a flush in case we are using a bad OS.
  8130. if (this._badOS) {
  8131. this.flushFramebuffer();
  8132. }
  8133. //submit frame to the vr device, if enabled
  8134. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8135. this._vrDisplayEnabled.submitFrame();
  8136. }
  8137. };
  8138. /**
  8139. * resize the view according to the canvas' size.
  8140. * @example
  8141. * window.addEventListener("resize", function () {
  8142. * engine.resize();
  8143. * });
  8144. */
  8145. Engine.prototype.resize = function () {
  8146. // We're not resizing the size of the canvas while in VR mode & presenting
  8147. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8148. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8149. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8150. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8151. }
  8152. };
  8153. /**
  8154. * force a specific size of the canvas
  8155. * @param {number} width - the new canvas' width
  8156. * @param {number} height - the new canvas' height
  8157. */
  8158. Engine.prototype.setSize = function (width, height) {
  8159. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8160. return;
  8161. }
  8162. this._renderingCanvas.width = width;
  8163. this._renderingCanvas.height = height;
  8164. for (var index = 0; index < this.scenes.length; index++) {
  8165. var scene = this.scenes[index];
  8166. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8167. var cam = scene.cameras[camIndex];
  8168. cam._currentRenderId = 0;
  8169. }
  8170. }
  8171. if (this.onResizeObservable.hasObservers) {
  8172. this.onResizeObservable.notifyObservers(this);
  8173. }
  8174. };
  8175. //WebVR functions
  8176. Engine.prototype.isVRDevicePresent = function (callback) {
  8177. this.getVRDevice(null, function (device) {
  8178. callback(device !== null);
  8179. });
  8180. };
  8181. Engine.prototype.getVRDevice = function (name, callback) {
  8182. if (!this.vrDisplaysPromise) {
  8183. callback(null);
  8184. return;
  8185. }
  8186. this.vrDisplaysPromise.then(function (devices) {
  8187. if (devices.length > 0) {
  8188. if (name) {
  8189. var found = devices.some(function (device) {
  8190. if (device.displayName === name) {
  8191. callback(device);
  8192. return true;
  8193. }
  8194. else {
  8195. return false;
  8196. }
  8197. });
  8198. if (!found) {
  8199. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8200. callback(devices[0]);
  8201. }
  8202. }
  8203. else {
  8204. //choose the first one
  8205. callback(devices[0]);
  8206. }
  8207. }
  8208. else {
  8209. BABYLON.Tools.Error("No WebVR devices found!");
  8210. callback(null);
  8211. }
  8212. });
  8213. };
  8214. Engine.prototype.initWebVR = function () {
  8215. if (!this.vrDisplaysPromise) {
  8216. this._getVRDisplays();
  8217. }
  8218. };
  8219. Engine.prototype.enableVR = function (vrDevice) {
  8220. this._vrDisplayEnabled = vrDevice;
  8221. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8222. };
  8223. Engine.prototype.disableVR = function () {
  8224. if (this._vrDisplayEnabled) {
  8225. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8226. }
  8227. };
  8228. Engine.prototype._getVRDisplays = function () {
  8229. var _this = this;
  8230. var getWebVRDevices = function (devices) {
  8231. var size = devices.length;
  8232. var i = 0;
  8233. _this._vrDisplays = devices.filter(function (device) {
  8234. return devices[i] instanceof VRDisplay;
  8235. });
  8236. return _this._vrDisplays;
  8237. };
  8238. //using a key due to typescript
  8239. if (navigator.getVRDisplays) {
  8240. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8241. }
  8242. };
  8243. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8244. this._currentRenderTarget = texture;
  8245. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8246. var gl = this._gl;
  8247. if (texture.isCube) {
  8248. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8249. }
  8250. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8251. this.wipeCaches();
  8252. };
  8253. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8254. if (this._currentFramebuffer !== framebuffer) {
  8255. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8256. this._currentFramebuffer = framebuffer;
  8257. }
  8258. };
  8259. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8260. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8261. this._currentRenderTarget = null;
  8262. // If MSAA, we need to bitblt back to main texture
  8263. var gl = this._gl;
  8264. if (texture._MSAAFramebuffer) {
  8265. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8266. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8267. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8268. }
  8269. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8270. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8271. gl.generateMipmap(gl.TEXTURE_2D);
  8272. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8273. }
  8274. if (onBeforeUnbind) {
  8275. if (texture._MSAAFramebuffer) {
  8276. // Bind the correct framebuffer
  8277. this.bindUnboundFramebuffer(texture._framebuffer);
  8278. }
  8279. onBeforeUnbind();
  8280. }
  8281. this.bindUnboundFramebuffer(null);
  8282. };
  8283. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8284. if (texture.generateMipMaps) {
  8285. var gl = this._gl;
  8286. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8287. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8288. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8289. }
  8290. };
  8291. Engine.prototype.flushFramebuffer = function () {
  8292. this._gl.flush();
  8293. };
  8294. Engine.prototype.restoreDefaultFramebuffer = function () {
  8295. this._currentRenderTarget = null;
  8296. this.bindUnboundFramebuffer(null);
  8297. if (this._cachedViewport) {
  8298. this.setViewport(this._cachedViewport);
  8299. }
  8300. this.wipeCaches();
  8301. };
  8302. // UBOs
  8303. Engine.prototype.createUniformBuffer = function (elements) {
  8304. var ubo = this._gl.createBuffer();
  8305. this.bindUniformBuffer(ubo);
  8306. if (elements instanceof Float32Array) {
  8307. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8308. }
  8309. else {
  8310. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8311. }
  8312. this.bindUniformBuffer(null);
  8313. ubo.references = 1;
  8314. return ubo;
  8315. };
  8316. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8317. var ubo = this._gl.createBuffer();
  8318. this.bindUniformBuffer(ubo);
  8319. if (elements instanceof Float32Array) {
  8320. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8321. }
  8322. else {
  8323. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8324. }
  8325. this.bindUniformBuffer(null);
  8326. ubo.references = 1;
  8327. return ubo;
  8328. };
  8329. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8330. this.bindUniformBuffer(uniformBuffer);
  8331. if (offset === undefined) {
  8332. offset = 0;
  8333. }
  8334. if (count === undefined) {
  8335. if (elements instanceof Float32Array) {
  8336. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8337. }
  8338. else {
  8339. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8340. }
  8341. }
  8342. else {
  8343. if (elements instanceof Float32Array) {
  8344. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8345. }
  8346. else {
  8347. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8348. }
  8349. }
  8350. this.bindUniformBuffer(null);
  8351. };
  8352. // VBOs
  8353. Engine.prototype._resetVertexBufferBinding = function () {
  8354. this.bindArrayBuffer(null);
  8355. this._cachedVertexBuffers = null;
  8356. };
  8357. Engine.prototype.createVertexBuffer = function (vertices) {
  8358. var vbo = this._gl.createBuffer();
  8359. this.bindArrayBuffer(vbo);
  8360. if (vertices instanceof Float32Array) {
  8361. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8362. }
  8363. else {
  8364. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8365. }
  8366. this._resetVertexBufferBinding();
  8367. vbo.references = 1;
  8368. return vbo;
  8369. };
  8370. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8371. var vbo = this._gl.createBuffer();
  8372. this.bindArrayBuffer(vbo);
  8373. if (vertices instanceof Float32Array) {
  8374. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8375. }
  8376. else {
  8377. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8378. }
  8379. this._resetVertexBufferBinding();
  8380. vbo.references = 1;
  8381. return vbo;
  8382. };
  8383. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8384. this.bindArrayBuffer(vertexBuffer);
  8385. if (offset === undefined) {
  8386. offset = 0;
  8387. }
  8388. if (count === undefined) {
  8389. if (vertices instanceof Float32Array) {
  8390. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8391. }
  8392. else {
  8393. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8394. }
  8395. }
  8396. else {
  8397. if (vertices instanceof Float32Array) {
  8398. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8399. }
  8400. else {
  8401. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8402. }
  8403. }
  8404. this._resetVertexBufferBinding();
  8405. };
  8406. Engine.prototype._resetIndexBufferBinding = function () {
  8407. this.bindIndexBuffer(null);
  8408. this._cachedIndexBuffer = null;
  8409. };
  8410. Engine.prototype.createIndexBuffer = function (indices) {
  8411. var vbo = this._gl.createBuffer();
  8412. this.bindIndexBuffer(vbo);
  8413. // Check for 32 bits indices
  8414. var arrayBuffer;
  8415. var need32Bits = false;
  8416. if (indices instanceof Uint16Array) {
  8417. arrayBuffer = indices;
  8418. }
  8419. else {
  8420. //check 32 bit support
  8421. if (this._caps.uintIndices) {
  8422. if (indices instanceof Uint32Array) {
  8423. arrayBuffer = indices;
  8424. need32Bits = true;
  8425. }
  8426. else {
  8427. //number[] or Int32Array, check if 32 bit is necessary
  8428. for (var index = 0; index < indices.length; index++) {
  8429. if (indices[index] > 65535) {
  8430. need32Bits = true;
  8431. break;
  8432. }
  8433. }
  8434. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8435. }
  8436. }
  8437. else {
  8438. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8439. arrayBuffer = new Uint16Array(indices);
  8440. }
  8441. }
  8442. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8443. this._resetIndexBufferBinding();
  8444. vbo.references = 1;
  8445. vbo.is32Bits = need32Bits;
  8446. return vbo;
  8447. };
  8448. Engine.prototype.bindArrayBuffer = function (buffer) {
  8449. if (!this._vaoRecordInProgress) {
  8450. this._unBindVertexArrayObject();
  8451. }
  8452. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8453. };
  8454. Engine.prototype.bindUniformBuffer = function (buffer) {
  8455. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8456. };
  8457. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8458. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8459. };
  8460. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8461. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8462. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8463. };
  8464. ;
  8465. Engine.prototype.bindIndexBuffer = function (buffer) {
  8466. if (!this._vaoRecordInProgress) {
  8467. this._unBindVertexArrayObject();
  8468. }
  8469. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8470. };
  8471. Engine.prototype.bindBuffer = function (buffer, target) {
  8472. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8473. this._gl.bindBuffer(target, buffer);
  8474. this._currentBoundBuffer[target] = buffer;
  8475. }
  8476. };
  8477. Engine.prototype.updateArrayBuffer = function (data) {
  8478. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8479. };
  8480. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8481. var pointer = this._currentBufferPointers[indx];
  8482. var changed = false;
  8483. if (!pointer) {
  8484. changed = true;
  8485. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8486. }
  8487. else {
  8488. if (pointer.buffer !== buffer) {
  8489. pointer.buffer = buffer;
  8490. changed = true;
  8491. }
  8492. if (pointer.size !== size) {
  8493. pointer.size = size;
  8494. changed = true;
  8495. }
  8496. if (pointer.type !== type) {
  8497. pointer.type = type;
  8498. changed = true;
  8499. }
  8500. if (pointer.normalized !== normalized) {
  8501. pointer.normalized = normalized;
  8502. changed = true;
  8503. }
  8504. if (pointer.stride !== stride) {
  8505. pointer.stride = stride;
  8506. changed = true;
  8507. }
  8508. if (pointer.offset !== offset) {
  8509. pointer.offset = offset;
  8510. changed = true;
  8511. }
  8512. }
  8513. if (changed || this._vaoRecordInProgress) {
  8514. this.bindArrayBuffer(buffer);
  8515. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8516. }
  8517. };
  8518. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8519. if (indexBuffer == null) {
  8520. return;
  8521. }
  8522. if (this._cachedIndexBuffer !== indexBuffer) {
  8523. this._cachedIndexBuffer = indexBuffer;
  8524. this.bindIndexBuffer(indexBuffer);
  8525. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8526. }
  8527. };
  8528. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8529. var attributes = effect.getAttributesNames();
  8530. if (!this._vaoRecordInProgress) {
  8531. this._unBindVertexArrayObject();
  8532. }
  8533. this.unbindAllAttributes();
  8534. for (var index = 0; index < attributes.length; index++) {
  8535. var order = effect.getAttributeLocation(index);
  8536. if (order >= 0) {
  8537. var vertexBuffer = vertexBuffers[attributes[index]];
  8538. if (!vertexBuffer) {
  8539. continue;
  8540. }
  8541. this._gl.enableVertexAttribArray(order);
  8542. if (!this._vaoRecordInProgress) {
  8543. this._vertexAttribArraysEnabled[order] = true;
  8544. }
  8545. var buffer = vertexBuffer.getBuffer();
  8546. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8547. if (vertexBuffer.getIsInstanced()) {
  8548. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8549. if (!this._vaoRecordInProgress) {
  8550. this._currentInstanceLocations.push(order);
  8551. this._currentInstanceBuffers.push(buffer);
  8552. }
  8553. }
  8554. }
  8555. }
  8556. };
  8557. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8558. var vao = this._gl.createVertexArray();
  8559. this._vaoRecordInProgress = true;
  8560. this._gl.bindVertexArray(vao);
  8561. this._mustWipeVertexAttributes = true;
  8562. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8563. this.bindIndexBuffer(indexBuffer);
  8564. this._vaoRecordInProgress = false;
  8565. this._gl.bindVertexArray(null);
  8566. return vao;
  8567. };
  8568. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8569. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8570. this._cachedVertexArrayObject = vertexArrayObject;
  8571. this._gl.bindVertexArray(vertexArrayObject);
  8572. this._cachedVertexBuffers = null;
  8573. this._cachedIndexBuffer = null;
  8574. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8575. this._mustWipeVertexAttributes = true;
  8576. }
  8577. };
  8578. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8579. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8580. this._cachedVertexBuffers = vertexBuffer;
  8581. this._cachedEffectForVertexBuffers = effect;
  8582. var attributesCount = effect.getAttributesCount();
  8583. this._unBindVertexArrayObject();
  8584. this.unbindAllAttributes();
  8585. var offset = 0;
  8586. for (var index = 0; index < attributesCount; index++) {
  8587. if (index < vertexDeclaration.length) {
  8588. var order = effect.getAttributeLocation(index);
  8589. if (order >= 0) {
  8590. this._gl.enableVertexAttribArray(order);
  8591. this._vertexAttribArraysEnabled[order] = true;
  8592. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8593. }
  8594. offset += vertexDeclaration[index] * 4;
  8595. }
  8596. }
  8597. }
  8598. this._bindIndexBufferWithCache(indexBuffer);
  8599. };
  8600. Engine.prototype._unBindVertexArrayObject = function () {
  8601. if (!this._cachedVertexArrayObject) {
  8602. return;
  8603. }
  8604. this._cachedVertexArrayObject = null;
  8605. this._gl.bindVertexArray(null);
  8606. };
  8607. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8608. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8609. this._cachedVertexBuffers = vertexBuffers;
  8610. this._cachedEffectForVertexBuffers = effect;
  8611. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8612. }
  8613. this._bindIndexBufferWithCache(indexBuffer);
  8614. };
  8615. Engine.prototype.unbindInstanceAttributes = function () {
  8616. var boundBuffer;
  8617. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8618. var instancesBuffer = this._currentInstanceBuffers[i];
  8619. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8620. boundBuffer = instancesBuffer;
  8621. this.bindArrayBuffer(instancesBuffer);
  8622. }
  8623. var offsetLocation = this._currentInstanceLocations[i];
  8624. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8625. }
  8626. this._currentInstanceBuffers.length = 0;
  8627. this._currentInstanceLocations.length = 0;
  8628. };
  8629. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8630. this._gl.deleteVertexArray(vao);
  8631. };
  8632. Engine.prototype._releaseBuffer = function (buffer) {
  8633. buffer.references--;
  8634. if (buffer.references === 0) {
  8635. this._gl.deleteBuffer(buffer);
  8636. return true;
  8637. }
  8638. return false;
  8639. };
  8640. Engine.prototype.createInstancesBuffer = function (capacity) {
  8641. var buffer = this._gl.createBuffer();
  8642. buffer.capacity = capacity;
  8643. this.bindArrayBuffer(buffer);
  8644. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8645. return buffer;
  8646. };
  8647. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8648. this._gl.deleteBuffer(buffer);
  8649. };
  8650. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8651. this.bindArrayBuffer(instancesBuffer);
  8652. if (data) {
  8653. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8654. }
  8655. if (offsetLocations[0].index !== undefined) {
  8656. var stride = 0;
  8657. for (var i = 0; i < offsetLocations.length; i++) {
  8658. var ai = offsetLocations[i];
  8659. stride += ai.attributeSize * 4;
  8660. }
  8661. for (var i = 0; i < offsetLocations.length; i++) {
  8662. var ai = offsetLocations[i];
  8663. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8664. this._gl.enableVertexAttribArray(ai.index);
  8665. this._vertexAttribArraysEnabled[ai.index] = true;
  8666. }
  8667. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8668. this._gl.vertexAttribDivisor(ai.index, 1);
  8669. this._currentInstanceLocations.push(ai.index);
  8670. this._currentInstanceBuffers.push(instancesBuffer);
  8671. }
  8672. }
  8673. else {
  8674. for (var index = 0; index < 4; index++) {
  8675. var offsetLocation = offsetLocations[index];
  8676. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8677. this._gl.enableVertexAttribArray(offsetLocation);
  8678. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8679. }
  8680. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8681. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8682. this._currentInstanceLocations.push(offsetLocation);
  8683. this._currentInstanceBuffers.push(instancesBuffer);
  8684. }
  8685. }
  8686. };
  8687. Engine.prototype.applyStates = function () {
  8688. this._depthCullingState.apply(this._gl);
  8689. this._stencilState.apply(this._gl);
  8690. this._alphaState.apply(this._gl);
  8691. };
  8692. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8693. // Apply states
  8694. this.applyStates();
  8695. this._drawCalls.addCount(1, false);
  8696. // Render
  8697. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8698. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8699. if (instancesCount) {
  8700. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8701. return;
  8702. }
  8703. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8704. };
  8705. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8706. // Apply states
  8707. this.applyStates();
  8708. this._drawCalls.addCount(1, false);
  8709. if (instancesCount) {
  8710. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8711. return;
  8712. }
  8713. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8714. };
  8715. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8716. // Apply states
  8717. this.applyStates();
  8718. this._drawCalls.addCount(1, false);
  8719. if (instancesCount) {
  8720. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8721. return;
  8722. }
  8723. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8724. };
  8725. // Shaders
  8726. Engine.prototype._releaseEffect = function (effect) {
  8727. if (this._compiledEffects[effect._key]) {
  8728. delete this._compiledEffects[effect._key];
  8729. if (effect.getProgram()) {
  8730. this._gl.deleteProgram(effect.getProgram());
  8731. }
  8732. }
  8733. };
  8734. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8735. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8736. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8737. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8738. if (this._compiledEffects[name]) {
  8739. var compiledEffect = this._compiledEffects[name];
  8740. if (onCompiled && compiledEffect.isReady()) {
  8741. onCompiled(compiledEffect);
  8742. }
  8743. return compiledEffect;
  8744. }
  8745. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8746. effect._key = name;
  8747. this._compiledEffects[name] = effect;
  8748. return effect;
  8749. };
  8750. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8751. if (uniformsNames === void 0) { uniformsNames = []; }
  8752. if (samplers === void 0) { samplers = []; }
  8753. if (defines === void 0) { defines = ""; }
  8754. return this.createEffect({
  8755. vertex: "particles",
  8756. fragmentElement: fragmentName
  8757. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8758. };
  8759. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8760. context = context || this._gl;
  8761. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8762. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8763. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8764. var shaderProgram = context.createProgram();
  8765. context.attachShader(shaderProgram, vertexShader);
  8766. context.attachShader(shaderProgram, fragmentShader);
  8767. context.linkProgram(shaderProgram);
  8768. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8769. if (!linked) {
  8770. var error = context.getProgramInfoLog(shaderProgram);
  8771. if (error) {
  8772. throw new Error(error);
  8773. }
  8774. }
  8775. context.deleteShader(vertexShader);
  8776. context.deleteShader(fragmentShader);
  8777. return shaderProgram;
  8778. };
  8779. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8780. var results = [];
  8781. for (var index = 0; index < uniformsNames.length; index++) {
  8782. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8783. }
  8784. return results;
  8785. };
  8786. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8787. var results = [];
  8788. for (var index = 0; index < attributesNames.length; index++) {
  8789. try {
  8790. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8791. }
  8792. catch (e) {
  8793. results.push(-1);
  8794. }
  8795. }
  8796. return results;
  8797. };
  8798. Engine.prototype.enableEffect = function (effect) {
  8799. // Use program
  8800. this.setProgram(effect.getProgram());
  8801. this._currentEffect = effect;
  8802. if (effect.onBind) {
  8803. effect.onBind(effect);
  8804. }
  8805. effect.onBindObservable.notifyObservers(effect);
  8806. };
  8807. Engine.prototype.setIntArray = function (uniform, array) {
  8808. if (!uniform)
  8809. return;
  8810. this._gl.uniform1iv(uniform, array);
  8811. };
  8812. Engine.prototype.setIntArray2 = function (uniform, array) {
  8813. if (!uniform || array.length % 2 !== 0)
  8814. return;
  8815. this._gl.uniform2iv(uniform, array);
  8816. };
  8817. Engine.prototype.setIntArray3 = function (uniform, array) {
  8818. if (!uniform || array.length % 3 !== 0)
  8819. return;
  8820. this._gl.uniform3iv(uniform, array);
  8821. };
  8822. Engine.prototype.setIntArray4 = function (uniform, array) {
  8823. if (!uniform || array.length % 4 !== 0)
  8824. return;
  8825. this._gl.uniform4iv(uniform, array);
  8826. };
  8827. Engine.prototype.setFloatArray = function (uniform, array) {
  8828. if (!uniform)
  8829. return;
  8830. this._gl.uniform1fv(uniform, array);
  8831. };
  8832. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8833. if (!uniform || array.length % 2 !== 0)
  8834. return;
  8835. this._gl.uniform2fv(uniform, array);
  8836. };
  8837. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8838. if (!uniform || array.length % 3 !== 0)
  8839. return;
  8840. this._gl.uniform3fv(uniform, array);
  8841. };
  8842. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8843. if (!uniform || array.length % 4 !== 0)
  8844. return;
  8845. this._gl.uniform4fv(uniform, array);
  8846. };
  8847. Engine.prototype.setArray = function (uniform, array) {
  8848. if (!uniform)
  8849. return;
  8850. this._gl.uniform1fv(uniform, array);
  8851. };
  8852. Engine.prototype.setArray2 = function (uniform, array) {
  8853. if (!uniform || array.length % 2 !== 0)
  8854. return;
  8855. this._gl.uniform2fv(uniform, array);
  8856. };
  8857. Engine.prototype.setArray3 = function (uniform, array) {
  8858. if (!uniform || array.length % 3 !== 0)
  8859. return;
  8860. this._gl.uniform3fv(uniform, array);
  8861. };
  8862. Engine.prototype.setArray4 = function (uniform, array) {
  8863. if (!uniform || array.length % 4 !== 0)
  8864. return;
  8865. this._gl.uniform4fv(uniform, array);
  8866. };
  8867. Engine.prototype.setMatrices = function (uniform, matrices) {
  8868. if (!uniform)
  8869. return;
  8870. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8871. };
  8872. Engine.prototype.setMatrix = function (uniform, matrix) {
  8873. if (!uniform)
  8874. return;
  8875. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8876. };
  8877. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8878. if (!uniform)
  8879. return;
  8880. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8881. };
  8882. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8883. if (!uniform)
  8884. return;
  8885. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8886. };
  8887. Engine.prototype.setFloat = function (uniform, value) {
  8888. if (!uniform)
  8889. return;
  8890. this._gl.uniform1f(uniform, value);
  8891. };
  8892. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8893. if (!uniform)
  8894. return;
  8895. this._gl.uniform2f(uniform, x, y);
  8896. };
  8897. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8898. if (!uniform)
  8899. return;
  8900. this._gl.uniform3f(uniform, x, y, z);
  8901. };
  8902. Engine.prototype.setBool = function (uniform, bool) {
  8903. if (!uniform)
  8904. return;
  8905. this._gl.uniform1i(uniform, bool);
  8906. };
  8907. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8908. if (!uniform)
  8909. return;
  8910. this._gl.uniform4f(uniform, x, y, z, w);
  8911. };
  8912. Engine.prototype.setColor3 = function (uniform, color3) {
  8913. if (!uniform)
  8914. return;
  8915. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8916. };
  8917. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8918. if (!uniform)
  8919. return;
  8920. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8921. };
  8922. // States
  8923. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8924. if (zOffset === void 0) { zOffset = 0; }
  8925. if (reverseSide === void 0) { reverseSide = false; }
  8926. // Culling
  8927. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8928. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8929. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8930. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8931. if (culling) {
  8932. this._depthCullingState.cullFace = cullFace;
  8933. this._depthCullingState.cull = true;
  8934. }
  8935. else {
  8936. this._depthCullingState.cull = false;
  8937. }
  8938. }
  8939. // Z offset
  8940. this.setZOffset(zOffset);
  8941. };
  8942. Engine.prototype.setZOffset = function (value) {
  8943. this._depthCullingState.zOffset = value;
  8944. };
  8945. Engine.prototype.getZOffset = function () {
  8946. return this._depthCullingState.zOffset;
  8947. };
  8948. Engine.prototype.setDepthBuffer = function (enable) {
  8949. this._depthCullingState.depthTest = enable;
  8950. };
  8951. Engine.prototype.getDepthWrite = function () {
  8952. return this._depthCullingState.depthMask;
  8953. };
  8954. Engine.prototype.setDepthWrite = function (enable) {
  8955. this._depthCullingState.depthMask = enable;
  8956. };
  8957. Engine.prototype.setColorWrite = function (enable) {
  8958. this._gl.colorMask(enable, enable, enable, enable);
  8959. };
  8960. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8961. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8962. };
  8963. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8964. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8965. if (this._alphaMode === mode) {
  8966. return;
  8967. }
  8968. switch (mode) {
  8969. case Engine.ALPHA_DISABLE:
  8970. this._alphaState.alphaBlend = false;
  8971. break;
  8972. case Engine.ALPHA_PREMULTIPLIED:
  8973. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8974. this._alphaState.alphaBlend = true;
  8975. break;
  8976. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8977. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8978. this._alphaState.alphaBlend = true;
  8979. break;
  8980. case Engine.ALPHA_COMBINE:
  8981. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8982. this._alphaState.alphaBlend = true;
  8983. break;
  8984. case Engine.ALPHA_ONEONE:
  8985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8986. this._alphaState.alphaBlend = true;
  8987. break;
  8988. case Engine.ALPHA_ADD:
  8989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8990. this._alphaState.alphaBlend = true;
  8991. break;
  8992. case Engine.ALPHA_SUBTRACT:
  8993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8994. this._alphaState.alphaBlend = true;
  8995. break;
  8996. case Engine.ALPHA_MULTIPLY:
  8997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8998. this._alphaState.alphaBlend = true;
  8999. break;
  9000. case Engine.ALPHA_MAXIMIZED:
  9001. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9002. this._alphaState.alphaBlend = true;
  9003. break;
  9004. case Engine.ALPHA_INTERPOLATE:
  9005. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9006. this._alphaState.alphaBlend = true;
  9007. break;
  9008. case Engine.ALPHA_SCREENMODE:
  9009. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9010. this._alphaState.alphaBlend = true;
  9011. break;
  9012. }
  9013. if (!noDepthWriteChange) {
  9014. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9015. }
  9016. this._alphaMode = mode;
  9017. };
  9018. Engine.prototype.getAlphaMode = function () {
  9019. return this._alphaMode;
  9020. };
  9021. Engine.prototype.setAlphaTesting = function (enable) {
  9022. this._alphaTest = enable;
  9023. };
  9024. Engine.prototype.getAlphaTesting = function () {
  9025. return !!this._alphaTest;
  9026. };
  9027. // Textures
  9028. Engine.prototype.wipeCaches = function (bruteForce) {
  9029. if (this.preventCacheWipeBetweenFrames) {
  9030. return;
  9031. }
  9032. this.resetTextureCache();
  9033. this._currentEffect = null;
  9034. // 6/8/2017: deltakosh: Should not be required anymore.
  9035. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9036. if (bruteForce) {
  9037. this._stencilState.reset();
  9038. this._depthCullingState.reset();
  9039. this.setDepthFunctionToLessOrEqual();
  9040. this._alphaState.reset();
  9041. }
  9042. this._cachedVertexBuffers = null;
  9043. this._cachedIndexBuffer = null;
  9044. this._cachedEffectForVertexBuffers = null;
  9045. this._unBindVertexArrayObject();
  9046. this.bindIndexBuffer(null);
  9047. this.bindArrayBuffer(null);
  9048. };
  9049. /**
  9050. * Set the compressed texture format to use, based on the formats you have, and the formats
  9051. * supported by the hardware / browser.
  9052. *
  9053. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9054. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9055. * to API arguments needed to compressed textures. This puts the burden on the container
  9056. * generator to house the arcane code for determining these for current & future formats.
  9057. *
  9058. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9059. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9060. *
  9061. * Note: The result of this call is not taken into account when a texture is base64.
  9062. *
  9063. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9064. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9065. *
  9066. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9067. * @returns The extension selected.
  9068. */
  9069. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9070. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9071. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9072. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9073. return this._textureFormatInUse = this._texturesSupported[i];
  9074. }
  9075. }
  9076. }
  9077. // actively set format to nothing, to allow this to be called more than once
  9078. // and possibly fail the 2nd time
  9079. return this._textureFormatInUse = null;
  9080. };
  9081. /**
  9082. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9083. * @param {string} urlArg- This contains one of the following:
  9084. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9085. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9086. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9087. *
  9088. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9089. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9090. * @param {Scene} scene- Needed for loading to the correct scene.
  9091. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9092. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9093. * @param {callback} onError- Optional callback to be called upon failure.
  9094. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9095. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9096. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9097. *
  9098. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9099. */
  9100. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9101. var _this = this;
  9102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9103. if (onLoad === void 0) { onLoad = null; }
  9104. if (onError === void 0) { onError = null; }
  9105. if (buffer === void 0) { buffer = null; }
  9106. var texture = fallBack ? fallBack : this._gl.createTexture();
  9107. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9108. var fromData = url.substr(0, 5) === "data:";
  9109. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9110. // establish the file extension, if possible
  9111. var lastDot = url.lastIndexOf('.');
  9112. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9113. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9114. if (isDDS) {
  9115. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9116. }
  9117. var isTGA = (extension === ".tga");
  9118. // determine if a ktx file should be substituted
  9119. var isKTX = false;
  9120. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9121. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9122. isKTX = true;
  9123. }
  9124. scene._addPendingData(texture);
  9125. texture.url = url;
  9126. texture.noMipmap = noMipmap;
  9127. texture.references = 1;
  9128. texture.samplingMode = samplingMode;
  9129. texture.onLoadedCallbacks = [];
  9130. if (onLoad) {
  9131. texture.onLoadedCallbacks.push(onLoad);
  9132. }
  9133. if (!fallBack)
  9134. this._loadedTexturesCache.push(texture);
  9135. var onerror = function () {
  9136. scene._removePendingData(texture);
  9137. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9138. if (isKTX) {
  9139. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9140. }
  9141. else if (onError) {
  9142. onError();
  9143. }
  9144. };
  9145. var callback;
  9146. // processing for non-image formats
  9147. if (isKTX || isTGA || isDDS) {
  9148. if (isKTX) {
  9149. callback = function (data) {
  9150. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9151. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9152. ktx.uploadLevels(_this._gl, !noMipmap);
  9153. }, samplingMode);
  9154. };
  9155. }
  9156. else if (isTGA) {
  9157. callback = function (arrayBuffer) {
  9158. var data = new Uint8Array(arrayBuffer);
  9159. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9160. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9161. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9162. }, samplingMode);
  9163. };
  9164. }
  9165. else if (isDDS) {
  9166. callback = function (data) {
  9167. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9168. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9169. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9170. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 1);
  9171. }, samplingMode);
  9172. };
  9173. }
  9174. if (!buffer) {
  9175. BABYLON.Tools.LoadFile(url, function (data) {
  9176. callback(data);
  9177. }, null, scene.database, true, onerror);
  9178. }
  9179. else {
  9180. callback(buffer);
  9181. }
  9182. // image format processing
  9183. }
  9184. else {
  9185. var onload = function (img) {
  9186. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9187. var isPot = (img.width === potWidth && img.height === potHeight);
  9188. if (!isPot) {
  9189. _this._prepareWorkingCanvas();
  9190. _this._workingCanvas.width = potWidth;
  9191. _this._workingCanvas.height = potHeight;
  9192. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9193. _this._workingContext.imageSmoothingEnabled = false;
  9194. _this._workingContext.mozImageSmoothingEnabled = false;
  9195. _this._workingContext.oImageSmoothingEnabled = false;
  9196. _this._workingContext.webkitImageSmoothingEnabled = false;
  9197. _this._workingContext.msImageSmoothingEnabled = false;
  9198. }
  9199. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9200. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9201. _this._workingContext.imageSmoothingEnabled = true;
  9202. _this._workingContext.mozImageSmoothingEnabled = true;
  9203. _this._workingContext.oImageSmoothingEnabled = true;
  9204. _this._workingContext.webkitImageSmoothingEnabled = true;
  9205. _this._workingContext.msImageSmoothingEnabled = true;
  9206. }
  9207. }
  9208. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9209. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9210. }, samplingMode);
  9211. };
  9212. if (!fromData || isBase64)
  9213. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9214. else if (buffer instanceof Array || typeof buffer === "string")
  9215. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9216. else
  9217. onload(buffer);
  9218. }
  9219. return texture;
  9220. };
  9221. Engine.prototype._getInternalFormat = function (format) {
  9222. var internalFormat = this._gl.RGBA;
  9223. switch (format) {
  9224. case Engine.TEXTUREFORMAT_ALPHA:
  9225. internalFormat = this._gl.ALPHA;
  9226. break;
  9227. case Engine.TEXTUREFORMAT_LUMINANCE:
  9228. internalFormat = this._gl.LUMINANCE;
  9229. break;
  9230. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9231. internalFormat = this._gl.LUMINANCE_ALPHA;
  9232. break;
  9233. case Engine.TEXTUREFORMAT_RGB:
  9234. internalFormat = this._gl.RGB;
  9235. break;
  9236. case Engine.TEXTUREFORMAT_RGBA:
  9237. internalFormat = this._gl.RGBA;
  9238. break;
  9239. }
  9240. return internalFormat;
  9241. };
  9242. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9243. if (compression === void 0) { compression = null; }
  9244. var internalFormat = this._getInternalFormat(format);
  9245. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9246. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9247. if (texture._width % 4 !== 0) {
  9248. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9249. }
  9250. if (compression) {
  9251. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9252. }
  9253. else {
  9254. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9255. }
  9256. if (texture.generateMipMaps) {
  9257. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9258. }
  9259. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9260. this.resetTextureCache();
  9261. texture.isReady = true;
  9262. };
  9263. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9264. if (compression === void 0) { compression = null; }
  9265. var texture = this._gl.createTexture();
  9266. texture._baseWidth = width;
  9267. texture._baseHeight = height;
  9268. texture._width = width;
  9269. texture._height = height;
  9270. texture.references = 1;
  9271. this.updateRawTexture(texture, data, format, invertY, compression);
  9272. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9273. // Filters
  9274. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9275. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9276. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9277. if (generateMipMaps) {
  9278. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9279. }
  9280. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9281. texture.samplingMode = samplingMode;
  9282. this._loadedTexturesCache.push(texture);
  9283. return texture;
  9284. };
  9285. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9286. var texture = this._gl.createTexture();
  9287. texture._baseWidth = width;
  9288. texture._baseHeight = height;
  9289. if (generateMipMaps) {
  9290. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9291. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9292. }
  9293. this.resetTextureCache();
  9294. texture._width = width;
  9295. texture._height = height;
  9296. texture.isReady = false;
  9297. texture.generateMipMaps = generateMipMaps;
  9298. texture.references = 1;
  9299. texture.samplingMode = samplingMode;
  9300. this.updateTextureSamplingMode(samplingMode, texture);
  9301. this._loadedTexturesCache.push(texture);
  9302. return texture;
  9303. };
  9304. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9305. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9306. if (texture.isCube) {
  9307. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9308. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9309. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9310. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9311. }
  9312. else {
  9313. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9314. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9315. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9316. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9317. }
  9318. texture.samplingMode = samplingMode;
  9319. };
  9320. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9321. if (premulAlpha === void 0) { premulAlpha = false; }
  9322. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9323. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9324. if (premulAlpha) {
  9325. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9326. }
  9327. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9328. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9329. if (texture.generateMipMaps) {
  9330. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9331. }
  9332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9333. if (premulAlpha) {
  9334. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9335. }
  9336. this.resetTextureCache();
  9337. texture.isReady = true;
  9338. };
  9339. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9340. if (texture._isDisabled) {
  9341. return;
  9342. }
  9343. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9344. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9345. try {
  9346. // Testing video texture support
  9347. if (this._videoTextureSupported === undefined) {
  9348. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9349. if (this._gl.getError() !== 0) {
  9350. this._videoTextureSupported = false;
  9351. }
  9352. else {
  9353. this._videoTextureSupported = true;
  9354. }
  9355. }
  9356. // Copy video through the current working canvas if video texture is not supported
  9357. if (!this._videoTextureSupported) {
  9358. if (!texture._workingCanvas) {
  9359. texture._workingCanvas = document.createElement("canvas");
  9360. texture._workingContext = texture._workingCanvas.getContext("2d");
  9361. texture._workingCanvas.width = texture._width;
  9362. texture._workingCanvas.height = texture._height;
  9363. }
  9364. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9365. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9366. }
  9367. else {
  9368. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9369. }
  9370. if (texture.generateMipMaps) {
  9371. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9372. }
  9373. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9374. this.resetTextureCache();
  9375. texture.isReady = true;
  9376. }
  9377. catch (ex) {
  9378. // Something unexpected
  9379. // Let's disable the texture
  9380. texture._isDisabled = true;
  9381. }
  9382. };
  9383. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9384. // old version had a "generateMipMaps" arg instead of options.
  9385. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9386. // in the same way, generateDepthBuffer is defaulted to true
  9387. var generateMipMaps = false;
  9388. var generateDepthBuffer = true;
  9389. var generateStencilBuffer = false;
  9390. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9391. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9392. if (options !== undefined) {
  9393. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9394. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9395. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9396. type = options.type === undefined ? type : options.type;
  9397. if (options.samplingMode !== undefined) {
  9398. samplingMode = options.samplingMode;
  9399. }
  9400. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9401. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9402. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9403. }
  9404. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9405. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9406. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9407. }
  9408. }
  9409. var gl = this._gl;
  9410. var texture = gl.createTexture();
  9411. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9412. var width = size.width || size;
  9413. var height = size.height || size;
  9414. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9415. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9416. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9417. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9418. }
  9419. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9420. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9421. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9423. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9424. // Create the framebuffer
  9425. var framebuffer = gl.createFramebuffer();
  9426. this.bindUnboundFramebuffer(framebuffer);
  9427. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9428. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9429. if (generateMipMaps) {
  9430. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9431. }
  9432. // Unbind
  9433. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9434. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9435. this.bindUnboundFramebuffer(null);
  9436. texture._framebuffer = framebuffer;
  9437. texture._baseWidth = width;
  9438. texture._baseHeight = height;
  9439. texture._width = width;
  9440. texture._height = height;
  9441. texture.isReady = true;
  9442. texture.samples = 1;
  9443. texture.generateMipMaps = generateMipMaps;
  9444. texture.references = 1;
  9445. texture.samplingMode = samplingMode;
  9446. texture.type = type;
  9447. texture._generateDepthBuffer = generateDepthBuffer;
  9448. texture._generateStencilBuffer = generateStencilBuffer;
  9449. this.resetTextureCache();
  9450. this._loadedTexturesCache.push(texture);
  9451. return texture;
  9452. };
  9453. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9454. var generateMipMaps = false;
  9455. var generateDepthBuffer = true;
  9456. var generateStencilBuffer = false;
  9457. var generateDepthTexture = false;
  9458. var textureCount = 1;
  9459. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9460. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9461. var types = [], samplingModes = [];
  9462. if (options !== undefined) {
  9463. generateMipMaps = options.generateMipMaps;
  9464. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9465. generateStencilBuffer = options.generateStencilBuffer;
  9466. generateDepthTexture = options.generateDepthTexture;
  9467. textureCount = options.textureCount || 1;
  9468. if (options.types) {
  9469. types = options.types;
  9470. }
  9471. if (options.samplingModes) {
  9472. samplingModes = options.samplingModes;
  9473. }
  9474. }
  9475. var gl = this._gl;
  9476. // Create the framebuffer
  9477. var framebuffer = gl.createFramebuffer();
  9478. this.bindUnboundFramebuffer(framebuffer);
  9479. var width = size.width || size;
  9480. var height = size.height || size;
  9481. var textures = [];
  9482. var attachments = [];
  9483. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9484. for (var i = 0; i < textureCount; i++) {
  9485. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9486. var type = types[i] || defaultType;
  9487. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9488. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9489. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9490. }
  9491. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9492. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9493. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9494. }
  9495. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9496. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9497. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9498. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9499. }
  9500. var texture = gl.createTexture();
  9501. var attachment = gl["COLOR_ATTACHMENT" + i];
  9502. textures.push(texture);
  9503. attachments.push(attachment);
  9504. gl.activeTexture(gl["TEXTURE" + i]);
  9505. gl.bindTexture(gl.TEXTURE_2D, texture);
  9506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9507. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9508. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9509. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9510. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9511. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9512. if (generateMipMaps) {
  9513. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9514. }
  9515. // Unbind
  9516. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9517. texture._framebuffer = framebuffer;
  9518. texture._depthStencilBuffer = depthStencilBuffer;
  9519. texture._baseWidth = width;
  9520. texture._baseHeight = height;
  9521. texture._width = width;
  9522. texture._height = height;
  9523. texture.isReady = true;
  9524. texture.samples = 1;
  9525. texture.generateMipMaps = generateMipMaps;
  9526. texture.references = 1;
  9527. texture.samplingMode = samplingMode;
  9528. texture.type = type;
  9529. texture._generateDepthBuffer = generateDepthBuffer;
  9530. texture._generateStencilBuffer = generateStencilBuffer;
  9531. this._loadedTexturesCache.push(texture);
  9532. }
  9533. if (generateDepthTexture) {
  9534. // Depth texture
  9535. var depthTexture = gl.createTexture();
  9536. gl.activeTexture(gl.TEXTURE0);
  9537. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9538. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9539. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9540. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9542. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9543. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9544. depthTexture._framebuffer = framebuffer;
  9545. depthTexture._baseWidth = width;
  9546. depthTexture._baseHeight = height;
  9547. depthTexture._width = width;
  9548. depthTexture._height = height;
  9549. depthTexture.isReady = true;
  9550. depthTexture.samples = 1;
  9551. depthTexture.generateMipMaps = generateMipMaps;
  9552. depthTexture.references = 1;
  9553. depthTexture.samplingMode = gl.NEAREST;
  9554. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9555. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9556. textures.push(depthTexture);
  9557. this._loadedTexturesCache.push(depthTexture);
  9558. }
  9559. gl.drawBuffers(attachments);
  9560. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9561. this.bindUnboundFramebuffer(null);
  9562. this.resetTextureCache();
  9563. return textures;
  9564. };
  9565. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9566. if (samples === void 0) { samples = 1; }
  9567. var depthStencilBuffer = null;
  9568. var gl = this._gl;
  9569. // Create the depth/stencil buffer
  9570. if (generateStencilBuffer) {
  9571. depthStencilBuffer = gl.createRenderbuffer();
  9572. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9573. if (samples > 1) {
  9574. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9575. }
  9576. else {
  9577. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9578. }
  9579. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9580. }
  9581. else if (generateDepthBuffer) {
  9582. depthStencilBuffer = gl.createRenderbuffer();
  9583. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9584. if (samples > 1) {
  9585. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9586. }
  9587. else {
  9588. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9589. }
  9590. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9591. }
  9592. return depthStencilBuffer;
  9593. };
  9594. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9595. if (this.webGLVersion < 2) {
  9596. return 1;
  9597. }
  9598. if (texture.samples === samples) {
  9599. return samples;
  9600. }
  9601. var gl = this._gl;
  9602. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9603. // Dispose previous render buffers
  9604. if (texture._depthStencilBuffer) {
  9605. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9606. }
  9607. if (texture._MSAAFramebuffer) {
  9608. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9609. }
  9610. if (texture._MSAARenderBuffer) {
  9611. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9612. }
  9613. if (samples > 1) {
  9614. texture._MSAAFramebuffer = gl.createFramebuffer();
  9615. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9616. var colorRenderbuffer = gl.createRenderbuffer();
  9617. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9618. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9619. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9620. texture._MSAARenderBuffer = colorRenderbuffer;
  9621. }
  9622. else {
  9623. this.bindUnboundFramebuffer(texture._framebuffer);
  9624. }
  9625. texture.samples = samples;
  9626. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9627. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9628. this.bindUnboundFramebuffer(null);
  9629. return samples;
  9630. };
  9631. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  9632. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  9633. };
  9634. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  9635. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  9636. };
  9637. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9638. var gl = this._gl;
  9639. var texture = gl.createTexture();
  9640. var generateMipMaps = true;
  9641. var generateDepthBuffer = true;
  9642. var generateStencilBuffer = false;
  9643. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9644. if (options !== undefined) {
  9645. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9646. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9647. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9648. if (options.samplingMode !== undefined) {
  9649. samplingMode = options.samplingMode;
  9650. }
  9651. }
  9652. texture.isCube = true;
  9653. texture.references = 1;
  9654. texture.generateMipMaps = generateMipMaps;
  9655. texture.references = 1;
  9656. texture.samples = 1;
  9657. texture.samplingMode = samplingMode;
  9658. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9659. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9660. for (var face = 0; face < 6; face++) {
  9661. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9662. }
  9663. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9667. // Create the framebuffer
  9668. var framebuffer = gl.createFramebuffer();
  9669. this.bindUnboundFramebuffer(framebuffer);
  9670. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9671. // Mipmaps
  9672. if (texture.generateMipMaps) {
  9673. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9674. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9675. }
  9676. // Unbind
  9677. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9678. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9679. this.bindUnboundFramebuffer(null);
  9680. texture._framebuffer = framebuffer;
  9681. texture._width = size;
  9682. texture._height = size;
  9683. texture.isReady = true;
  9684. this.resetTextureCache();
  9685. this._loadedTexturesCache.push(texture);
  9686. return texture;
  9687. };
  9688. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9689. var _this = this;
  9690. if (onLoad === void 0) { onLoad = null; }
  9691. if (onError === void 0) { onError = null; }
  9692. var gl = this._gl;
  9693. var texture = gl.createTexture();
  9694. texture.isCube = true;
  9695. texture.url = rootUrl;
  9696. texture.references = 1;
  9697. texture.onLoadedCallbacks = [];
  9698. var isKTX = false;
  9699. var isDDS = false;
  9700. var lastDot = rootUrl.lastIndexOf('.');
  9701. var extension = rootUrl.substring(lastDot).toLowerCase();
  9702. if (this._textureFormatInUse) {
  9703. extension = this._textureFormatInUse;
  9704. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9705. isKTX = true;
  9706. }
  9707. else {
  9708. isDDS = (extension === ".dds");
  9709. }
  9710. if (isKTX) {
  9711. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9712. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9713. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9714. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9715. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9716. ktx.uploadLevels(_this._gl, !noMipmap);
  9717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9721. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9722. _this.resetTextureCache();
  9723. texture._width = ktx.pixelWidth;
  9724. texture._height = ktx.pixelHeight;
  9725. texture.isReady = true;
  9726. }, null, null, true, onError);
  9727. }
  9728. else if (isDDS) {
  9729. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9730. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9731. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9732. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9733. if (info.isCompressed) {
  9734. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9735. }
  9736. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 6);
  9737. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9738. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9739. }
  9740. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9741. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9742. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9743. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9744. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9745. _this.resetTextureCache();
  9746. texture._width = info.width;
  9747. texture._height = info.height;
  9748. texture.isReady = true;
  9749. texture.type = info.textureType;
  9750. }, null, null, true, onError);
  9751. }
  9752. else {
  9753. cascadeLoad(rootUrl, scene, function (imgs) {
  9754. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9755. var height = width;
  9756. _this._prepareWorkingCanvas();
  9757. _this._workingCanvas.width = width;
  9758. _this._workingCanvas.height = height;
  9759. var faces = [
  9760. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9761. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9762. ];
  9763. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9764. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9765. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9766. for (var index = 0; index < faces.length; index++) {
  9767. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9768. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9769. }
  9770. if (!noMipmap) {
  9771. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9772. }
  9773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9777. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9778. _this.resetTextureCache();
  9779. texture._width = width;
  9780. texture._height = height;
  9781. texture.isReady = true;
  9782. texture.onLoadedCallbacks.forEach(function (callback) {
  9783. callback();
  9784. });
  9785. if (onLoad) {
  9786. onLoad();
  9787. }
  9788. }, files, onError);
  9789. }
  9790. this._loadedTexturesCache.push(texture);
  9791. return texture;
  9792. };
  9793. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9794. texture._width = width;
  9795. texture._height = height;
  9796. texture._size = width * height;
  9797. texture._baseWidth = width;
  9798. texture._baseHeight = height;
  9799. };
  9800. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9801. if (compression === void 0) { compression = null; }
  9802. if (level === void 0) { level = 0; }
  9803. var gl = this._gl;
  9804. var textureType = this._getWebGLTextureType(type);
  9805. var internalFormat = this._getInternalFormat(format);
  9806. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9807. var needConversion = false;
  9808. if (internalFormat === gl.RGB) {
  9809. internalFormat = gl.RGBA;
  9810. needConversion = true;
  9811. }
  9812. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9813. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9814. if (texture._width % 4 !== 0) {
  9815. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9816. }
  9817. var facesIndex = [
  9818. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9819. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9820. ];
  9821. // Data are known to be in +X +Y +Z -X -Y -Z
  9822. for (var index = 0; index < facesIndex.length; index++) {
  9823. var faceData = data[index];
  9824. if (compression) {
  9825. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9826. }
  9827. else {
  9828. if (needConversion) {
  9829. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9830. }
  9831. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9832. }
  9833. }
  9834. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9835. if (isPot && texture.generateMipMaps && level === 0) {
  9836. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9837. }
  9838. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9839. this.resetTextureCache();
  9840. texture.isReady = true;
  9841. };
  9842. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9843. if (compression === void 0) { compression = null; }
  9844. var gl = this._gl;
  9845. var texture = gl.createTexture();
  9846. texture.isCube = true;
  9847. texture.references = 1;
  9848. var textureType = this._getWebGLTextureType(type);
  9849. var internalFormat = this._getInternalFormat(format);
  9850. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9851. var needConversion = false;
  9852. if (internalFormat === gl.RGB) {
  9853. internalFormat = gl.RGBA;
  9854. needConversion = true;
  9855. }
  9856. var width = size;
  9857. var height = width;
  9858. texture._width = width;
  9859. texture._height = height;
  9860. // Double check on POT to generate Mips.
  9861. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9862. if (!isPot) {
  9863. generateMipMaps = false;
  9864. }
  9865. texture.generateMipMaps = generateMipMaps;
  9866. // Upload data if needed. The texture won t be ready until then.
  9867. if (data) {
  9868. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9869. }
  9870. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9871. // Filters
  9872. if (data && generateMipMaps) {
  9873. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9874. }
  9875. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9878. }
  9879. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9882. }
  9883. else {
  9884. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9887. }
  9888. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9889. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9890. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9891. this._loadedTexturesCache.push(texture);
  9892. return texture;
  9893. };
  9894. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9895. var _this = this;
  9896. if (onLoad === void 0) { onLoad = null; }
  9897. if (onError === void 0) { onError = null; }
  9898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9899. if (invertY === void 0) { invertY = false; }
  9900. var gl = this._gl;
  9901. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9902. scene._addPendingData(texture);
  9903. texture.url = url;
  9904. var onerror = function () {
  9905. scene._removePendingData(texture);
  9906. if (onError) {
  9907. onError();
  9908. }
  9909. };
  9910. var internalCallback = function (data) {
  9911. var rgbeDataArrays = callback(data);
  9912. var facesIndex = [
  9913. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9914. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9915. ];
  9916. var width = texture._width;
  9917. var height = texture._height;
  9918. if (mipmmapGenerator) {
  9919. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9920. // I ll remove ASAP.
  9921. var textureType = _this._getWebGLTextureType(type);
  9922. var internalFormat = _this._getInternalFormat(format);
  9923. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9924. var needConversion = false;
  9925. if (internalFormat === gl.RGB) {
  9926. internalFormat = gl.RGBA;
  9927. needConversion = true;
  9928. }
  9929. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9930. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9931. var arrayTemp = [];
  9932. // Data are known to be in +X +Y +Z -X -Y -Z
  9933. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9934. arrayTemp.push(rgbeDataArrays[0]); // +X
  9935. arrayTemp.push(rgbeDataArrays[3]); // -X
  9936. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9937. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9938. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9939. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9940. var mipData = mipmmapGenerator(arrayTemp);
  9941. // mipData is order in +X -X +Y -Y +Z -Z
  9942. var mipFaces = [0, 2, 4, 1, 3, 5];
  9943. for (var level = 0; level < mipData.length; level++) {
  9944. var mipSize = width >> level;
  9945. for (var mipIndex in mipFaces) {
  9946. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9947. if (needConversion) {
  9948. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9949. }
  9950. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9951. }
  9952. }
  9953. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9954. }
  9955. else {
  9956. texture.generateMipMaps = !noMipmap;
  9957. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9958. }
  9959. texture.isReady = true;
  9960. _this.resetTextureCache();
  9961. scene._removePendingData(texture);
  9962. if (onLoad) {
  9963. onLoad();
  9964. }
  9965. };
  9966. BABYLON.Tools.LoadFile(url, function (data) {
  9967. internalCallback(data);
  9968. }, onerror, scene.database, true);
  9969. return texture;
  9970. };
  9971. ;
  9972. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9973. // Create new RGBA data container.
  9974. var rgbaData;
  9975. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9976. rgbaData = new Float32Array(width * height * 4);
  9977. }
  9978. else {
  9979. rgbaData = new Uint32Array(width * height * 4);
  9980. }
  9981. // Convert each pixel.
  9982. for (var x = 0; x < width; x++) {
  9983. for (var y = 0; y < height; y++) {
  9984. var index = (y * width + x) * 3;
  9985. var newIndex = (y * width + x) * 4;
  9986. // Map Old Value to new value.
  9987. rgbaData[newIndex + 0] = rgbData[index + 0];
  9988. rgbaData[newIndex + 1] = rgbData[index + 1];
  9989. rgbaData[newIndex + 2] = rgbData[index + 2];
  9990. // Add fully opaque alpha channel.
  9991. rgbaData[newIndex + 3] = 1;
  9992. }
  9993. }
  9994. return rgbaData;
  9995. };
  9996. Engine.prototype._releaseFramebufferObjects = function (texture) {
  9997. var gl = this._gl;
  9998. if (texture._framebuffer) {
  9999. gl.deleteFramebuffer(texture._framebuffer);
  10000. texture._framebuffer = null;
  10001. }
  10002. if (texture._depthStencilBuffer) {
  10003. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10004. texture._depthStencilBuffer = null;
  10005. }
  10006. if (texture._MSAAFramebuffer) {
  10007. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10008. texture._MSAAFramebuffer = null;
  10009. }
  10010. if (texture._MSAARenderBuffer) {
  10011. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10012. texture._MSAARenderBuffer = null;
  10013. }
  10014. };
  10015. Engine.prototype._releaseTexture = function (texture) {
  10016. var gl = this._gl;
  10017. this._releaseFramebufferObjects(texture);
  10018. gl.deleteTexture(texture);
  10019. // Unbind channels
  10020. this.unbindAllTextures();
  10021. var index = this._loadedTexturesCache.indexOf(texture);
  10022. if (index !== -1) {
  10023. this._loadedTexturesCache.splice(index, 1);
  10024. }
  10025. };
  10026. Engine.prototype.setProgram = function (program) {
  10027. if (this._currentProgram !== program) {
  10028. this._gl.useProgram(program);
  10029. this._currentProgram = program;
  10030. }
  10031. };
  10032. Engine.prototype.bindSamplers = function (effect) {
  10033. this.setProgram(effect.getProgram());
  10034. var samplers = effect.getSamplers();
  10035. for (var index = 0; index < samplers.length; index++) {
  10036. var uniform = effect.getUniform(samplers[index]);
  10037. this._gl.uniform1i(uniform, index);
  10038. }
  10039. this._currentEffect = null;
  10040. };
  10041. Engine.prototype.activateTexture = function (texture) {
  10042. if (this._activeTexture !== texture) {
  10043. this._gl.activeTexture(texture);
  10044. this._activeTexture = texture;
  10045. }
  10046. };
  10047. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10048. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10049. this._gl.bindTexture(target, texture);
  10050. this._activeTexturesCache[this._activeTexture] = texture;
  10051. }
  10052. };
  10053. Engine.prototype._bindTexture = function (channel, texture) {
  10054. if (channel < 0) {
  10055. return;
  10056. }
  10057. this.activateTexture(this._gl.TEXTURE0 + channel);
  10058. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10059. };
  10060. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10061. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10062. };
  10063. Engine.prototype.unbindAllTextures = function () {
  10064. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10065. this.activateTexture(this._gl["TEXTURE" + channel]);
  10066. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10067. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10068. }
  10069. };
  10070. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10071. if (channel < 0) {
  10072. return;
  10073. }
  10074. this._gl.uniform1i(uniform, channel);
  10075. this._setTexture(channel, texture);
  10076. };
  10077. Engine.prototype._setTexture = function (channel, texture) {
  10078. // Not ready?
  10079. if (!texture) {
  10080. if (this._activeTexturesCache[channel] != null) {
  10081. this.activateTexture(this._gl["TEXTURE" + channel]);
  10082. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10083. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10084. }
  10085. return;
  10086. }
  10087. // Video
  10088. var alreadyActivated = false;
  10089. if (texture.video) {
  10090. this.activateTexture(this._gl["TEXTURE" + channel]);
  10091. alreadyActivated = true;
  10092. texture.update();
  10093. }
  10094. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10095. texture.delayLoad();
  10096. return;
  10097. }
  10098. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10099. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10100. if (this._activeTexturesCache[channel] === internalTexture) {
  10101. return;
  10102. }
  10103. if (!alreadyActivated) {
  10104. this.activateTexture(this._gl["TEXTURE" + channel]);
  10105. }
  10106. if (internalTexture.isCube) {
  10107. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10108. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10109. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10110. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10111. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10112. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10113. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10114. }
  10115. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10116. }
  10117. else {
  10118. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10119. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10120. internalTexture._cachedWrapU = texture.wrapU;
  10121. switch (texture.wrapU) {
  10122. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10123. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10124. break;
  10125. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10126. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10127. break;
  10128. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10129. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10130. break;
  10131. }
  10132. }
  10133. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10134. internalTexture._cachedWrapV = texture.wrapV;
  10135. switch (texture.wrapV) {
  10136. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10137. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10138. break;
  10139. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10140. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10141. break;
  10142. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10143. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10144. break;
  10145. }
  10146. }
  10147. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10148. }
  10149. };
  10150. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10151. if (channel < 0) {
  10152. return;
  10153. }
  10154. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10155. this._textureUnits = new Int32Array(textures.length);
  10156. }
  10157. for (var i = 0; i < textures.length; i++) {
  10158. this._textureUnits[i] = channel + i;
  10159. }
  10160. this._gl.uniform1iv(uniform, this._textureUnits);
  10161. for (var index = 0; index < textures.length; index++) {
  10162. this._setTexture(channel + index, textures[index]);
  10163. }
  10164. };
  10165. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10166. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10167. var value = texture.anisotropicFilteringLevel;
  10168. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10169. value = 1;
  10170. }
  10171. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10172. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10173. texture._cachedAnisotropicFilteringLevel = value;
  10174. }
  10175. };
  10176. Engine.prototype.readPixels = function (x, y, width, height) {
  10177. var data = new Uint8Array(height * width * 4);
  10178. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10179. return data;
  10180. };
  10181. /**
  10182. * Add an externaly attached data from its key.
  10183. * This method call will fail and return false, if such key already exists.
  10184. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10185. * @param key the unique key that identifies the data
  10186. * @param data the data object to associate to the key for this Engine instance
  10187. * @return true if no such key were already present and the data was added successfully, false otherwise
  10188. */
  10189. Engine.prototype.addExternalData = function (key, data) {
  10190. if (!this._externalData) {
  10191. this._externalData = new BABYLON.StringDictionary();
  10192. }
  10193. return this._externalData.add(key, data);
  10194. };
  10195. /**
  10196. * Get an externaly attached data from its key
  10197. * @param key the unique key that identifies the data
  10198. * @return the associated data, if present (can be null), or undefined if not present
  10199. */
  10200. Engine.prototype.getExternalData = function (key) {
  10201. if (!this._externalData) {
  10202. this._externalData = new BABYLON.StringDictionary();
  10203. }
  10204. return this._externalData.get(key);
  10205. };
  10206. /**
  10207. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10208. * @param key the unique key that identifies the data
  10209. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10210. * @return the associated data, can be null if the factory returned null.
  10211. */
  10212. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10213. if (!this._externalData) {
  10214. this._externalData = new BABYLON.StringDictionary();
  10215. }
  10216. return this._externalData.getOrAddWithFactory(key, factory);
  10217. };
  10218. /**
  10219. * Remove an externaly attached data from the Engine instance
  10220. * @param key the unique key that identifies the data
  10221. * @return true if the data was successfully removed, false if it doesn't exist
  10222. */
  10223. Engine.prototype.removeExternalData = function (key) {
  10224. if (!this._externalData) {
  10225. this._externalData = new BABYLON.StringDictionary();
  10226. }
  10227. return this._externalData.remove(key);
  10228. };
  10229. Engine.prototype.releaseInternalTexture = function (texture) {
  10230. if (!texture) {
  10231. return;
  10232. }
  10233. texture.references--;
  10234. // Final reference ?
  10235. if (texture.references === 0) {
  10236. var texturesCache = this.getLoadedTexturesCache();
  10237. var index = texturesCache.indexOf(texture);
  10238. if (index > -1) {
  10239. texturesCache.splice(index, 1);
  10240. }
  10241. this._releaseTexture(texture);
  10242. }
  10243. };
  10244. Engine.prototype.unbindAllAttributes = function () {
  10245. if (this._mustWipeVertexAttributes) {
  10246. this._mustWipeVertexAttributes = false;
  10247. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10248. this._gl.disableVertexAttribArray(i);
  10249. this._vertexAttribArraysEnabled[i] = false;
  10250. this._currentBufferPointers[i] = null;
  10251. }
  10252. return;
  10253. }
  10254. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10255. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10256. continue;
  10257. }
  10258. this._gl.disableVertexAttribArray(i);
  10259. this._vertexAttribArraysEnabled[i] = false;
  10260. this._currentBufferPointers[i] = null;
  10261. }
  10262. };
  10263. Engine.prototype.releaseEffects = function () {
  10264. for (var name in this._compiledEffects) {
  10265. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10266. }
  10267. this._compiledEffects = {};
  10268. };
  10269. // Dispose
  10270. Engine.prototype.dispose = function () {
  10271. this.hideLoadingUI();
  10272. this.stopRenderLoop();
  10273. // Empty texture
  10274. if (this._emptyTexture) {
  10275. this._releaseTexture(this._emptyTexture);
  10276. this._emptyTexture = null;
  10277. }
  10278. if (this._emptyCubeTexture) {
  10279. this._releaseTexture(this._emptyCubeTexture);
  10280. this._emptyCubeTexture = null;
  10281. }
  10282. // Release scenes
  10283. while (this.scenes.length) {
  10284. this.scenes[0].dispose();
  10285. }
  10286. // Release audio engine
  10287. if (Engine.audioEngine) {
  10288. Engine.audioEngine.dispose();
  10289. }
  10290. // Release effects
  10291. this.releaseEffects();
  10292. // Unbind
  10293. this.unbindAllAttributes();
  10294. if (this._dummyFramebuffer) {
  10295. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10296. }
  10297. this._gl = null;
  10298. //WebVR
  10299. this.disableVR();
  10300. // Events
  10301. window.removeEventListener("blur", this._onBlur);
  10302. window.removeEventListener("focus", this._onFocus);
  10303. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10304. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10305. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10306. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10307. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10308. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10309. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10310. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10311. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10312. // Remove from Instances
  10313. var index = Engine.Instances.indexOf(this);
  10314. if (index >= 0) {
  10315. Engine.Instances.splice(index, 1);
  10316. }
  10317. };
  10318. // Loading screen
  10319. Engine.prototype.displayLoadingUI = function () {
  10320. var loadingScreen = this.loadingScreen;
  10321. if (loadingScreen) {
  10322. loadingScreen.displayLoadingUI();
  10323. }
  10324. };
  10325. Engine.prototype.hideLoadingUI = function () {
  10326. var loadingScreen = this.loadingScreen;
  10327. if (loadingScreen) {
  10328. loadingScreen.hideLoadingUI();
  10329. }
  10330. };
  10331. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10332. get: function () {
  10333. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10334. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10335. return this._loadingScreen;
  10336. },
  10337. set: function (loadingScreen) {
  10338. this._loadingScreen = loadingScreen;
  10339. },
  10340. enumerable: true,
  10341. configurable: true
  10342. });
  10343. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10344. set: function (text) {
  10345. this.loadingScreen.loadingUIText = text;
  10346. },
  10347. enumerable: true,
  10348. configurable: true
  10349. });
  10350. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10351. set: function (color) {
  10352. this.loadingScreen.loadingUIBackgroundColor = color;
  10353. },
  10354. enumerable: true,
  10355. configurable: true
  10356. });
  10357. Engine.prototype.attachContextLostEvent = function (callback) {
  10358. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10359. };
  10360. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10361. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10362. };
  10363. Engine.prototype.getVertexShaderSource = function (program) {
  10364. var shaders = this._gl.getAttachedShaders(program);
  10365. return this._gl.getShaderSource(shaders[0]);
  10366. };
  10367. Engine.prototype.getFragmentShaderSource = function (program) {
  10368. var shaders = this._gl.getAttachedShaders(program);
  10369. return this._gl.getShaderSource(shaders[1]);
  10370. };
  10371. Engine.prototype.getError = function () {
  10372. return this._gl.getError();
  10373. };
  10374. // FPS
  10375. Engine.prototype.getFps = function () {
  10376. return this.fps;
  10377. };
  10378. Engine.prototype.getDeltaTime = function () {
  10379. return this.deltaTime;
  10380. };
  10381. Engine.prototype._measureFps = function () {
  10382. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10383. var length = this.previousFramesDuration.length;
  10384. if (length >= 2) {
  10385. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10386. }
  10387. if (length >= this.fpsRange) {
  10388. if (length > this.fpsRange) {
  10389. this.previousFramesDuration.splice(0, 1);
  10390. length = this.previousFramesDuration.length;
  10391. }
  10392. var sum = 0;
  10393. for (var id = 0; id < length - 1; id++) {
  10394. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10395. }
  10396. this.fps = 1000.0 / (sum / (length - 1));
  10397. }
  10398. };
  10399. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, lodIndex) {
  10400. if (faceIndex === void 0) { faceIndex = -1; }
  10401. if (lodIndex === void 0) { lodIndex = 0; }
  10402. var gl = this._gl;
  10403. if (!this._dummyFramebuffer) {
  10404. this._dummyFramebuffer = gl.createFramebuffer();
  10405. }
  10406. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10407. if (faceIndex > -1) {
  10408. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, lodIndex);
  10409. }
  10410. else {
  10411. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, lodIndex);
  10412. }
  10413. var readFormat = gl.RGBA;
  10414. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10415. var buffer = new Uint8Array(4 * width * height);
  10416. gl.readPixels(0, 0, width, height, readFormat, readType, buffer);
  10417. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10418. return buffer;
  10419. };
  10420. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10421. if (this._webGLVersion > 1) {
  10422. return this._caps.colorBufferFloat;
  10423. }
  10424. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10425. };
  10426. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10427. if (this._webGLVersion > 1) {
  10428. return this._caps.colorBufferFloat;
  10429. }
  10430. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10431. };
  10432. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10433. Engine.prototype._canRenderToFramebuffer = function (type) {
  10434. var gl = this._gl;
  10435. //clear existing errors
  10436. while (gl.getError() !== gl.NO_ERROR) { }
  10437. var successful = true;
  10438. var texture = gl.createTexture();
  10439. gl.bindTexture(gl.TEXTURE_2D, texture);
  10440. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10441. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10442. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10443. var fb = gl.createFramebuffer();
  10444. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10445. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10446. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10447. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10448. successful = successful && (gl.getError() === gl.NO_ERROR);
  10449. //try render by clearing frame buffer's color buffer
  10450. if (successful) {
  10451. gl.clear(gl.COLOR_BUFFER_BIT);
  10452. successful = successful && (gl.getError() === gl.NO_ERROR);
  10453. }
  10454. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10455. if (successful) {
  10456. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10457. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10458. var readFormat = gl.RGBA;
  10459. var readType = gl.UNSIGNED_BYTE;
  10460. var buffer = new Uint8Array(4);
  10461. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10462. successful = successful && (gl.getError() === gl.NO_ERROR);
  10463. }
  10464. //clean up
  10465. gl.deleteTexture(texture);
  10466. gl.deleteFramebuffer(fb);
  10467. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10468. //clear accumulated errors
  10469. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10470. return successful;
  10471. };
  10472. Engine.prototype._getWebGLTextureType = function (type) {
  10473. if (type === Engine.TEXTURETYPE_FLOAT) {
  10474. return this._gl.FLOAT;
  10475. }
  10476. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10477. // Add Half Float Constant.
  10478. return this._gl.HALF_FLOAT_OES;
  10479. }
  10480. return this._gl.UNSIGNED_BYTE;
  10481. };
  10482. ;
  10483. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10484. if (this._webGLVersion === 1) {
  10485. return this._gl.RGBA;
  10486. }
  10487. if (type === Engine.TEXTURETYPE_FLOAT) {
  10488. return this._gl.RGBA32F;
  10489. }
  10490. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10491. return this._gl.RGBA16F;
  10492. }
  10493. return this._gl.RGBA;
  10494. };
  10495. ;
  10496. // Statics
  10497. Engine.isSupported = function () {
  10498. try {
  10499. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10500. if (navigator.isCocoonJS) {
  10501. return true;
  10502. }
  10503. var tempcanvas = document.createElement("canvas");
  10504. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10505. return gl != null && !!window.WebGLRenderingContext;
  10506. }
  10507. catch (e) {
  10508. return false;
  10509. }
  10510. };
  10511. return Engine;
  10512. }());
  10513. Engine.Instances = new Array();
  10514. // Const statics
  10515. Engine._ALPHA_DISABLE = 0;
  10516. Engine._ALPHA_ADD = 1;
  10517. Engine._ALPHA_COMBINE = 2;
  10518. Engine._ALPHA_SUBTRACT = 3;
  10519. Engine._ALPHA_MULTIPLY = 4;
  10520. Engine._ALPHA_MAXIMIZED = 5;
  10521. Engine._ALPHA_ONEONE = 6;
  10522. Engine._ALPHA_PREMULTIPLIED = 7;
  10523. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10524. Engine._ALPHA_INTERPOLATE = 9;
  10525. Engine._ALPHA_SCREENMODE = 10;
  10526. Engine._DELAYLOADSTATE_NONE = 0;
  10527. Engine._DELAYLOADSTATE_LOADED = 1;
  10528. Engine._DELAYLOADSTATE_LOADING = 2;
  10529. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10530. Engine._TEXTUREFORMAT_ALPHA = 0;
  10531. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10532. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10533. Engine._TEXTUREFORMAT_RGB = 4;
  10534. Engine._TEXTUREFORMAT_RGBA = 5;
  10535. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10536. Engine._TEXTURETYPE_FLOAT = 1;
  10537. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10538. // Depht or Stencil test Constants.
  10539. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10540. 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.
  10541. 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.
  10542. 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.
  10543. 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.
  10544. 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.
  10545. 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.
  10546. 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.
  10547. // Stencil Actions Constants.
  10548. Engine._KEEP = 0x1E00;
  10549. Engine._REPLACE = 0x1E01;
  10550. Engine._INCR = 0x1E02;
  10551. Engine._DECR = 0x1E03;
  10552. Engine._INVERT = 0x150A;
  10553. Engine._INCR_WRAP = 0x8507;
  10554. Engine._DECR_WRAP = 0x8508;
  10555. // Texture rescaling mode
  10556. Engine._SCALEMODE_FLOOR = 1;
  10557. Engine._SCALEMODE_NEAREST = 2;
  10558. Engine._SCALEMODE_CEILING = 3;
  10559. // Updatable statics so stick with vars here
  10560. Engine.CollisionsEpsilon = 0.001;
  10561. Engine.CodeRepository = "src/";
  10562. Engine.ShadersRepository = "src/Shaders/";
  10563. BABYLON.Engine = Engine;
  10564. })(BABYLON || (BABYLON = {}));
  10565. //# sourceMappingURL=babylon.engine.js.map
  10566. /// <reference path="Tools\babylon.decorators.ts" />
  10567. var BABYLON;
  10568. (function (BABYLON) {
  10569. /**
  10570. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10571. */
  10572. var Node = (function () {
  10573. /**
  10574. * @constructor
  10575. * @param {string} name - the name and id to be given to this node
  10576. * @param {BABYLON.Scene} the scene this node will be added to
  10577. */
  10578. function Node(name, scene) {
  10579. this.state = "";
  10580. this.metadata = null;
  10581. this.doNotSerialize = false;
  10582. this.animations = new Array();
  10583. this._ranges = {};
  10584. this._childrenFlag = -1;
  10585. this._isEnabled = true;
  10586. this._isReady = true;
  10587. this._currentRenderId = -1;
  10588. this._parentRenderId = -1;
  10589. /**
  10590. * An event triggered when the mesh is disposed.
  10591. * @type {BABYLON.Observable}
  10592. */
  10593. this.onDisposeObservable = new BABYLON.Observable();
  10594. this.name = name;
  10595. this.id = name;
  10596. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10597. this._initCache();
  10598. }
  10599. Object.defineProperty(Node.prototype, "parent", {
  10600. get: function () {
  10601. return this._parentNode;
  10602. },
  10603. set: function (parent) {
  10604. if (this._parentNode === parent) {
  10605. return;
  10606. }
  10607. if (this._parentNode) {
  10608. var index = this._parentNode._children.indexOf(this);
  10609. if (index !== -1) {
  10610. this._parentNode._children.splice(index, 1);
  10611. }
  10612. }
  10613. this._parentNode = parent;
  10614. if (this._parentNode) {
  10615. if (!this._parentNode._children) {
  10616. this._parentNode._children = new Array();
  10617. }
  10618. this._parentNode._children.push(this);
  10619. }
  10620. },
  10621. enumerable: true,
  10622. configurable: true
  10623. });
  10624. Node.prototype.getClassName = function () {
  10625. return "Node";
  10626. };
  10627. Object.defineProperty(Node.prototype, "onDispose", {
  10628. set: function (callback) {
  10629. if (this._onDisposeObserver) {
  10630. this.onDisposeObservable.remove(this._onDisposeObserver);
  10631. }
  10632. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10633. },
  10634. enumerable: true,
  10635. configurable: true
  10636. });
  10637. Node.prototype.getScene = function () {
  10638. return this._scene;
  10639. };
  10640. Node.prototype.getEngine = function () {
  10641. return this._scene.getEngine();
  10642. };
  10643. // override it in derived class
  10644. Node.prototype.getWorldMatrix = function () {
  10645. return BABYLON.Matrix.Identity();
  10646. };
  10647. // override it in derived class if you add new variables to the cache
  10648. // and call the parent class method
  10649. Node.prototype._initCache = function () {
  10650. this._cache = {};
  10651. this._cache.parent = undefined;
  10652. };
  10653. Node.prototype.updateCache = function (force) {
  10654. if (!force && this.isSynchronized())
  10655. return;
  10656. this._cache.parent = this.parent;
  10657. this._updateCache();
  10658. };
  10659. // override it in derived class if you add new variables to the cache
  10660. // and call the parent class method if !ignoreParentClass
  10661. Node.prototype._updateCache = function (ignoreParentClass) {
  10662. };
  10663. // override it in derived class if you add new variables to the cache
  10664. Node.prototype._isSynchronized = function () {
  10665. return true;
  10666. };
  10667. Node.prototype._markSyncedWithParent = function () {
  10668. this._parentRenderId = this.parent._currentRenderId;
  10669. };
  10670. Node.prototype.isSynchronizedWithParent = function () {
  10671. if (!this.parent) {
  10672. return true;
  10673. }
  10674. if (this._parentRenderId !== this.parent._currentRenderId) {
  10675. return false;
  10676. }
  10677. return this.parent.isSynchronized();
  10678. };
  10679. Node.prototype.isSynchronized = function (updateCache) {
  10680. var check = this.hasNewParent();
  10681. check = check || !this.isSynchronizedWithParent();
  10682. check = check || !this._isSynchronized();
  10683. if (updateCache)
  10684. this.updateCache(true);
  10685. return !check;
  10686. };
  10687. Node.prototype.hasNewParent = function (update) {
  10688. if (this._cache.parent === this.parent)
  10689. return false;
  10690. if (update)
  10691. this._cache.parent = this.parent;
  10692. return true;
  10693. };
  10694. /**
  10695. * Is this node ready to be used/rendered
  10696. * @return {boolean} is it ready
  10697. */
  10698. Node.prototype.isReady = function () {
  10699. return this._isReady;
  10700. };
  10701. /**
  10702. * Is this node enabled.
  10703. * If the node has a parent and is enabled, the parent will be inspected as well.
  10704. * @return {boolean} whether this node (and its parent) is enabled.
  10705. * @see setEnabled
  10706. */
  10707. Node.prototype.isEnabled = function () {
  10708. if (!this._isEnabled) {
  10709. return false;
  10710. }
  10711. if (this.parent) {
  10712. return this.parent.isEnabled();
  10713. }
  10714. return true;
  10715. };
  10716. /**
  10717. * Set the enabled state of this node.
  10718. * @param {boolean} value - the new enabled state
  10719. * @see isEnabled
  10720. */
  10721. Node.prototype.setEnabled = function (value) {
  10722. this._isEnabled = value;
  10723. };
  10724. /**
  10725. * Is this node a descendant of the given node.
  10726. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10727. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10728. * @see parent
  10729. */
  10730. Node.prototype.isDescendantOf = function (ancestor) {
  10731. if (this.parent) {
  10732. if (this.parent === ancestor) {
  10733. return true;
  10734. }
  10735. return this.parent.isDescendantOf(ancestor);
  10736. }
  10737. return false;
  10738. };
  10739. /**
  10740. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10741. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10742. * @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.
  10743. * @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.
  10744. */
  10745. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10746. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10747. if (!this._children) {
  10748. return;
  10749. }
  10750. for (var index = 0; index < this._children.length; index++) {
  10751. var item = this._children[index];
  10752. if (!predicate || predicate(item)) {
  10753. results.push(item);
  10754. }
  10755. if (!directDescendantsOnly) {
  10756. item._getDescendants(results, false, predicate);
  10757. }
  10758. }
  10759. };
  10760. /**
  10761. * Will return all nodes that have this node as ascendant.
  10762. * @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.
  10763. * @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.
  10764. * @return {BABYLON.Node[]} all children nodes of all types.
  10765. */
  10766. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10767. var results = [];
  10768. this._getDescendants(results, directDescendantsOnly, predicate);
  10769. return results;
  10770. };
  10771. /**
  10772. * Get all child-meshes of this node.
  10773. */
  10774. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10775. var results = [];
  10776. this._getDescendants(results, directDecendantsOnly, function (node) {
  10777. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10778. });
  10779. return results;
  10780. };
  10781. /**
  10782. * Get all direct children of this node.
  10783. */
  10784. Node.prototype.getChildren = function (predicate) {
  10785. return this.getDescendants(true, predicate);
  10786. };
  10787. Node.prototype._setReady = function (state) {
  10788. if (state === this._isReady) {
  10789. return;
  10790. }
  10791. if (!state) {
  10792. this._isReady = false;
  10793. return;
  10794. }
  10795. this._isReady = true;
  10796. if (this.onReady) {
  10797. this.onReady(this);
  10798. }
  10799. };
  10800. Node.prototype.getAnimationByName = function (name) {
  10801. for (var i = 0; i < this.animations.length; i++) {
  10802. var animation = this.animations[i];
  10803. if (animation.name === name) {
  10804. return animation;
  10805. }
  10806. }
  10807. return null;
  10808. };
  10809. Node.prototype.createAnimationRange = function (name, from, to) {
  10810. // check name not already in use
  10811. if (!this._ranges[name]) {
  10812. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10813. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10814. if (this.animations[i]) {
  10815. this.animations[i].createRange(name, from, to);
  10816. }
  10817. }
  10818. }
  10819. };
  10820. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10821. if (deleteFrames === void 0) { deleteFrames = true; }
  10822. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10823. if (this.animations[i]) {
  10824. this.animations[i].deleteRange(name, deleteFrames);
  10825. }
  10826. }
  10827. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10828. };
  10829. Node.prototype.getAnimationRange = function (name) {
  10830. return this._ranges[name];
  10831. };
  10832. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10833. var range = this.getAnimationRange(name);
  10834. if (!range) {
  10835. return null;
  10836. }
  10837. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10838. };
  10839. Node.prototype.serializeAnimationRanges = function () {
  10840. var serializationRanges = [];
  10841. for (var name in this._ranges) {
  10842. var range = {};
  10843. range.name = name;
  10844. range.from = this._ranges[name].from;
  10845. range.to = this._ranges[name].to;
  10846. serializationRanges.push(range);
  10847. }
  10848. return serializationRanges;
  10849. };
  10850. Node.prototype.dispose = function () {
  10851. this.parent = null;
  10852. // Callback
  10853. this.onDisposeObservable.notifyObservers(this);
  10854. this.onDisposeObservable.clear();
  10855. };
  10856. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10857. if (parsedNode.ranges) {
  10858. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10859. var data = parsedNode.ranges[index];
  10860. node.createAnimationRange(data.name, data.from, data.to);
  10861. }
  10862. }
  10863. };
  10864. return Node;
  10865. }());
  10866. __decorate([
  10867. BABYLON.serialize()
  10868. ], Node.prototype, "name", void 0);
  10869. __decorate([
  10870. BABYLON.serialize()
  10871. ], Node.prototype, "id", void 0);
  10872. __decorate([
  10873. BABYLON.serialize()
  10874. ], Node.prototype, "uniqueId", void 0);
  10875. __decorate([
  10876. BABYLON.serialize()
  10877. ], Node.prototype, "state", void 0);
  10878. __decorate([
  10879. BABYLON.serialize()
  10880. ], Node.prototype, "metadata", void 0);
  10881. BABYLON.Node = Node;
  10882. })(BABYLON || (BABYLON = {}));
  10883. //# sourceMappingURL=babylon.node.js.map
  10884. var BABYLON;
  10885. (function (BABYLON) {
  10886. var BoundingSphere = (function () {
  10887. function BoundingSphere(minimum, maximum) {
  10888. this.minimum = minimum;
  10889. this.maximum = maximum;
  10890. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10891. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10892. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10893. this.radius = distance * 0.5;
  10894. this.centerWorld = BABYLON.Vector3.Zero();
  10895. this._update(BABYLON.Matrix.Identity());
  10896. }
  10897. // Methods
  10898. BoundingSphere.prototype._update = function (world) {
  10899. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10900. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10901. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10902. };
  10903. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10904. for (var i = 0; i < 6; i++) {
  10905. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10906. return false;
  10907. }
  10908. return true;
  10909. };
  10910. BoundingSphere.prototype.intersectsPoint = function (point) {
  10911. var x = this.centerWorld.x - point.x;
  10912. var y = this.centerWorld.y - point.y;
  10913. var z = this.centerWorld.z - point.z;
  10914. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10915. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10916. return false;
  10917. return true;
  10918. };
  10919. // Statics
  10920. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10921. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10922. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10923. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10924. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10925. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10926. return false;
  10927. return true;
  10928. };
  10929. return BoundingSphere;
  10930. }());
  10931. BABYLON.BoundingSphere = BoundingSphere;
  10932. })(BABYLON || (BABYLON = {}));
  10933. //# sourceMappingURL=babylon.boundingSphere.js.map
  10934. var BABYLON;
  10935. (function (BABYLON) {
  10936. var BoundingBox = (function () {
  10937. function BoundingBox(minimum, maximum) {
  10938. this.minimum = minimum;
  10939. this.maximum = maximum;
  10940. this.vectors = new Array();
  10941. this.vectorsWorld = new Array();
  10942. // Bounding vectors
  10943. this.vectors.push(this.minimum.clone());
  10944. this.vectors.push(this.maximum.clone());
  10945. this.vectors.push(this.minimum.clone());
  10946. this.vectors[2].x = this.maximum.x;
  10947. this.vectors.push(this.minimum.clone());
  10948. this.vectors[3].y = this.maximum.y;
  10949. this.vectors.push(this.minimum.clone());
  10950. this.vectors[4].z = this.maximum.z;
  10951. this.vectors.push(this.maximum.clone());
  10952. this.vectors[5].z = this.minimum.z;
  10953. this.vectors.push(this.maximum.clone());
  10954. this.vectors[6].x = this.minimum.x;
  10955. this.vectors.push(this.maximum.clone());
  10956. this.vectors[7].y = this.minimum.y;
  10957. // OBB
  10958. this.center = this.maximum.add(this.minimum).scale(0.5);
  10959. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10960. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10961. // World
  10962. for (var index = 0; index < this.vectors.length; index++) {
  10963. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10964. }
  10965. this.minimumWorld = BABYLON.Vector3.Zero();
  10966. this.maximumWorld = BABYLON.Vector3.Zero();
  10967. this.centerWorld = BABYLON.Vector3.Zero();
  10968. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10969. this._update(BABYLON.Matrix.Identity());
  10970. }
  10971. // Methods
  10972. BoundingBox.prototype.getWorldMatrix = function () {
  10973. return this._worldMatrix;
  10974. };
  10975. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10976. this._worldMatrix.copyFrom(matrix);
  10977. return this;
  10978. };
  10979. BoundingBox.prototype._update = function (world) {
  10980. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10981. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10982. for (var index = 0; index < this.vectors.length; index++) {
  10983. var v = this.vectorsWorld[index];
  10984. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10985. if (v.x < this.minimumWorld.x)
  10986. this.minimumWorld.x = v.x;
  10987. if (v.y < this.minimumWorld.y)
  10988. this.minimumWorld.y = v.y;
  10989. if (v.z < this.minimumWorld.z)
  10990. this.minimumWorld.z = v.z;
  10991. if (v.x > this.maximumWorld.x)
  10992. this.maximumWorld.x = v.x;
  10993. if (v.y > this.maximumWorld.y)
  10994. this.maximumWorld.y = v.y;
  10995. if (v.z > this.maximumWorld.z)
  10996. this.maximumWorld.z = v.z;
  10997. }
  10998. // Extend
  10999. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11000. this.extendSizeWorld.scaleInPlace(0.5);
  11001. // OBB
  11002. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11003. this.centerWorld.scaleInPlace(0.5);
  11004. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11005. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11006. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11007. this._worldMatrix = world;
  11008. };
  11009. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11010. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11011. };
  11012. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11013. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11014. };
  11015. BoundingBox.prototype.intersectsPoint = function (point) {
  11016. var delta = -BABYLON.Epsilon;
  11017. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11018. return false;
  11019. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11020. return false;
  11021. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11022. return false;
  11023. return true;
  11024. };
  11025. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11026. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11027. };
  11028. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11029. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11030. return false;
  11031. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11032. return false;
  11033. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11034. return false;
  11035. return true;
  11036. };
  11037. // Statics
  11038. BoundingBox.Intersects = function (box0, box1) {
  11039. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11040. return false;
  11041. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11042. return false;
  11043. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11044. return false;
  11045. return true;
  11046. };
  11047. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11048. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11049. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11050. return (num <= (sphereRadius * sphereRadius));
  11051. };
  11052. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11053. for (var p = 0; p < 6; p++) {
  11054. for (var i = 0; i < 8; i++) {
  11055. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11056. return false;
  11057. }
  11058. }
  11059. }
  11060. return true;
  11061. };
  11062. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11063. for (var p = 0; p < 6; p++) {
  11064. var inCount = 8;
  11065. for (var i = 0; i < 8; i++) {
  11066. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11067. --inCount;
  11068. }
  11069. else {
  11070. break;
  11071. }
  11072. }
  11073. if (inCount === 0)
  11074. return false;
  11075. }
  11076. return true;
  11077. };
  11078. return BoundingBox;
  11079. }());
  11080. BABYLON.BoundingBox = BoundingBox;
  11081. })(BABYLON || (BABYLON = {}));
  11082. //# sourceMappingURL=babylon.boundingBox.js.map
  11083. var BABYLON;
  11084. (function (BABYLON) {
  11085. var computeBoxExtents = function (axis, box) {
  11086. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11087. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11088. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11089. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11090. var r = r0 + r1 + r2;
  11091. return {
  11092. min: p - r,
  11093. max: p + r
  11094. };
  11095. };
  11096. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11097. var axisOverlap = function (axis, box0, box1) {
  11098. var result0 = computeBoxExtents(axis, box0);
  11099. var result1 = computeBoxExtents(axis, box1);
  11100. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11101. };
  11102. var BoundingInfo = (function () {
  11103. function BoundingInfo(minimum, maximum) {
  11104. this.minimum = minimum;
  11105. this.maximum = maximum;
  11106. this._isLocked = false;
  11107. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11108. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11109. }
  11110. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11111. get: function () {
  11112. return this._isLocked;
  11113. },
  11114. set: function (value) {
  11115. this._isLocked = value;
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. // Methods
  11121. BoundingInfo.prototype.update = function (world) {
  11122. if (this._isLocked) {
  11123. return;
  11124. }
  11125. this.boundingBox._update(world);
  11126. this.boundingSphere._update(world);
  11127. };
  11128. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11129. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11130. return false;
  11131. return this.boundingBox.isInFrustum(frustumPlanes);
  11132. };
  11133. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11134. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11135. };
  11136. BoundingInfo.prototype._checkCollision = function (collider) {
  11137. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11138. };
  11139. BoundingInfo.prototype.intersectsPoint = function (point) {
  11140. if (!this.boundingSphere.centerWorld) {
  11141. return false;
  11142. }
  11143. if (!this.boundingSphere.intersectsPoint(point)) {
  11144. return false;
  11145. }
  11146. if (!this.boundingBox.intersectsPoint(point)) {
  11147. return false;
  11148. }
  11149. return true;
  11150. };
  11151. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11152. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11153. return false;
  11154. }
  11155. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11156. return false;
  11157. }
  11158. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11159. return false;
  11160. }
  11161. if (!precise) {
  11162. return true;
  11163. }
  11164. var box0 = this.boundingBox;
  11165. var box1 = boundingInfo.boundingBox;
  11166. if (!axisOverlap(box0.directions[0], box0, box1))
  11167. return false;
  11168. if (!axisOverlap(box0.directions[1], box0, box1))
  11169. return false;
  11170. if (!axisOverlap(box0.directions[2], box0, box1))
  11171. return false;
  11172. if (!axisOverlap(box1.directions[0], box0, box1))
  11173. return false;
  11174. if (!axisOverlap(box1.directions[1], box0, box1))
  11175. return false;
  11176. if (!axisOverlap(box1.directions[2], box0, box1))
  11177. return false;
  11178. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11179. return false;
  11180. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11181. return false;
  11182. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11183. return false;
  11184. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11185. return false;
  11186. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11187. return false;
  11188. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11189. return false;
  11190. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11191. return false;
  11192. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11193. return false;
  11194. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11195. return false;
  11196. return true;
  11197. };
  11198. return BoundingInfo;
  11199. }());
  11200. BABYLON.BoundingInfo = BoundingInfo;
  11201. })(BABYLON || (BABYLON = {}));
  11202. //# sourceMappingURL=babylon.boundingInfo.js.map
  11203. var BABYLON;
  11204. (function (BABYLON) {
  11205. var AbstractMesh = (function (_super) {
  11206. __extends(AbstractMesh, _super);
  11207. // Constructor
  11208. function AbstractMesh(name, scene) {
  11209. var _this = _super.call(this, name, scene) || this;
  11210. _this._facetNb = 0; // facet number
  11211. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11212. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11213. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11214. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11215. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11216. _this._subDiv = {
  11217. max: 1,
  11218. X: 1,
  11219. Y: 1,
  11220. Z: 1
  11221. };
  11222. // Events
  11223. /**
  11224. * An event triggered when this mesh collides with another one
  11225. * @type {BABYLON.Observable}
  11226. */
  11227. _this.onCollideObservable = new BABYLON.Observable();
  11228. /**
  11229. * An event triggered when the collision's position changes
  11230. * @type {BABYLON.Observable}
  11231. */
  11232. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11233. /**
  11234. * An event triggered after the world matrix is updated
  11235. * @type {BABYLON.Observable}
  11236. */
  11237. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11238. // Properties
  11239. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11240. _this.position = BABYLON.Vector3.Zero();
  11241. _this._rotation = BABYLON.Vector3.Zero();
  11242. _this._scaling = BABYLON.Vector3.One();
  11243. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11244. _this.visibility = 1.0;
  11245. _this.alphaIndex = Number.MAX_VALUE;
  11246. _this.infiniteDistance = false;
  11247. _this.isVisible = true;
  11248. _this.isPickable = true;
  11249. _this.showBoundingBox = false;
  11250. _this.showSubMeshesBoundingBox = false;
  11251. _this.isBlocker = false;
  11252. _this.renderingGroupId = 0;
  11253. _this._receiveShadows = false;
  11254. _this.renderOutline = false;
  11255. _this.outlineColor = BABYLON.Color3.Red();
  11256. _this.outlineWidth = 0.02;
  11257. _this.renderOverlay = false;
  11258. _this.overlayColor = BABYLON.Color3.Red();
  11259. _this.overlayAlpha = 0.5;
  11260. _this._hasVertexAlpha = false;
  11261. _this._useVertexColors = true;
  11262. _this._computeBonesUsingShaders = true;
  11263. _this._numBoneInfluencers = 4;
  11264. _this._applyFog = true;
  11265. _this.scalingDeterminant = 1;
  11266. _this.useOctreeForRenderingSelection = true;
  11267. _this.useOctreeForPicking = true;
  11268. _this.useOctreeForCollisions = true;
  11269. _this.layerMask = 0x0FFFFFFF;
  11270. /**
  11271. * True if the mesh must be rendered in any case.
  11272. */
  11273. _this.alwaysSelectAsActiveMesh = false;
  11274. // Collisions
  11275. _this._checkCollisions = false;
  11276. _this._collisionMask = -1;
  11277. _this._collisionGroup = -1;
  11278. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11279. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11280. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11281. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11282. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11283. // Edges
  11284. _this.edgesWidth = 1;
  11285. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11286. // Cache
  11287. _this._localWorld = BABYLON.Matrix.Zero();
  11288. _this._worldMatrix = BABYLON.Matrix.Zero();
  11289. _this._absolutePosition = BABYLON.Vector3.Zero();
  11290. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11291. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11292. _this._isDirty = false;
  11293. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11294. _this._isDisposed = false;
  11295. _this._renderId = 0;
  11296. _this._intersectionsInProgress = new Array();
  11297. _this._isWorldMatrixFrozen = false;
  11298. _this._unIndexed = false;
  11299. _this._lightSources = new Array();
  11300. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11301. if (collidedMesh === void 0) { collidedMesh = null; }
  11302. //TODO move this to the collision coordinator!
  11303. if (_this.getScene().workerCollisions)
  11304. newPosition.multiplyInPlace(_this._collider.radius);
  11305. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11306. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11307. _this.position.addInPlace(_this._diffPositionForCollisions);
  11308. }
  11309. if (collidedMesh) {
  11310. _this.onCollideObservable.notifyObservers(collidedMesh);
  11311. }
  11312. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11313. };
  11314. _this.getScene().addMesh(_this);
  11315. _this._resyncLightSources();
  11316. return _this;
  11317. }
  11318. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11319. get: function () {
  11320. return AbstractMesh._BILLBOARDMODE_NONE;
  11321. },
  11322. enumerable: true,
  11323. configurable: true
  11324. });
  11325. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11326. get: function () {
  11327. return AbstractMesh._BILLBOARDMODE_X;
  11328. },
  11329. enumerable: true,
  11330. configurable: true
  11331. });
  11332. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11333. get: function () {
  11334. return AbstractMesh._BILLBOARDMODE_Y;
  11335. },
  11336. enumerable: true,
  11337. configurable: true
  11338. });
  11339. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11340. get: function () {
  11341. return AbstractMesh._BILLBOARDMODE_Z;
  11342. },
  11343. enumerable: true,
  11344. configurable: true
  11345. });
  11346. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11347. get: function () {
  11348. return AbstractMesh._BILLBOARDMODE_ALL;
  11349. },
  11350. enumerable: true,
  11351. configurable: true
  11352. });
  11353. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11354. /**
  11355. * Read-only : the number of facets in the mesh
  11356. */
  11357. get: function () {
  11358. return this._facetNb;
  11359. },
  11360. enumerable: true,
  11361. configurable: true
  11362. });
  11363. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11364. /**
  11365. * The number (integer) of subdivisions per axis in the partioning space
  11366. */
  11367. get: function () {
  11368. return this._partitioningSubdivisions;
  11369. },
  11370. set: function (nb) {
  11371. this._partitioningSubdivisions = nb;
  11372. },
  11373. enumerable: true,
  11374. configurable: true
  11375. });
  11376. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11377. /**
  11378. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11379. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11380. */
  11381. get: function () {
  11382. return this._partitioningBBoxRatio;
  11383. },
  11384. set: function (ratio) {
  11385. this._partitioningBBoxRatio = ratio;
  11386. },
  11387. enumerable: true,
  11388. configurable: true
  11389. });
  11390. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11391. /**
  11392. * Read-only boolean : is the feature facetData enabled ?
  11393. */
  11394. get: function () {
  11395. return this._facetDataEnabled;
  11396. },
  11397. enumerable: true,
  11398. configurable: true
  11399. });
  11400. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11401. set: function (callback) {
  11402. if (this._onCollideObserver) {
  11403. this.onCollideObservable.remove(this._onCollideObserver);
  11404. }
  11405. this._onCollideObserver = this.onCollideObservable.add(callback);
  11406. },
  11407. enumerable: true,
  11408. configurable: true
  11409. });
  11410. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11411. set: function (callback) {
  11412. if (this._onCollisionPositionChangeObserver) {
  11413. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11414. }
  11415. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11416. },
  11417. enumerable: true,
  11418. configurable: true
  11419. });
  11420. Object.defineProperty(AbstractMesh.prototype, "material", {
  11421. get: function () {
  11422. return this._material;
  11423. },
  11424. set: function (value) {
  11425. if (this._material === value) {
  11426. return;
  11427. }
  11428. this._material = value;
  11429. if (!this.subMeshes) {
  11430. return;
  11431. }
  11432. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11433. var subMesh = _a[_i];
  11434. subMesh.setEffect(null);
  11435. }
  11436. },
  11437. enumerable: true,
  11438. configurable: true
  11439. });
  11440. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11441. get: function () {
  11442. return this._receiveShadows;
  11443. },
  11444. set: function (value) {
  11445. if (this._receiveShadows === value) {
  11446. return;
  11447. }
  11448. this._receiveShadows = value;
  11449. this._markSubMeshesAsLightDirty();
  11450. },
  11451. enumerable: true,
  11452. configurable: true
  11453. });
  11454. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11455. get: function () {
  11456. return this._hasVertexAlpha;
  11457. },
  11458. set: function (value) {
  11459. if (this._hasVertexAlpha === value) {
  11460. return;
  11461. }
  11462. this._hasVertexAlpha = value;
  11463. this._markSubMeshesAsAttributesDirty();
  11464. },
  11465. enumerable: true,
  11466. configurable: true
  11467. });
  11468. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11469. get: function () {
  11470. return this._useVertexColors;
  11471. },
  11472. set: function (value) {
  11473. if (this._useVertexColors === value) {
  11474. return;
  11475. }
  11476. this._useVertexColors = value;
  11477. this._markSubMeshesAsAttributesDirty();
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11483. get: function () {
  11484. return this._computeBonesUsingShaders;
  11485. },
  11486. set: function (value) {
  11487. if (this._computeBonesUsingShaders === value) {
  11488. return;
  11489. }
  11490. this._computeBonesUsingShaders = value;
  11491. this._markSubMeshesAsAttributesDirty();
  11492. },
  11493. enumerable: true,
  11494. configurable: true
  11495. });
  11496. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11497. get: function () {
  11498. return this._numBoneInfluencers;
  11499. },
  11500. set: function (value) {
  11501. if (this._numBoneInfluencers === value) {
  11502. return;
  11503. }
  11504. this._numBoneInfluencers = value;
  11505. this._markSubMeshesAsAttributesDirty();
  11506. },
  11507. enumerable: true,
  11508. configurable: true
  11509. });
  11510. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11511. get: function () {
  11512. return this._applyFog;
  11513. },
  11514. set: function (value) {
  11515. if (this._applyFog === value) {
  11516. return;
  11517. }
  11518. this._applyFog = value;
  11519. this._markSubMeshesAsMiscDirty();
  11520. },
  11521. enumerable: true,
  11522. configurable: true
  11523. });
  11524. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11525. get: function () {
  11526. return this._collisionMask;
  11527. },
  11528. set: function (mask) {
  11529. this._collisionMask = !isNaN(mask) ? mask : -1;
  11530. },
  11531. enumerable: true,
  11532. configurable: true
  11533. });
  11534. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11535. get: function () {
  11536. return this._collisionGroup;
  11537. },
  11538. set: function (mask) {
  11539. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11540. },
  11541. enumerable: true,
  11542. configurable: true
  11543. });
  11544. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11545. get: function () {
  11546. return null;
  11547. },
  11548. enumerable: true,
  11549. configurable: true
  11550. });
  11551. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11552. get: function () {
  11553. return this._skeleton;
  11554. },
  11555. set: function (value) {
  11556. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11557. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11558. }
  11559. if (value && value.needInitialSkinMatrix) {
  11560. value._registerMeshWithPoseMatrix(this);
  11561. }
  11562. this._skeleton = value;
  11563. if (!this._skeleton) {
  11564. this._bonesTransformMatrices = null;
  11565. }
  11566. this._markSubMeshesAsAttributesDirty();
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. /**
  11572. * Returns the string "AbstractMesh"
  11573. */
  11574. AbstractMesh.prototype.getClassName = function () {
  11575. return "AbstractMesh";
  11576. };
  11577. /**
  11578. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11579. */
  11580. AbstractMesh.prototype.toString = function (fullDetails) {
  11581. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11582. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11583. if (this._skeleton) {
  11584. ret += ", skeleton: " + this._skeleton.name;
  11585. }
  11586. if (fullDetails) {
  11587. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11588. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11589. }
  11590. return ret;
  11591. };
  11592. AbstractMesh.prototype._resyncLightSources = function () {
  11593. this._lightSources.length = 0;
  11594. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11595. var light = _a[_i];
  11596. if (!light.isEnabled()) {
  11597. continue;
  11598. }
  11599. if (light.canAffectMesh(this)) {
  11600. this._lightSources.push(light);
  11601. }
  11602. }
  11603. this._markSubMeshesAsLightDirty();
  11604. };
  11605. AbstractMesh.prototype._resyncLighSource = function (light) {
  11606. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11607. var index = this._lightSources.indexOf(light);
  11608. if (index === -1) {
  11609. if (!isIn) {
  11610. return;
  11611. }
  11612. this._lightSources.push(light);
  11613. }
  11614. else {
  11615. if (isIn) {
  11616. return;
  11617. }
  11618. this._lightSources.splice(index, 1);
  11619. }
  11620. this._markSubMeshesAsLightDirty();
  11621. };
  11622. AbstractMesh.prototype._removeLightSource = function (light) {
  11623. var index = this._lightSources.indexOf(light);
  11624. if (index === -1) {
  11625. return;
  11626. }
  11627. this._lightSources.splice(index, 1);
  11628. };
  11629. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11630. if (!this.subMeshes) {
  11631. return;
  11632. }
  11633. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11634. var subMesh = _a[_i];
  11635. if (subMesh._materialDefines) {
  11636. func(subMesh._materialDefines);
  11637. }
  11638. }
  11639. };
  11640. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11641. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11642. };
  11643. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11644. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11645. };
  11646. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11647. if (!this.subMeshes) {
  11648. return;
  11649. }
  11650. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11651. var subMesh = _a[_i];
  11652. var material = subMesh.getMaterial();
  11653. if (material) {
  11654. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11655. }
  11656. }
  11657. };
  11658. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11659. /**
  11660. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11661. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11662. * Default : (0.0, 0.0, 0.0)
  11663. */
  11664. get: function () {
  11665. return this._rotation;
  11666. },
  11667. set: function (newRotation) {
  11668. this._rotation = newRotation;
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11674. /**
  11675. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11676. * Default : (1.0, 1.0, 1.0)
  11677. */
  11678. get: function () {
  11679. return this._scaling;
  11680. },
  11681. set: function (newScaling) {
  11682. this._scaling = newScaling;
  11683. if (this.physicsImpostor) {
  11684. this.physicsImpostor.forceUpdate();
  11685. }
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11691. /**
  11692. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11693. * It's null by default.
  11694. * 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)
  11695. */
  11696. get: function () {
  11697. return this._rotationQuaternion;
  11698. },
  11699. set: function (quaternion) {
  11700. this._rotationQuaternion = quaternion;
  11701. //reset the rotation vector.
  11702. if (quaternion && this.rotation.length()) {
  11703. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11704. }
  11705. },
  11706. enumerable: true,
  11707. configurable: true
  11708. });
  11709. // Methods
  11710. /**
  11711. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11712. * Returns the AbstractMesh.
  11713. */
  11714. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11715. this._poseMatrix.copyFrom(matrix);
  11716. return this;
  11717. };
  11718. /**
  11719. * Returns the mesh Pose matrix.
  11720. * Returned object : Matrix
  11721. */
  11722. AbstractMesh.prototype.getPoseMatrix = function () {
  11723. return this._poseMatrix;
  11724. };
  11725. /**
  11726. * Disables the mesh edger rendering mode.
  11727. * Returns the AbstractMesh.
  11728. */
  11729. AbstractMesh.prototype.disableEdgesRendering = function () {
  11730. if (this._edgesRenderer !== undefined) {
  11731. this._edgesRenderer.dispose();
  11732. this._edgesRenderer = undefined;
  11733. }
  11734. return this;
  11735. };
  11736. /**
  11737. * Enables the edge rendering mode on the mesh.
  11738. * This mode makes the mesh edges visible.
  11739. * Returns the AbstractMesh.
  11740. */
  11741. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11742. if (epsilon === void 0) { epsilon = 0.95; }
  11743. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11744. this.disableEdgesRendering();
  11745. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11746. return this;
  11747. };
  11748. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11749. /**
  11750. * Returns true if the mesh is blocked. Used by the class Mesh.
  11751. * Returns the boolean `false` by default.
  11752. */
  11753. get: function () {
  11754. return false;
  11755. },
  11756. enumerable: true,
  11757. configurable: true
  11758. });
  11759. /**
  11760. * Returns the mesh itself by default, used by the class Mesh.
  11761. * Returned type : AbstractMesh
  11762. */
  11763. AbstractMesh.prototype.getLOD = function (camera) {
  11764. return this;
  11765. };
  11766. /**
  11767. * Returns 0 by default, used by the class Mesh.
  11768. * Returns an integer.
  11769. */
  11770. AbstractMesh.prototype.getTotalVertices = function () {
  11771. return 0;
  11772. };
  11773. /**
  11774. * Returns null by default, used by the class Mesh.
  11775. * Returned type : integer array
  11776. */
  11777. AbstractMesh.prototype.getIndices = function () {
  11778. return null;
  11779. };
  11780. /**
  11781. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11782. * Returned type : float array or Float32Array
  11783. */
  11784. AbstractMesh.prototype.getVerticesData = function (kind) {
  11785. return null;
  11786. };
  11787. /**
  11788. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11789. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11790. * The `data` are either a numeric array either a Float32Array.
  11791. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11792. * 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).
  11793. * Note that a new underlying VertexBuffer object is created each call.
  11794. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11795. *
  11796. * Possible `kind` values :
  11797. * - BABYLON.VertexBuffer.PositionKind
  11798. * - BABYLON.VertexBuffer.UVKind
  11799. * - BABYLON.VertexBuffer.UV2Kind
  11800. * - BABYLON.VertexBuffer.UV3Kind
  11801. * - BABYLON.VertexBuffer.UV4Kind
  11802. * - BABYLON.VertexBuffer.UV5Kind
  11803. * - BABYLON.VertexBuffer.UV6Kind
  11804. * - BABYLON.VertexBuffer.ColorKind
  11805. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11806. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11807. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11808. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11809. *
  11810. * Returns the Mesh.
  11811. */
  11812. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11813. return null;
  11814. };
  11815. /**
  11816. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11817. * If the mesh has no geometry, it is simply returned as it is.
  11818. * The `data` are either a numeric array either a Float32Array.
  11819. * No new underlying VertexBuffer object is created.
  11820. * 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.
  11821. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11822. *
  11823. * Possible `kind` values :
  11824. * - BABYLON.VertexBuffer.PositionKind
  11825. * - BABYLON.VertexBuffer.UVKind
  11826. * - BABYLON.VertexBuffer.UV2Kind
  11827. * - BABYLON.VertexBuffer.UV3Kind
  11828. * - BABYLON.VertexBuffer.UV4Kind
  11829. * - BABYLON.VertexBuffer.UV5Kind
  11830. * - BABYLON.VertexBuffer.UV6Kind
  11831. * - BABYLON.VertexBuffer.ColorKind
  11832. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11833. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11834. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11835. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11836. *
  11837. * Returns the Mesh.
  11838. */
  11839. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11840. return null;
  11841. };
  11842. /**
  11843. * Sets the mesh indices.
  11844. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11845. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11846. * This method creates a new index buffer each call.
  11847. * Returns the Mesh.
  11848. */
  11849. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11850. return null;
  11851. };
  11852. /** Returns false by default, used by the class Mesh.
  11853. * Returns a boolean
  11854. */
  11855. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11856. return false;
  11857. };
  11858. /**
  11859. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11860. * Returns a BoundingInfo
  11861. */
  11862. AbstractMesh.prototype.getBoundingInfo = function () {
  11863. if (this._masterMesh) {
  11864. return this._masterMesh.getBoundingInfo();
  11865. }
  11866. if (!this._boundingInfo) {
  11867. this._updateBoundingInfo();
  11868. }
  11869. return this._boundingInfo;
  11870. };
  11871. /**
  11872. * Sets a mesh new object BoundingInfo.
  11873. * Returns the AbstractMesh.
  11874. */
  11875. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11876. this._boundingInfo = boundingInfo;
  11877. return this;
  11878. };
  11879. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11880. get: function () {
  11881. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. AbstractMesh.prototype._preActivate = function () {
  11887. };
  11888. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11889. };
  11890. AbstractMesh.prototype._activate = function (renderId) {
  11891. this._renderId = renderId;
  11892. };
  11893. /**
  11894. * Returns the last update of the World matrix
  11895. * Returns a Matrix.
  11896. */
  11897. AbstractMesh.prototype.getWorldMatrix = function () {
  11898. if (this._masterMesh) {
  11899. return this._masterMesh.getWorldMatrix();
  11900. }
  11901. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11902. this.computeWorldMatrix();
  11903. }
  11904. return this._worldMatrix;
  11905. };
  11906. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11907. /**
  11908. * Returns directly the last state of the mesh World matrix.
  11909. * A Matrix is returned.
  11910. */
  11911. get: function () {
  11912. return this._worldMatrix;
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11918. /**
  11919. * Returns the current mesh absolute position.
  11920. * Retuns a Vector3.
  11921. */
  11922. get: function () {
  11923. return this._absolutePosition;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. /**
  11929. * Prevents the World matrix to be computed any longer.
  11930. * Returns the AbstractMesh.
  11931. */
  11932. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11933. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11934. this.computeWorldMatrix(true);
  11935. this._isWorldMatrixFrozen = true;
  11936. return this;
  11937. };
  11938. /**
  11939. * Allows back the World matrix computation.
  11940. * Returns the AbstractMesh.
  11941. */
  11942. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11943. this._isWorldMatrixFrozen = false;
  11944. this.computeWorldMatrix(true);
  11945. return this;
  11946. };
  11947. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11948. /**
  11949. * True if the World matrix has been frozen.
  11950. * Returns a boolean.
  11951. */
  11952. get: function () {
  11953. return this._isWorldMatrixFrozen;
  11954. },
  11955. enumerable: true,
  11956. configurable: true
  11957. });
  11958. /**
  11959. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11960. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11961. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11962. * The passed axis is also normalized.
  11963. * Returns the AbstractMesh.
  11964. */
  11965. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11966. axis.normalize();
  11967. if (!this.rotationQuaternion) {
  11968. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11969. this.rotation = BABYLON.Vector3.Zero();
  11970. }
  11971. var rotationQuaternion;
  11972. if (!space || space === BABYLON.Space.LOCAL) {
  11973. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11974. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11975. }
  11976. else {
  11977. if (this.parent) {
  11978. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11979. invertParentWorldMatrix.invert();
  11980. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11981. }
  11982. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11983. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11984. }
  11985. return this;
  11986. };
  11987. /**
  11988. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  11989. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11990. * The passed axis is also normalized.
  11991. * Returns the AbstractMesh.
  11992. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  11993. */
  11994. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  11995. axis.normalize();
  11996. if (!this.rotationQuaternion) {
  11997. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11998. this.rotation.copyFromFloats(0, 0, 0);
  11999. }
  12000. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12001. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12002. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12003. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12004. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12005. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12006. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12007. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12008. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  12009. return this;
  12010. };
  12011. /**
  12012. * Translates the mesh along the axis vector for the passed distance in the given space.
  12013. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12014. * Returns the AbstractMesh.
  12015. */
  12016. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12017. var displacementVector = axis.scale(distance);
  12018. if (!space || space === BABYLON.Space.LOCAL) {
  12019. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12020. this.setPositionWithLocalVector(tempV3);
  12021. }
  12022. else {
  12023. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12024. }
  12025. return this;
  12026. };
  12027. /**
  12028. * Adds a rotation step to the mesh current rotation.
  12029. * x, y, z are Euler angles expressed in radians.
  12030. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12031. * This means this rotation is made in the mesh local space only.
  12032. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12033. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12034. * ```javascript
  12035. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12036. * ```
  12037. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12038. * 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.
  12039. * Returns the AbstractMesh.
  12040. */
  12041. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12042. var rotationQuaternion;
  12043. if (this.rotationQuaternion) {
  12044. rotationQuaternion = this.rotationQuaternion;
  12045. }
  12046. else {
  12047. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12048. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12049. }
  12050. var accumulation = BABYLON.Tmp.Quaternion[0];
  12051. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12052. rotationQuaternion.multiplyInPlace(accumulation);
  12053. if (!this.rotationQuaternion) {
  12054. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12055. }
  12056. return this;
  12057. };
  12058. /**
  12059. * Retuns the mesh absolute position in the World.
  12060. * Returns a Vector3.
  12061. */
  12062. AbstractMesh.prototype.getAbsolutePosition = function () {
  12063. this.computeWorldMatrix();
  12064. return this._absolutePosition;
  12065. };
  12066. /**
  12067. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12068. * Returns the AbstractMesh.
  12069. */
  12070. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12071. if (!absolutePosition) {
  12072. return;
  12073. }
  12074. var absolutePositionX;
  12075. var absolutePositionY;
  12076. var absolutePositionZ;
  12077. if (absolutePosition.x === undefined) {
  12078. if (arguments.length < 3) {
  12079. return;
  12080. }
  12081. absolutePositionX = arguments[0];
  12082. absolutePositionY = arguments[1];
  12083. absolutePositionZ = arguments[2];
  12084. }
  12085. else {
  12086. absolutePositionX = absolutePosition.x;
  12087. absolutePositionY = absolutePosition.y;
  12088. absolutePositionZ = absolutePosition.z;
  12089. }
  12090. if (this.parent) {
  12091. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12092. invertParentWorldMatrix.invert();
  12093. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12094. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12095. }
  12096. else {
  12097. this.position.x = absolutePositionX;
  12098. this.position.y = absolutePositionY;
  12099. this.position.z = absolutePositionZ;
  12100. }
  12101. return this;
  12102. };
  12103. // ================================== Point of View Movement =================================
  12104. /**
  12105. * Perform relative position change from the point of view of behind the front of the mesh.
  12106. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12107. * Supports definition of mesh facing forward or backward.
  12108. * @param {number} amountRight
  12109. * @param {number} amountUp
  12110. * @param {number} amountForward
  12111. *
  12112. * Returns the AbstractMesh.
  12113. */
  12114. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12115. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12116. return this;
  12117. };
  12118. /**
  12119. * Calculate 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 a new Vector3.
  12127. */
  12128. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12129. var rotMatrix = new BABYLON.Matrix();
  12130. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12131. rotQuaternion.toRotationMatrix(rotMatrix);
  12132. var translationDelta = BABYLON.Vector3.Zero();
  12133. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12134. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12135. return translationDelta;
  12136. };
  12137. // ================================== Point of View Rotation =================================
  12138. /**
  12139. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12140. * Supports definition of mesh facing forward or backward.
  12141. * @param {number} flipBack
  12142. * @param {number} twirlClockwise
  12143. * @param {number} tiltRight
  12144. *
  12145. * Returns the AbstractMesh.
  12146. */
  12147. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12148. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12149. return this;
  12150. };
  12151. /**
  12152. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12153. * Supports definition of mesh facing forward or backward.
  12154. * @param {number} flipBack
  12155. * @param {number} twirlClockwise
  12156. * @param {number} tiltRight
  12157. *
  12158. * Returns a new Vector3.
  12159. */
  12160. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12161. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12162. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12163. };
  12164. /**
  12165. * Sets a new pivot matrix to the mesh.
  12166. * Returns the AbstractMesh.
  12167. */
  12168. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12169. this._pivotMatrix = matrix;
  12170. this._cache.pivotMatrixUpdated = true;
  12171. return this;
  12172. };
  12173. /**
  12174. * Returns the mesh pivot matrix.
  12175. * Default : Identity.
  12176. * A Matrix is returned.
  12177. */
  12178. AbstractMesh.prototype.getPivotMatrix = function () {
  12179. return this._pivotMatrix;
  12180. };
  12181. AbstractMesh.prototype._isSynchronized = function () {
  12182. if (this._isDirty) {
  12183. return false;
  12184. }
  12185. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12186. return false;
  12187. if (this._cache.pivotMatrixUpdated) {
  12188. return false;
  12189. }
  12190. if (this.infiniteDistance) {
  12191. return false;
  12192. }
  12193. if (!this._cache.position.equals(this.position))
  12194. return false;
  12195. if (this.rotationQuaternion) {
  12196. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12197. return false;
  12198. }
  12199. if (!this._cache.rotation.equals(this.rotation))
  12200. return false;
  12201. if (!this._cache.scaling.equals(this.scaling))
  12202. return false;
  12203. return true;
  12204. };
  12205. AbstractMesh.prototype._initCache = function () {
  12206. _super.prototype._initCache.call(this);
  12207. this._cache.localMatrixUpdated = false;
  12208. this._cache.position = BABYLON.Vector3.Zero();
  12209. this._cache.scaling = BABYLON.Vector3.Zero();
  12210. this._cache.rotation = BABYLON.Vector3.Zero();
  12211. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12212. this._cache.billboardMode = -1;
  12213. };
  12214. AbstractMesh.prototype.markAsDirty = function (property) {
  12215. if (property === "rotation") {
  12216. this.rotationQuaternion = null;
  12217. }
  12218. this._currentRenderId = Number.MAX_VALUE;
  12219. this._isDirty = true;
  12220. return this;
  12221. };
  12222. /**
  12223. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12224. * Returns the AbstractMesh.
  12225. */
  12226. AbstractMesh.prototype._updateBoundingInfo = function () {
  12227. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12228. this._boundingInfo.update(this.worldMatrixFromCache);
  12229. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12230. return this;
  12231. };
  12232. /**
  12233. * Update a mesh's children BoundingInfo objects only.
  12234. * Returns the AbstractMesh.
  12235. */
  12236. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12237. if (!this.subMeshes) {
  12238. return;
  12239. }
  12240. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12241. var subMesh = this.subMeshes[subIndex];
  12242. if (!subMesh.IsGlobal) {
  12243. subMesh.updateBoundingInfo(matrix);
  12244. }
  12245. }
  12246. return this;
  12247. };
  12248. /**
  12249. * Computes the mesh World matrix and returns it.
  12250. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12251. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12252. * If the parameter `force`is set to `true`, the actual computation is done.
  12253. * Returns the mesh World Matrix.
  12254. */
  12255. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12256. if (this._isWorldMatrixFrozen) {
  12257. return this._worldMatrix;
  12258. }
  12259. if (!force && this.isSynchronized(true)) {
  12260. this._currentRenderId = this.getScene().getRenderId();
  12261. return this._worldMatrix;
  12262. }
  12263. this._cache.position.copyFrom(this.position);
  12264. this._cache.scaling.copyFrom(this.scaling);
  12265. this._cache.pivotMatrixUpdated = false;
  12266. this._cache.billboardMode = this.billboardMode;
  12267. this._currentRenderId = this.getScene().getRenderId();
  12268. this._isDirty = false;
  12269. // Scaling
  12270. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12271. // Rotation
  12272. //rotate, if quaternion is set and rotation was used
  12273. if (this.rotationQuaternion) {
  12274. var len = this.rotation.length();
  12275. if (len) {
  12276. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12277. this.rotation.copyFromFloats(0, 0, 0);
  12278. }
  12279. }
  12280. if (this.rotationQuaternion) {
  12281. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12282. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12283. }
  12284. else {
  12285. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12286. this._cache.rotation.copyFrom(this.rotation);
  12287. }
  12288. // Translation
  12289. if (this.infiniteDistance && !this.parent) {
  12290. var camera = this.getScene().activeCamera;
  12291. if (camera) {
  12292. var cameraWorldMatrix = camera.getWorldMatrix();
  12293. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12294. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12295. }
  12296. }
  12297. else {
  12298. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12299. }
  12300. // Composing transformations
  12301. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12302. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12303. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12304. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12305. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12306. // Need to decompose each rotation here
  12307. var currentPosition = BABYLON.Tmp.Vector3[3];
  12308. if (this.parent && this.parent.getWorldMatrix) {
  12309. if (this._meshToBoneReferal) {
  12310. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12311. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12312. }
  12313. else {
  12314. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12315. }
  12316. }
  12317. else {
  12318. currentPosition.copyFrom(this.position);
  12319. }
  12320. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12321. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12322. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12323. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12324. }
  12325. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12326. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12327. }
  12328. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12329. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12330. }
  12331. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12332. }
  12333. else {
  12334. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12335. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12336. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12337. }
  12338. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12339. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12340. }
  12341. // Local world
  12342. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12343. // Parent
  12344. if (this.parent && this.parent.getWorldMatrix) {
  12345. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12346. if (this._meshToBoneReferal) {
  12347. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12348. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12349. }
  12350. else {
  12351. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12352. }
  12353. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12354. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12355. this._worldMatrix.copyFrom(this._localWorld);
  12356. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12357. }
  12358. else {
  12359. if (this._meshToBoneReferal) {
  12360. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12361. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12362. }
  12363. else {
  12364. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12365. }
  12366. }
  12367. this._markSyncedWithParent();
  12368. }
  12369. else {
  12370. this._worldMatrix.copyFrom(this._localWorld);
  12371. }
  12372. // Bounding info
  12373. this._updateBoundingInfo();
  12374. // Absolute position
  12375. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12376. // Callbacks
  12377. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12378. if (!this._poseMatrix) {
  12379. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12380. }
  12381. return this._worldMatrix;
  12382. };
  12383. /**
  12384. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12385. * @param func: callback function to add
  12386. *
  12387. * Returns the AbstractMesh.
  12388. */
  12389. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12390. this.onAfterWorldMatrixUpdateObservable.add(func);
  12391. return this;
  12392. };
  12393. /**
  12394. * Removes a registered callback function.
  12395. * Returns the AbstractMesh.
  12396. */
  12397. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12398. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12399. return this;
  12400. };
  12401. /**
  12402. * Sets the mesh position in its local space.
  12403. * Returns the AbstractMesh.
  12404. */
  12405. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12406. this.computeWorldMatrix();
  12407. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12408. return this;
  12409. };
  12410. /**
  12411. * Returns the mesh position in the local space from the current World matrix values.
  12412. * Returns a new Vector3.
  12413. */
  12414. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12415. this.computeWorldMatrix();
  12416. var invLocalWorldMatrix = this._localWorld.clone();
  12417. invLocalWorldMatrix.invert();
  12418. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12419. };
  12420. /**
  12421. * Translates the mesh along the passed Vector3 in its local space.
  12422. * Returns the AbstractMesh.
  12423. */
  12424. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12425. this.computeWorldMatrix(true);
  12426. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12427. return this;
  12428. };
  12429. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12430. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12431. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12432. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12433. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12434. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12435. /// <returns>Mesh oriented towards targetMesh</returns>
  12436. if (yawCor === void 0) { yawCor = 0; }
  12437. if (pitchCor === void 0) { pitchCor = 0; }
  12438. if (rollCor === void 0) { rollCor = 0; }
  12439. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12440. var dv = AbstractMesh._lookAtVectorCache;
  12441. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12442. targetPoint.subtractToRef(pos, dv);
  12443. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12444. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12445. var pitch = Math.atan2(dv.y, len);
  12446. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12447. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12448. return this;
  12449. };
  12450. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12451. this._meshToBoneReferal = affectedMesh;
  12452. this.parent = bone;
  12453. if (bone.getWorldMatrix().determinant() < 0) {
  12454. this.scalingDeterminant *= -1;
  12455. }
  12456. return this;
  12457. };
  12458. AbstractMesh.prototype.detachFromBone = function () {
  12459. if (this.parent.getWorldMatrix().determinant() < 0) {
  12460. this.scalingDeterminant *= -1;
  12461. }
  12462. this._meshToBoneReferal = null;
  12463. this.parent = null;
  12464. return this;
  12465. };
  12466. /**
  12467. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12468. * A mesh is in the frustum if its bounding box intersects the frustum.
  12469. * Boolean returned.
  12470. */
  12471. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12472. return this._boundingInfo.isInFrustum(frustumPlanes);
  12473. };
  12474. /**
  12475. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12476. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12477. * Boolean returned.
  12478. */
  12479. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12480. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12481. ;
  12482. };
  12483. /**
  12484. * True if the mesh intersects another mesh or a SolidParticle object.
  12485. * 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)
  12486. * Returns a boolean.
  12487. */
  12488. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12489. if (!this._boundingInfo || !mesh._boundingInfo) {
  12490. return false;
  12491. }
  12492. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12493. };
  12494. /**
  12495. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12496. * Returns a boolean.
  12497. */
  12498. AbstractMesh.prototype.intersectsPoint = function (point) {
  12499. if (!this._boundingInfo) {
  12500. return false;
  12501. }
  12502. return this._boundingInfo.intersectsPoint(point);
  12503. };
  12504. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12505. return this.physicsImpostor;
  12506. };
  12507. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12508. if (!camera) {
  12509. camera = this.getScene().activeCamera;
  12510. }
  12511. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12512. };
  12513. /**
  12514. * Returns the distance from the mesh to the active camera.
  12515. * Returns a float.
  12516. */
  12517. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12518. if (!camera) {
  12519. camera = this.getScene().activeCamera;
  12520. }
  12521. return this.absolutePosition.subtract(camera.position).length();
  12522. };
  12523. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12524. if (!this.physicsImpostor) {
  12525. return;
  12526. }
  12527. this.physicsImpostor.applyImpulse(force, contactPoint);
  12528. return this;
  12529. };
  12530. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12531. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12532. return;
  12533. }
  12534. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12535. mainPivot: pivot1,
  12536. connectedPivot: pivot2,
  12537. nativeParams: options
  12538. });
  12539. return this;
  12540. };
  12541. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12542. // Collisions
  12543. /**
  12544. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12545. * Default `false`.
  12546. */
  12547. get: function () {
  12548. return this._checkCollisions;
  12549. },
  12550. set: function (collisionEnabled) {
  12551. this._checkCollisions = collisionEnabled;
  12552. if (this.getScene().workerCollisions) {
  12553. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12554. }
  12555. },
  12556. enumerable: true,
  12557. configurable: true
  12558. });
  12559. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12560. var globalPosition = this.getAbsolutePosition();
  12561. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12562. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12563. if (!this._collider) {
  12564. this._collider = new BABYLON.Collider();
  12565. }
  12566. this._collider.radius = this.ellipsoid;
  12567. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12568. return this;
  12569. };
  12570. // Submeshes octree
  12571. /**
  12572. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12573. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12574. * Returns an Octree of submeshes.
  12575. */
  12576. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12577. if (maxCapacity === void 0) { maxCapacity = 64; }
  12578. if (maxDepth === void 0) { maxDepth = 2; }
  12579. if (!this._submeshesOctree) {
  12580. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12581. }
  12582. this.computeWorldMatrix(true);
  12583. // Update octree
  12584. var bbox = this.getBoundingInfo().boundingBox;
  12585. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12586. return this._submeshesOctree;
  12587. };
  12588. // Collisions
  12589. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12590. this._generatePointsArray();
  12591. // Transformation
  12592. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12593. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12594. subMesh._lastColliderWorldVertices = [];
  12595. subMesh._trianglePlanes = [];
  12596. var start = subMesh.verticesStart;
  12597. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12598. for (var i = start; i < end; i++) {
  12599. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12600. }
  12601. }
  12602. // Collide
  12603. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12604. if (collider.collisionFound) {
  12605. collider.collidedMesh = this;
  12606. }
  12607. return this;
  12608. };
  12609. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12610. var subMeshes;
  12611. var len;
  12612. // Octrees
  12613. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12614. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12615. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12616. len = intersections.length;
  12617. subMeshes = intersections.data;
  12618. }
  12619. else {
  12620. subMeshes = this.subMeshes;
  12621. len = subMeshes.length;
  12622. }
  12623. for (var index = 0; index < len; index++) {
  12624. var subMesh = subMeshes[index];
  12625. // Bounding test
  12626. if (len > 1 && !subMesh._checkCollision(collider))
  12627. continue;
  12628. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12629. }
  12630. return this;
  12631. };
  12632. AbstractMesh.prototype._checkCollision = function (collider) {
  12633. // Bounding box test
  12634. if (!this._boundingInfo._checkCollision(collider))
  12635. return this;
  12636. // Transformation matrix
  12637. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12638. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12639. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12640. return this;
  12641. };
  12642. // Picking
  12643. AbstractMesh.prototype._generatePointsArray = function () {
  12644. return false;
  12645. };
  12646. /**
  12647. * Checks if the passed Ray intersects with the mesh.
  12648. * Returns an object PickingInfo.
  12649. */
  12650. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12651. var pickingInfo = new BABYLON.PickingInfo();
  12652. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12653. return pickingInfo;
  12654. }
  12655. if (!this._generatePointsArray()) {
  12656. return pickingInfo;
  12657. }
  12658. var intersectInfo = null;
  12659. // Octrees
  12660. var subMeshes;
  12661. var len;
  12662. if (this._submeshesOctree && this.useOctreeForPicking) {
  12663. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12664. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12665. len = intersections.length;
  12666. subMeshes = intersections.data;
  12667. }
  12668. else {
  12669. subMeshes = this.subMeshes;
  12670. len = subMeshes.length;
  12671. }
  12672. for (var index = 0; index < len; index++) {
  12673. var subMesh = subMeshes[index];
  12674. // Bounding test
  12675. if (len > 1 && !subMesh.canIntersects(ray))
  12676. continue;
  12677. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12678. if (currentIntersectInfo) {
  12679. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12680. intersectInfo = currentIntersectInfo;
  12681. intersectInfo.subMeshId = index;
  12682. if (fastCheck) {
  12683. break;
  12684. }
  12685. }
  12686. }
  12687. }
  12688. if (intersectInfo) {
  12689. // Get picked point
  12690. var world = this.getWorldMatrix();
  12691. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12692. var direction = ray.direction.clone();
  12693. direction = direction.scale(intersectInfo.distance);
  12694. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12695. var pickedPoint = worldOrigin.add(worldDirection);
  12696. // Return result
  12697. pickingInfo.hit = true;
  12698. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12699. pickingInfo.pickedPoint = pickedPoint;
  12700. pickingInfo.pickedMesh = this;
  12701. pickingInfo.bu = intersectInfo.bu;
  12702. pickingInfo.bv = intersectInfo.bv;
  12703. pickingInfo.faceId = intersectInfo.faceId;
  12704. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12705. return pickingInfo;
  12706. }
  12707. return pickingInfo;
  12708. };
  12709. /**
  12710. * Clones the mesh, used by the class Mesh.
  12711. * Just returns `null` for an AbstractMesh.
  12712. */
  12713. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12714. return null;
  12715. };
  12716. /**
  12717. * Disposes all the mesh submeshes.
  12718. * Returns the AbstractMesh.
  12719. */
  12720. AbstractMesh.prototype.releaseSubMeshes = function () {
  12721. if (this.subMeshes) {
  12722. while (this.subMeshes.length) {
  12723. this.subMeshes[0].dispose();
  12724. }
  12725. }
  12726. else {
  12727. this.subMeshes = new Array();
  12728. }
  12729. return this;
  12730. };
  12731. /**
  12732. * Disposes the AbstractMesh.
  12733. * Some internal references are kept for further use.
  12734. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12735. * Returns nothing.
  12736. */
  12737. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12738. var _this = this;
  12739. var index;
  12740. // Action manager
  12741. if (this.actionManager) {
  12742. this.actionManager.dispose();
  12743. this.actionManager = null;
  12744. }
  12745. // Skeleton
  12746. this.skeleton = null;
  12747. // Animations
  12748. this.getScene().stopAnimation(this);
  12749. // Physics
  12750. if (this.physicsImpostor) {
  12751. this.physicsImpostor.dispose();
  12752. }
  12753. // Intersections in progress
  12754. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12755. var other = this._intersectionsInProgress[index];
  12756. var pos = other._intersectionsInProgress.indexOf(this);
  12757. other._intersectionsInProgress.splice(pos, 1);
  12758. }
  12759. this._intersectionsInProgress = [];
  12760. // Lights
  12761. var lights = this.getScene().lights;
  12762. lights.forEach(function (light) {
  12763. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12764. if (meshIndex !== -1) {
  12765. light.includedOnlyMeshes.splice(meshIndex, 1);
  12766. }
  12767. meshIndex = light.excludedMeshes.indexOf(_this);
  12768. if (meshIndex !== -1) {
  12769. light.excludedMeshes.splice(meshIndex, 1);
  12770. }
  12771. // Shadow generators
  12772. var generator = light.getShadowGenerator();
  12773. if (generator) {
  12774. var shadowMap = generator.getShadowMap();
  12775. meshIndex = shadowMap.renderList.indexOf(_this);
  12776. if (meshIndex !== -1) {
  12777. shadowMap.renderList.splice(meshIndex, 1);
  12778. }
  12779. }
  12780. });
  12781. // Edges
  12782. if (this._edgesRenderer) {
  12783. this._edgesRenderer.dispose();
  12784. this._edgesRenderer = null;
  12785. }
  12786. // SubMeshes
  12787. if (this.getClassName() !== "InstancedMesh") {
  12788. this.releaseSubMeshes();
  12789. }
  12790. // Octree
  12791. var sceneOctree = this.getScene().selectionOctree;
  12792. if (sceneOctree) {
  12793. var index = sceneOctree.dynamicContent.indexOf(this);
  12794. if (index !== -1) {
  12795. sceneOctree.dynamicContent.splice(index, 1);
  12796. }
  12797. }
  12798. // Engine
  12799. this.getScene().getEngine().wipeCaches();
  12800. // Remove from scene
  12801. this.getScene().removeMesh(this);
  12802. if (!doNotRecurse) {
  12803. // Particles
  12804. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12805. if (this.getScene().particleSystems[index].emitter === this) {
  12806. this.getScene().particleSystems[index].dispose();
  12807. index--;
  12808. }
  12809. }
  12810. // Children
  12811. var objects = this.getDescendants(true);
  12812. for (index = 0; index < objects.length; index++) {
  12813. objects[index].dispose();
  12814. }
  12815. }
  12816. else {
  12817. var childMeshes = this.getChildMeshes(true);
  12818. for (index = 0; index < childMeshes.length; index++) {
  12819. var child = childMeshes[index];
  12820. child.parent = null;
  12821. child.computeWorldMatrix(true);
  12822. }
  12823. }
  12824. // facet data
  12825. if (this._facetDataEnabled) {
  12826. this.disableFacetData();
  12827. }
  12828. this.onAfterWorldMatrixUpdateObservable.clear();
  12829. this.onCollideObservable.clear();
  12830. this.onCollisionPositionChangeObservable.clear();
  12831. this._isDisposed = true;
  12832. _super.prototype.dispose.call(this);
  12833. };
  12834. /**
  12835. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12836. * This Vector3 is expressed in the World space.
  12837. */
  12838. AbstractMesh.prototype.getDirection = function (localAxis) {
  12839. var result = BABYLON.Vector3.Zero();
  12840. this.getDirectionToRef(localAxis, result);
  12841. return result;
  12842. };
  12843. /**
  12844. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12845. * localAxis is expressed in the mesh local space.
  12846. * result is computed in the Wordl space from the mesh World matrix.
  12847. * Returns the AbstractMesh.
  12848. */
  12849. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12850. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12851. return this;
  12852. };
  12853. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12854. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12855. if (this.getScene().getRenderId() == 0) {
  12856. this.computeWorldMatrix(true);
  12857. }
  12858. var wm = this.getWorldMatrix();
  12859. if (space == BABYLON.Space.WORLD) {
  12860. var tmat = BABYLON.Tmp.Matrix[0];
  12861. wm.invertToRef(tmat);
  12862. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12863. }
  12864. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12865. this._pivotMatrix.m[12] = -point.x;
  12866. this._pivotMatrix.m[13] = -point.y;
  12867. this._pivotMatrix.m[14] = -point.z;
  12868. this._cache.pivotMatrixUpdated = true;
  12869. return this;
  12870. };
  12871. /**
  12872. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12873. */
  12874. AbstractMesh.prototype.getPivotPoint = function () {
  12875. var point = BABYLON.Vector3.Zero();
  12876. this.getPivotPointToRef(point);
  12877. return point;
  12878. };
  12879. /**
  12880. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12881. * Returns the AbstractMesh.
  12882. */
  12883. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12884. result.x = -this._pivotMatrix.m[12];
  12885. result.y = -this._pivotMatrix.m[13];
  12886. result.z = -this._pivotMatrix.m[14];
  12887. return this;
  12888. };
  12889. /**
  12890. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12891. */
  12892. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12893. var point = BABYLON.Vector3.Zero();
  12894. this.getAbsolutePivotPointToRef(point);
  12895. return point;
  12896. };
  12897. /**
  12898. * Defines the passed mesh as the parent of the current mesh.
  12899. * Returns the AbstractMesh.
  12900. */
  12901. AbstractMesh.prototype.setParent = function (mesh) {
  12902. var child = this;
  12903. var parent = mesh;
  12904. if (mesh == null) {
  12905. var rotation = BABYLON.Tmp.Quaternion[0];
  12906. var position = BABYLON.Tmp.Vector3[0];
  12907. var scale = BABYLON.Tmp.Vector3[1];
  12908. child.getWorldMatrix().decompose(scale, rotation, position);
  12909. if (child.rotationQuaternion) {
  12910. child.rotationQuaternion.copyFrom(rotation);
  12911. }
  12912. else {
  12913. rotation.toEulerAnglesToRef(child.rotation);
  12914. }
  12915. child.position.x = position.x;
  12916. child.position.y = position.y;
  12917. child.position.z = position.z;
  12918. }
  12919. else {
  12920. var rotation = BABYLON.Tmp.Quaternion[0];
  12921. var position = BABYLON.Tmp.Vector3[0];
  12922. var scale = BABYLON.Tmp.Vector3[1];
  12923. var m1 = BABYLON.Tmp.Matrix[0];
  12924. var m2 = BABYLON.Tmp.Matrix[1];
  12925. parent.getWorldMatrix().decompose(scale, rotation, position);
  12926. rotation.toRotationMatrix(m1);
  12927. m2.setTranslation(position);
  12928. m2.multiplyToRef(m1, m1);
  12929. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12930. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12931. m.decompose(scale, rotation, position);
  12932. if (child.rotationQuaternion) {
  12933. child.rotationQuaternion.copyFrom(rotation);
  12934. }
  12935. else {
  12936. rotation.toEulerAnglesToRef(child.rotation);
  12937. }
  12938. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12939. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12940. m.decompose(scale, rotation, position);
  12941. child.position.x = position.x;
  12942. child.position.y = position.y;
  12943. child.position.z = position.z;
  12944. }
  12945. child.parent = parent;
  12946. return this;
  12947. };
  12948. /**
  12949. * Adds the passed mesh as a child to the current mesh.
  12950. * Returns the AbstractMesh.
  12951. */
  12952. AbstractMesh.prototype.addChild = function (mesh) {
  12953. mesh.setParent(this);
  12954. return this;
  12955. };
  12956. /**
  12957. * Removes the passed mesh from the current mesh children list.
  12958. * Returns the AbstractMesh.
  12959. */
  12960. AbstractMesh.prototype.removeChild = function (mesh) {
  12961. mesh.setParent(null);
  12962. return this;
  12963. };
  12964. /**
  12965. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12966. * Returns the AbstractMesh.
  12967. */
  12968. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12969. result.x = this._pivotMatrix.m[12];
  12970. result.y = this._pivotMatrix.m[13];
  12971. result.z = this._pivotMatrix.m[14];
  12972. this.getPivotPointToRef(result);
  12973. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12974. return this;
  12975. };
  12976. // Facet data
  12977. /**
  12978. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12979. * Returns the AbstractMesh.
  12980. */
  12981. AbstractMesh.prototype._initFacetData = function () {
  12982. if (!this._facetNormals) {
  12983. this._facetNormals = new Array();
  12984. }
  12985. if (!this._facetPositions) {
  12986. this._facetPositions = new Array();
  12987. }
  12988. if (!this._facetPartitioning) {
  12989. this._facetPartitioning = new Array();
  12990. }
  12991. this._facetNb = this.getIndices().length / 3;
  12992. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12993. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12994. for (var f = 0; f < this._facetNb; f++) {
  12995. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12996. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12997. }
  12998. this._facetDataEnabled = true;
  12999. return this;
  13000. };
  13001. /**
  13002. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13003. * This method can be called within the render loop.
  13004. * 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.
  13005. * Returns the AbstractMesh.
  13006. */
  13007. AbstractMesh.prototype.updateFacetData = function () {
  13008. if (!this._facetDataEnabled) {
  13009. this._initFacetData();
  13010. }
  13011. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13012. var indices = this.getIndices();
  13013. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13014. var bInfo = this.getBoundingInfo();
  13015. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13016. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13017. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13018. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13019. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13020. this._subDiv.max = this._partitioningSubdivisions;
  13021. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13022. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13023. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13024. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13025. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13026. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13027. // set the parameters for ComputeNormals()
  13028. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13029. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13030. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13031. this._facetParameters.bInfo = bInfo;
  13032. this._facetParameters.bbSize = this._bbSize;
  13033. this._facetParameters.subDiv = this._subDiv;
  13034. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13035. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13036. return this;
  13037. };
  13038. /**
  13039. * Returns the facetLocalNormals array.
  13040. * The normals are expressed in the mesh local space.
  13041. */
  13042. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13043. if (!this._facetNormals) {
  13044. this.updateFacetData();
  13045. }
  13046. return this._facetNormals;
  13047. };
  13048. /**
  13049. * Returns the facetLocalPositions array.
  13050. * The facet positions are expressed in the mesh local space.
  13051. */
  13052. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13053. if (!this._facetPositions) {
  13054. this.updateFacetData();
  13055. }
  13056. return this._facetPositions;
  13057. };
  13058. /**
  13059. * Returns the facetLocalPartioning array.
  13060. */
  13061. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13062. if (!this._facetPartitioning) {
  13063. this.updateFacetData();
  13064. }
  13065. return this._facetPartitioning;
  13066. };
  13067. /**
  13068. * Returns the i-th facet position in the world system.
  13069. * This method allocates a new Vector3 per call.
  13070. */
  13071. AbstractMesh.prototype.getFacetPosition = function (i) {
  13072. var pos = BABYLON.Vector3.Zero();
  13073. this.getFacetPositionToRef(i, pos);
  13074. return pos;
  13075. };
  13076. /**
  13077. * Sets the reference Vector3 with the i-th facet position in the world system.
  13078. * Returns the AbstractMesh.
  13079. */
  13080. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13081. var localPos = (this.getFacetLocalPositions())[i];
  13082. var world = this.getWorldMatrix();
  13083. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13084. return this;
  13085. };
  13086. /**
  13087. * Returns the i-th facet normal in the world system.
  13088. * This method allocates a new Vector3 per call.
  13089. */
  13090. AbstractMesh.prototype.getFacetNormal = function (i) {
  13091. var norm = BABYLON.Vector3.Zero();
  13092. this.getFacetNormalToRef(i, norm);
  13093. return norm;
  13094. };
  13095. /**
  13096. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13097. * Returns the AbstractMesh.
  13098. */
  13099. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13100. var localNorm = (this.getFacetLocalNormals())[i];
  13101. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13102. return this;
  13103. };
  13104. /**
  13105. * 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).
  13106. */
  13107. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13108. var bInfo = this.getBoundingInfo();
  13109. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13110. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13111. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13112. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13113. return null;
  13114. }
  13115. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13116. };
  13117. /**
  13118. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13119. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13120. * 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.
  13121. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13122. * 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.
  13123. */
  13124. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13125. if (checkFace === void 0) { checkFace = false; }
  13126. if (facing === void 0) { facing = true; }
  13127. var world = this.getWorldMatrix();
  13128. var invMat = BABYLON.Tmp.Matrix[5];
  13129. world.invertToRef(invMat);
  13130. var invVect = BABYLON.Tmp.Vector3[8];
  13131. var closest = null;
  13132. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13133. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13134. if (projected) {
  13135. // tranform the local computed projected vector to world coordinates
  13136. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13137. }
  13138. return closest;
  13139. };
  13140. /**
  13141. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13142. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13143. * 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.
  13144. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13145. * 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.
  13146. */
  13147. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13148. if (checkFace === void 0) { checkFace = false; }
  13149. if (facing === void 0) { facing = true; }
  13150. var closest = null;
  13151. var tmpx = 0.0;
  13152. var tmpy = 0.0;
  13153. var tmpz = 0.0;
  13154. var d = 0.0; // tmp dot facet normal * facet position
  13155. var t0 = 0.0;
  13156. var projx = 0.0;
  13157. var projy = 0.0;
  13158. var projz = 0.0;
  13159. // Get all the facets in the same partitioning block than (x, y, z)
  13160. var facetPositions = this.getFacetLocalPositions();
  13161. var facetNormals = this.getFacetLocalNormals();
  13162. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13163. if (!facetsInBlock) {
  13164. return null;
  13165. }
  13166. // Get the closest facet to (x, y, z)
  13167. var shortest = Number.MAX_VALUE; // init distance vars
  13168. var tmpDistance = shortest;
  13169. var fib; // current facet in the block
  13170. var norm; // current facet normal
  13171. var p0; // current facet barycenter position
  13172. // loop on all the facets in the current partitioning block
  13173. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13174. fib = facetsInBlock[idx];
  13175. norm = facetNormals[fib];
  13176. p0 = facetPositions[fib];
  13177. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13178. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13179. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13180. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13181. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13182. projx = x + norm.x * t0;
  13183. projy = y + norm.y * t0;
  13184. projz = z + norm.z * t0;
  13185. tmpx = projx - x;
  13186. tmpy = projy - y;
  13187. tmpz = projz - z;
  13188. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13189. if (tmpDistance < shortest) {
  13190. shortest = tmpDistance;
  13191. closest = fib;
  13192. if (projected) {
  13193. projected.x = projx;
  13194. projected.y = projy;
  13195. projected.z = projz;
  13196. }
  13197. }
  13198. }
  13199. }
  13200. return closest;
  13201. };
  13202. /**
  13203. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13204. */
  13205. AbstractMesh.prototype.getFacetDataParameters = function () {
  13206. return this._facetParameters;
  13207. };
  13208. /**
  13209. * Disables the feature FacetData and frees the related memory.
  13210. * Returns the AbstractMesh.
  13211. */
  13212. AbstractMesh.prototype.disableFacetData = function () {
  13213. if (this._facetDataEnabled) {
  13214. this._facetDataEnabled = false;
  13215. this._facetPositions = null;
  13216. this._facetNormals = null;
  13217. this._facetPartitioning = null;
  13218. this._facetParameters = null;
  13219. }
  13220. return this;
  13221. };
  13222. /**
  13223. * Creates new normals data for the mesh.
  13224. * @param updatable.
  13225. */
  13226. AbstractMesh.prototype.createNormals = function (updatable) {
  13227. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13228. var indices = this.getIndices();
  13229. var normals;
  13230. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13231. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13232. }
  13233. else {
  13234. normals = [];
  13235. }
  13236. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13237. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13238. };
  13239. return AbstractMesh;
  13240. }(BABYLON.Node));
  13241. // Statics
  13242. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13243. AbstractMesh._BILLBOARDMODE_X = 1;
  13244. AbstractMesh._BILLBOARDMODE_Y = 2;
  13245. AbstractMesh._BILLBOARDMODE_Z = 4;
  13246. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13247. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13248. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13249. BABYLON.AbstractMesh = AbstractMesh;
  13250. })(BABYLON || (BABYLON = {}));
  13251. //# sourceMappingURL=babylon.abstractMesh.js.map
  13252. var BABYLON;
  13253. (function (BABYLON) {
  13254. var Light = (function (_super) {
  13255. __extends(Light, _super);
  13256. /**
  13257. * Creates a Light object in the scene.
  13258. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13259. */
  13260. function Light(name, scene) {
  13261. var _this = _super.call(this, name, scene) || this;
  13262. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13263. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13264. _this.intensity = 1.0;
  13265. _this.range = Number.MAX_VALUE;
  13266. /**
  13267. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13268. * of light.
  13269. */
  13270. _this._photometricScale = 1.0;
  13271. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13272. _this._radius = 0.00001;
  13273. _this.renderPriority = 0;
  13274. /**
  13275. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13276. * the current shadow generator.
  13277. */
  13278. _this.shadowEnabled = true;
  13279. _this._excludeWithLayerMask = 0;
  13280. _this._includeOnlyWithLayerMask = 0;
  13281. _this._lightmapMode = 0;
  13282. _this._excludedMeshesIds = new Array();
  13283. _this._includedOnlyMeshesIds = new Array();
  13284. _this.getScene().addLight(_this);
  13285. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13286. _this._buildUniformLayout();
  13287. _this.includedOnlyMeshes = new Array();
  13288. _this.excludedMeshes = new Array();
  13289. _this._resyncMeshes();
  13290. return _this;
  13291. }
  13292. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13293. /**
  13294. * If every light affecting the material is in this lightmapMode,
  13295. * material.lightmapTexture adds or multiplies
  13296. * (depends on material.useLightmapAsShadowmap)
  13297. * after every other light calculations.
  13298. */
  13299. get: function () {
  13300. return Light._LIGHTMAP_DEFAULT;
  13301. },
  13302. enumerable: true,
  13303. configurable: true
  13304. });
  13305. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13306. /**
  13307. * material.lightmapTexture as only diffuse lighting from this light
  13308. * adds pnly specular lighting from this light
  13309. * adds dynamic shadows
  13310. */
  13311. get: function () {
  13312. return Light._LIGHTMAP_SPECULAR;
  13313. },
  13314. enumerable: true,
  13315. configurable: true
  13316. });
  13317. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13318. /**
  13319. * material.lightmapTexture as only lighting
  13320. * no light calculation from this light
  13321. * only adds dynamic shadows from this light
  13322. */
  13323. get: function () {
  13324. return Light._LIGHTMAP_SHADOWSONLY;
  13325. },
  13326. enumerable: true,
  13327. configurable: true
  13328. });
  13329. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13330. /**
  13331. * Each light type uses the default quantity according to its type:
  13332. * point/spot lights use luminous intensity
  13333. * directional lights use illuminance
  13334. */
  13335. get: function () {
  13336. return Light._INTENSITYMODE_AUTOMATIC;
  13337. },
  13338. enumerable: true,
  13339. configurable: true
  13340. });
  13341. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13342. /**
  13343. * lumen (lm)
  13344. */
  13345. get: function () {
  13346. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13347. },
  13348. enumerable: true,
  13349. configurable: true
  13350. });
  13351. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13352. /**
  13353. * candela (lm/sr)
  13354. */
  13355. get: function () {
  13356. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13357. },
  13358. enumerable: true,
  13359. configurable: true
  13360. });
  13361. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13362. /**
  13363. * lux (lm/m^2)
  13364. */
  13365. get: function () {
  13366. return Light._INTENSITYMODE_ILLUMINANCE;
  13367. },
  13368. enumerable: true,
  13369. configurable: true
  13370. });
  13371. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13372. /**
  13373. * nit (cd/m^2)
  13374. */
  13375. get: function () {
  13376. return Light._INTENSITYMODE_LUMINANCE;
  13377. },
  13378. enumerable: true,
  13379. configurable: true
  13380. });
  13381. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13382. /**
  13383. * Light type const id of the point light.
  13384. */
  13385. get: function () {
  13386. return Light._LIGHTTYPEID_POINTLIGHT;
  13387. },
  13388. enumerable: true,
  13389. configurable: true
  13390. });
  13391. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13392. /**
  13393. * Light type const id of the directional light.
  13394. */
  13395. get: function () {
  13396. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13397. },
  13398. enumerable: true,
  13399. configurable: true
  13400. });
  13401. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13402. /**
  13403. * Light type const id of the spot light.
  13404. */
  13405. get: function () {
  13406. return Light._LIGHTTYPEID_SPOTLIGHT;
  13407. },
  13408. enumerable: true,
  13409. configurable: true
  13410. });
  13411. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13412. /**
  13413. * Light type const id of the hemispheric light.
  13414. */
  13415. get: function () {
  13416. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13417. },
  13418. enumerable: true,
  13419. configurable: true
  13420. });
  13421. Object.defineProperty(Light.prototype, "intensityMode", {
  13422. /**
  13423. * Gets the photometric scale used to interpret the intensity.
  13424. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13425. */
  13426. get: function () {
  13427. return this._intensityMode;
  13428. },
  13429. /**
  13430. * Sets the photometric scale used to interpret the intensity.
  13431. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13432. */
  13433. set: function (value) {
  13434. this._intensityMode = value;
  13435. this._computePhotometricScale();
  13436. },
  13437. enumerable: true,
  13438. configurable: true
  13439. });
  13440. ;
  13441. ;
  13442. Object.defineProperty(Light.prototype, "radius", {
  13443. /**
  13444. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13445. */
  13446. get: function () {
  13447. return this._radius;
  13448. },
  13449. /**
  13450. * sets the light radius used by PBR Materials to simulate soft area lights.
  13451. */
  13452. set: function (value) {
  13453. this._radius = value;
  13454. this._computePhotometricScale();
  13455. },
  13456. enumerable: true,
  13457. configurable: true
  13458. });
  13459. ;
  13460. ;
  13461. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13462. get: function () {
  13463. return this._includedOnlyMeshes;
  13464. },
  13465. set: function (value) {
  13466. this._includedOnlyMeshes = value;
  13467. this._hookArrayForIncludedOnly(value);
  13468. },
  13469. enumerable: true,
  13470. configurable: true
  13471. });
  13472. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13473. get: function () {
  13474. return this._excludedMeshes;
  13475. },
  13476. set: function (value) {
  13477. this._excludedMeshes = value;
  13478. this._hookArrayForExcluded(value);
  13479. },
  13480. enumerable: true,
  13481. configurable: true
  13482. });
  13483. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13484. get: function () {
  13485. return this._excludeWithLayerMask;
  13486. },
  13487. set: function (value) {
  13488. this._excludeWithLayerMask = value;
  13489. this._resyncMeshes();
  13490. },
  13491. enumerable: true,
  13492. configurable: true
  13493. });
  13494. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13495. get: function () {
  13496. return this._includeOnlyWithLayerMask;
  13497. },
  13498. set: function (value) {
  13499. this._includeOnlyWithLayerMask = value;
  13500. this._resyncMeshes();
  13501. },
  13502. enumerable: true,
  13503. configurable: true
  13504. });
  13505. Object.defineProperty(Light.prototype, "lightmapMode", {
  13506. get: function () {
  13507. return this._lightmapMode;
  13508. },
  13509. set: function (value) {
  13510. if (this._lightmapMode === value) {
  13511. return;
  13512. }
  13513. this._lightmapMode = value;
  13514. this._markMeshesAsLightDirty();
  13515. },
  13516. enumerable: true,
  13517. configurable: true
  13518. });
  13519. Light.prototype._buildUniformLayout = function () {
  13520. // Overridden
  13521. };
  13522. /**
  13523. * Returns the string "Light".
  13524. */
  13525. Light.prototype.getClassName = function () {
  13526. return "Light";
  13527. };
  13528. /**
  13529. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13530. */
  13531. Light.prototype.toString = function (fullDetails) {
  13532. var ret = "Name: " + this.name;
  13533. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13534. if (this.animations) {
  13535. for (var i = 0; i < this.animations.length; i++) {
  13536. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13537. }
  13538. }
  13539. if (fullDetails) {
  13540. }
  13541. return ret;
  13542. };
  13543. /**
  13544. * Set the enabled state of this node.
  13545. * @param {boolean} value - the new enabled state
  13546. * @see isEnabled
  13547. */
  13548. Light.prototype.setEnabled = function (value) {
  13549. _super.prototype.setEnabled.call(this, value);
  13550. this._resyncMeshes();
  13551. };
  13552. /**
  13553. * Returns the Light associated shadow generator.
  13554. */
  13555. Light.prototype.getShadowGenerator = function () {
  13556. return this._shadowGenerator;
  13557. };
  13558. /**
  13559. * Returns a Vector3, the absolute light position in the World.
  13560. */
  13561. Light.prototype.getAbsolutePosition = function () {
  13562. return BABYLON.Vector3.Zero();
  13563. };
  13564. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13565. };
  13566. Light.prototype._getWorldMatrix = function () {
  13567. return BABYLON.Matrix.Identity();
  13568. };
  13569. /**
  13570. * Boolean : True if the light will affect the passed mesh.
  13571. */
  13572. Light.prototype.canAffectMesh = function (mesh) {
  13573. if (!mesh) {
  13574. return true;
  13575. }
  13576. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13577. return false;
  13578. }
  13579. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13580. return false;
  13581. }
  13582. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13583. return false;
  13584. }
  13585. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13586. return false;
  13587. }
  13588. return true;
  13589. };
  13590. /**
  13591. * Returns the light World matrix.
  13592. */
  13593. Light.prototype.getWorldMatrix = function () {
  13594. this._currentRenderId = this.getScene().getRenderId();
  13595. var worldMatrix = this._getWorldMatrix();
  13596. if (this.parent && this.parent.getWorldMatrix) {
  13597. if (!this._parentedWorldMatrix) {
  13598. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13599. }
  13600. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13601. this._markSyncedWithParent();
  13602. return this._parentedWorldMatrix;
  13603. }
  13604. return worldMatrix;
  13605. };
  13606. /**
  13607. * Sort function to order lights for rendering.
  13608. * @param a First Light object to compare to second.
  13609. * @param b Second Light object to compare first.
  13610. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13611. */
  13612. Light.compareLightsPriority = function (a, b) {
  13613. //shadow-casting lights have priority over non-shadow-casting lights
  13614. //the renderPrioirty is a secondary sort criterion
  13615. if (a.shadowEnabled !== b.shadowEnabled) {
  13616. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13617. }
  13618. return b.renderPriority - a.renderPriority;
  13619. };
  13620. /**
  13621. * Disposes the light.
  13622. */
  13623. Light.prototype.dispose = function () {
  13624. if (this._shadowGenerator) {
  13625. this._shadowGenerator.dispose();
  13626. this._shadowGenerator = null;
  13627. }
  13628. // Animations
  13629. this.getScene().stopAnimation(this);
  13630. // Remove from meshes
  13631. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13632. var mesh = _a[_i];
  13633. mesh._removeLightSource(this);
  13634. }
  13635. this._uniformBuffer.dispose();
  13636. // Remove from scene
  13637. this.getScene().removeLight(this);
  13638. _super.prototype.dispose.call(this);
  13639. };
  13640. /**
  13641. * Returns the light type ID (integer).
  13642. */
  13643. Light.prototype.getTypeID = function () {
  13644. return 0;
  13645. };
  13646. /**
  13647. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13648. */
  13649. Light.prototype.getScaledIntensity = function () {
  13650. return this._photometricScale * this.intensity;
  13651. };
  13652. /**
  13653. * Returns a new Light object, named "name", from the current one.
  13654. */
  13655. Light.prototype.clone = function (name) {
  13656. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13657. };
  13658. /**
  13659. * Serializes the current light into a Serialization object.
  13660. * Returns the serialized object.
  13661. */
  13662. Light.prototype.serialize = function () {
  13663. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13664. // Type
  13665. serializationObject.type = this.getTypeID();
  13666. // Parent
  13667. if (this.parent) {
  13668. serializationObject.parentId = this.parent.id;
  13669. }
  13670. // Inclusion / exclusions
  13671. if (this.excludedMeshes.length > 0) {
  13672. serializationObject.excludedMeshesIds = [];
  13673. this.excludedMeshes.forEach(function (mesh) {
  13674. serializationObject.excludedMeshesIds.push(mesh.id);
  13675. });
  13676. }
  13677. if (this.includedOnlyMeshes.length > 0) {
  13678. serializationObject.includedOnlyMeshesIds = [];
  13679. this.includedOnlyMeshes.forEach(function (mesh) {
  13680. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13681. });
  13682. }
  13683. // Animations
  13684. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13685. serializationObject.ranges = this.serializeAnimationRanges();
  13686. return serializationObject;
  13687. };
  13688. /**
  13689. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13690. * This new light is named "name" and added to the passed scene.
  13691. */
  13692. Light.GetConstructorFromName = function (type, name, scene) {
  13693. switch (type) {
  13694. case 0:
  13695. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13696. case 1:
  13697. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13698. case 2:
  13699. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13700. case 3:
  13701. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13702. }
  13703. };
  13704. /**
  13705. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13706. */
  13707. Light.Parse = function (parsedLight, scene) {
  13708. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13709. // Inclusion / exclusions
  13710. if (parsedLight.excludedMeshesIds) {
  13711. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13712. }
  13713. if (parsedLight.includedOnlyMeshesIds) {
  13714. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13715. }
  13716. // Parent
  13717. if (parsedLight.parentId) {
  13718. light._waitingParentId = parsedLight.parentId;
  13719. }
  13720. // Animations
  13721. if (parsedLight.animations) {
  13722. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13723. var parsedAnimation = parsedLight.animations[animationIndex];
  13724. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13725. }
  13726. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13727. }
  13728. if (parsedLight.autoAnimate) {
  13729. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13730. }
  13731. return light;
  13732. };
  13733. Light.prototype._hookArrayForExcluded = function (array) {
  13734. var _this = this;
  13735. var oldPush = array.push;
  13736. array.push = function () {
  13737. var items = [];
  13738. for (var _i = 0; _i < arguments.length; _i++) {
  13739. items[_i] = arguments[_i];
  13740. }
  13741. var result = oldPush.apply(array, items);
  13742. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13743. var item = items_1[_a];
  13744. item._resyncLighSource(_this);
  13745. }
  13746. return result;
  13747. };
  13748. var oldSplice = array.splice;
  13749. array.splice = function (index, deleteCount) {
  13750. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13751. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13752. var item = deleted_1[_i];
  13753. item._resyncLighSource(_this);
  13754. }
  13755. return deleted;
  13756. };
  13757. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13758. var item = array_1[_i];
  13759. item._resyncLighSource(this);
  13760. }
  13761. };
  13762. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13763. var _this = this;
  13764. var oldPush = array.push;
  13765. array.push = function () {
  13766. var items = [];
  13767. for (var _i = 0; _i < arguments.length; _i++) {
  13768. items[_i] = arguments[_i];
  13769. }
  13770. var result = oldPush.apply(array, items);
  13771. _this._resyncMeshes();
  13772. return result;
  13773. };
  13774. var oldSplice = array.splice;
  13775. array.splice = function (index, deleteCount) {
  13776. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13777. _this._resyncMeshes();
  13778. return deleted;
  13779. };
  13780. this._resyncMeshes();
  13781. };
  13782. Light.prototype._resyncMeshes = function () {
  13783. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13784. var mesh = _a[_i];
  13785. mesh._resyncLighSource(this);
  13786. }
  13787. };
  13788. Light.prototype._markMeshesAsLightDirty = function () {
  13789. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13790. var mesh = _a[_i];
  13791. if (mesh._lightSources.indexOf(this) !== -1) {
  13792. mesh._markSubMeshesAsLightDirty();
  13793. }
  13794. }
  13795. };
  13796. /**
  13797. * Recomputes the cached photometric scale if needed.
  13798. */
  13799. Light.prototype._computePhotometricScale = function () {
  13800. this._photometricScale = this._getPhotometricScale();
  13801. this.getScene().resetCachedMaterial();
  13802. };
  13803. /**
  13804. * Returns the Photometric Scale according to the light type and intensity mode.
  13805. */
  13806. Light.prototype._getPhotometricScale = function () {
  13807. var photometricScale = 0.0;
  13808. var lightTypeID = this.getTypeID();
  13809. //get photometric mode
  13810. var photometricMode = this.intensityMode;
  13811. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13812. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13813. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13814. }
  13815. else {
  13816. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13817. }
  13818. }
  13819. //compute photometric scale
  13820. switch (lightTypeID) {
  13821. case Light.LIGHTTYPEID_POINTLIGHT:
  13822. case Light.LIGHTTYPEID_SPOTLIGHT:
  13823. switch (photometricMode) {
  13824. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13825. photometricScale = 1.0 / (4.0 * Math.PI);
  13826. break;
  13827. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13828. photometricScale = 1.0;
  13829. break;
  13830. case Light.INTENSITYMODE_LUMINANCE:
  13831. photometricScale = this.radius * this.radius;
  13832. break;
  13833. }
  13834. break;
  13835. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13836. switch (photometricMode) {
  13837. case Light.INTENSITYMODE_ILLUMINANCE:
  13838. photometricScale = 1.0;
  13839. break;
  13840. case Light.INTENSITYMODE_LUMINANCE:
  13841. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13842. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13843. var apexAngleRadians = this.radius;
  13844. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13845. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13846. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13847. photometricScale = solidAngle;
  13848. break;
  13849. }
  13850. break;
  13851. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13852. // No fall off in hemisperic light.
  13853. photometricScale = 1.0;
  13854. break;
  13855. }
  13856. return photometricScale;
  13857. };
  13858. Light.prototype._reorderLightsInScene = function () {
  13859. var scene = this.getScene();
  13860. if (this.renderPriority != 0) {
  13861. scene.requireLightSorting = true;
  13862. }
  13863. this.getScene().sortLightsByPriority();
  13864. };
  13865. return Light;
  13866. }(BABYLON.Node));
  13867. //lightmapMode Consts
  13868. Light._LIGHTMAP_DEFAULT = 0;
  13869. Light._LIGHTMAP_SPECULAR = 1;
  13870. Light._LIGHTMAP_SHADOWSONLY = 2;
  13871. // Intensity Mode Consts
  13872. Light._INTENSITYMODE_AUTOMATIC = 0;
  13873. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13874. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13875. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13876. Light._INTENSITYMODE_LUMINANCE = 4;
  13877. // Light types ids const.
  13878. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13879. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13880. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13881. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13882. __decorate([
  13883. BABYLON.serializeAsColor3()
  13884. ], Light.prototype, "diffuse", void 0);
  13885. __decorate([
  13886. BABYLON.serializeAsColor3()
  13887. ], Light.prototype, "specular", void 0);
  13888. __decorate([
  13889. BABYLON.serialize()
  13890. ], Light.prototype, "intensity", void 0);
  13891. __decorate([
  13892. BABYLON.serialize()
  13893. ], Light.prototype, "range", void 0);
  13894. __decorate([
  13895. BABYLON.serialize()
  13896. ], Light.prototype, "intensityMode", null);
  13897. __decorate([
  13898. BABYLON.serialize()
  13899. ], Light.prototype, "radius", null);
  13900. __decorate([
  13901. BABYLON.serialize()
  13902. ], Light.prototype, "_renderPriority", void 0);
  13903. __decorate([
  13904. BABYLON.expandToProperty("_reorderLightsInScene")
  13905. ], Light.prototype, "renderPriority", void 0);
  13906. __decorate([
  13907. BABYLON.serialize()
  13908. ], Light.prototype, "shadowEnabled", void 0);
  13909. __decorate([
  13910. BABYLON.serialize("excludeWithLayerMask")
  13911. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13912. __decorate([
  13913. BABYLON.serialize("includeOnlyWithLayerMask")
  13914. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13915. __decorate([
  13916. BABYLON.serialize("lightmapMode")
  13917. ], Light.prototype, "_lightmapMode", void 0);
  13918. BABYLON.Light = Light;
  13919. })(BABYLON || (BABYLON = {}));
  13920. //# sourceMappingURL=babylon.light.js.map
  13921. var BABYLON;
  13922. (function (BABYLON) {
  13923. var Camera = (function (_super) {
  13924. __extends(Camera, _super);
  13925. function Camera(name, position, scene) {
  13926. var _this = _super.call(this, name, scene) || this;
  13927. _this.upVector = BABYLON.Vector3.Up();
  13928. _this.orthoLeft = null;
  13929. _this.orthoRight = null;
  13930. _this.orthoBottom = null;
  13931. _this.orthoTop = null;
  13932. _this.fov = 0.8;
  13933. _this.minZ = 1.0;
  13934. _this.maxZ = 10000.0;
  13935. _this.inertia = 0.9;
  13936. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13937. _this.isIntermediate = false;
  13938. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13939. _this.layerMask = 0x0FFFFFFF;
  13940. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13941. // Camera rig members
  13942. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13943. _this._rigCameras = new Array();
  13944. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13945. _this.customRenderTargets = new Array();
  13946. // Cache
  13947. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13948. _this._projectionMatrix = new BABYLON.Matrix();
  13949. _this._doNotComputeProjectionMatrix = false;
  13950. _this._postProcesses = new Array();
  13951. _this._transformMatrix = BABYLON.Matrix.Zero();
  13952. _this._activeMeshes = new BABYLON.SmartArray(256);
  13953. _this._globalPosition = BABYLON.Vector3.Zero();
  13954. _this._refreshFrustumPlanes = true;
  13955. _this.getScene().addCamera(_this);
  13956. if (!_this.getScene().activeCamera) {
  13957. _this.getScene().activeCamera = _this;
  13958. }
  13959. _this.position = position;
  13960. return _this;
  13961. }
  13962. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13963. get: function () {
  13964. return Camera._PERSPECTIVE_CAMERA;
  13965. },
  13966. enumerable: true,
  13967. configurable: true
  13968. });
  13969. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13970. get: function () {
  13971. return Camera._ORTHOGRAPHIC_CAMERA;
  13972. },
  13973. enumerable: true,
  13974. configurable: true
  13975. });
  13976. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13977. get: function () {
  13978. return Camera._FOVMODE_VERTICAL_FIXED;
  13979. },
  13980. enumerable: true,
  13981. configurable: true
  13982. });
  13983. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13984. get: function () {
  13985. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13986. },
  13987. enumerable: true,
  13988. configurable: true
  13989. });
  13990. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13991. get: function () {
  13992. return Camera._RIG_MODE_NONE;
  13993. },
  13994. enumerable: true,
  13995. configurable: true
  13996. });
  13997. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13998. get: function () {
  13999. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14000. },
  14001. enumerable: true,
  14002. configurable: true
  14003. });
  14004. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14005. get: function () {
  14006. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14007. },
  14008. enumerable: true,
  14009. configurable: true
  14010. });
  14011. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14012. get: function () {
  14013. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14014. },
  14015. enumerable: true,
  14016. configurable: true
  14017. });
  14018. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14019. get: function () {
  14020. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14021. },
  14022. enumerable: true,
  14023. configurable: true
  14024. });
  14025. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14026. get: function () {
  14027. return Camera._RIG_MODE_VR;
  14028. },
  14029. enumerable: true,
  14030. configurable: true
  14031. });
  14032. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14033. get: function () {
  14034. return Camera._RIG_MODE_WEBVR;
  14035. },
  14036. enumerable: true,
  14037. configurable: true
  14038. });
  14039. Camera.prototype.getClassName = function () {
  14040. return "Camera";
  14041. };
  14042. /**
  14043. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14044. */
  14045. Camera.prototype.toString = function (fullDetails) {
  14046. var ret = "Name: " + this.name;
  14047. ret += ", type: " + this.getClassName();
  14048. if (this.animations) {
  14049. for (var i = 0; i < this.animations.length; i++) {
  14050. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14051. }
  14052. }
  14053. if (fullDetails) {
  14054. }
  14055. return ret;
  14056. };
  14057. Object.defineProperty(Camera.prototype, "globalPosition", {
  14058. get: function () {
  14059. return this._globalPosition;
  14060. },
  14061. enumerable: true,
  14062. configurable: true
  14063. });
  14064. Camera.prototype.getActiveMeshes = function () {
  14065. return this._activeMeshes;
  14066. };
  14067. Camera.prototype.isActiveMesh = function (mesh) {
  14068. return (this._activeMeshes.indexOf(mesh) !== -1);
  14069. };
  14070. //Cache
  14071. Camera.prototype._initCache = function () {
  14072. _super.prototype._initCache.call(this);
  14073. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14074. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14075. this._cache.mode = undefined;
  14076. this._cache.minZ = undefined;
  14077. this._cache.maxZ = undefined;
  14078. this._cache.fov = undefined;
  14079. this._cache.fovMode = undefined;
  14080. this._cache.aspectRatio = undefined;
  14081. this._cache.orthoLeft = undefined;
  14082. this._cache.orthoRight = undefined;
  14083. this._cache.orthoBottom = undefined;
  14084. this._cache.orthoTop = undefined;
  14085. this._cache.renderWidth = undefined;
  14086. this._cache.renderHeight = undefined;
  14087. };
  14088. Camera.prototype._updateCache = function (ignoreParentClass) {
  14089. if (!ignoreParentClass) {
  14090. _super.prototype._updateCache.call(this);
  14091. }
  14092. var engine = this.getEngine();
  14093. this._cache.position.copyFrom(this.position);
  14094. this._cache.upVector.copyFrom(this.upVector);
  14095. this._cache.mode = this.mode;
  14096. this._cache.minZ = this.minZ;
  14097. this._cache.maxZ = this.maxZ;
  14098. this._cache.fov = this.fov;
  14099. this._cache.fovMode = this.fovMode;
  14100. this._cache.aspectRatio = engine.getAspectRatio(this);
  14101. this._cache.orthoLeft = this.orthoLeft;
  14102. this._cache.orthoRight = this.orthoRight;
  14103. this._cache.orthoBottom = this.orthoBottom;
  14104. this._cache.orthoTop = this.orthoTop;
  14105. this._cache.renderWidth = engine.getRenderWidth();
  14106. this._cache.renderHeight = engine.getRenderHeight();
  14107. };
  14108. Camera.prototype._updateFromScene = function () {
  14109. this.updateCache();
  14110. this.update();
  14111. };
  14112. // Synchronized
  14113. Camera.prototype._isSynchronized = function () {
  14114. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14115. };
  14116. Camera.prototype._isSynchronizedViewMatrix = function () {
  14117. if (!_super.prototype._isSynchronized.call(this))
  14118. return false;
  14119. return this._cache.position.equals(this.position)
  14120. && this._cache.upVector.equals(this.upVector)
  14121. && this.isSynchronizedWithParent();
  14122. };
  14123. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14124. var check = this._cache.mode === this.mode
  14125. && this._cache.minZ === this.minZ
  14126. && this._cache.maxZ === this.maxZ;
  14127. if (!check) {
  14128. return false;
  14129. }
  14130. var engine = this.getEngine();
  14131. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14132. check = this._cache.fov === this.fov
  14133. && this._cache.fovMode === this.fovMode
  14134. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14135. }
  14136. else {
  14137. check = this._cache.orthoLeft === this.orthoLeft
  14138. && this._cache.orthoRight === this.orthoRight
  14139. && this._cache.orthoBottom === this.orthoBottom
  14140. && this._cache.orthoTop === this.orthoTop
  14141. && this._cache.renderWidth === engine.getRenderWidth()
  14142. && this._cache.renderHeight === engine.getRenderHeight();
  14143. }
  14144. return check;
  14145. };
  14146. // Controls
  14147. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14148. };
  14149. Camera.prototype.detachControl = function (element) {
  14150. };
  14151. Camera.prototype.update = function () {
  14152. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14153. this._updateRigCameras();
  14154. }
  14155. this._checkInputs();
  14156. };
  14157. Camera.prototype._checkInputs = function () {
  14158. };
  14159. Object.defineProperty(Camera.prototype, "rigCameras", {
  14160. get: function () {
  14161. return this._rigCameras;
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14167. get: function () {
  14168. return this._rigPostProcess;
  14169. },
  14170. enumerable: true,
  14171. configurable: true
  14172. });
  14173. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14174. // invalidate framebuffer
  14175. if (this._postProcesses.length > 0) {
  14176. this._postProcesses[0].markTextureDirty();
  14177. }
  14178. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14179. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14180. var cam = this._rigCameras[i];
  14181. var rigPostProcess = cam._rigPostProcess;
  14182. // for VR rig, there does not have to be a post process
  14183. if (rigPostProcess) {
  14184. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14185. if (isPass) {
  14186. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14187. cam.isIntermediate = this._postProcesses.length === 0;
  14188. }
  14189. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14190. rigPostProcess.markTextureDirty();
  14191. }
  14192. else {
  14193. cam._postProcesses = this._postProcesses.slice(0);
  14194. }
  14195. }
  14196. };
  14197. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14198. if (insertAt === void 0) { insertAt = null; }
  14199. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14200. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14201. return 0;
  14202. }
  14203. if (insertAt == null || insertAt < 0) {
  14204. this._postProcesses.push(postProcess);
  14205. }
  14206. else {
  14207. this._postProcesses.splice(insertAt, 0, postProcess);
  14208. }
  14209. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14210. return this._postProcesses.indexOf(postProcess);
  14211. };
  14212. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14213. if (atIndices === void 0) { atIndices = null; }
  14214. var result = [];
  14215. var i;
  14216. var index;
  14217. if (!atIndices) {
  14218. var idx = this._postProcesses.indexOf(postProcess);
  14219. if (idx !== -1) {
  14220. this._postProcesses.splice(idx, 1);
  14221. }
  14222. }
  14223. else {
  14224. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14225. // iterate descending, so can just splice as we go
  14226. for (i = atIndices.length - 1; i >= 0; i--) {
  14227. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14228. result.push(i);
  14229. continue;
  14230. }
  14231. index = atIndices[i];
  14232. this._postProcesses.splice(index, 1);
  14233. }
  14234. }
  14235. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14236. return result;
  14237. };
  14238. Camera.prototype.getWorldMatrix = function () {
  14239. if (!this._worldMatrix) {
  14240. this._worldMatrix = BABYLON.Matrix.Identity();
  14241. }
  14242. var viewMatrix = this.getViewMatrix();
  14243. viewMatrix.invertToRef(this._worldMatrix);
  14244. return this._worldMatrix;
  14245. };
  14246. Camera.prototype._getViewMatrix = function () {
  14247. return BABYLON.Matrix.Identity();
  14248. };
  14249. Camera.prototype.getViewMatrix = function (force) {
  14250. this._computedViewMatrix = this._computeViewMatrix(force);
  14251. if (!force && this._isSynchronizedViewMatrix()) {
  14252. return this._computedViewMatrix;
  14253. }
  14254. this._refreshFrustumPlanes = true;
  14255. if (!this.parent || !this.parent.getWorldMatrix) {
  14256. this._globalPosition.copyFrom(this.position);
  14257. }
  14258. else {
  14259. if (!this._worldMatrix) {
  14260. this._worldMatrix = BABYLON.Matrix.Identity();
  14261. }
  14262. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14263. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14264. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14265. this._computedViewMatrix.invert();
  14266. this._markSyncedWithParent();
  14267. }
  14268. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14269. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14270. }
  14271. this._currentRenderId = this.getScene().getRenderId();
  14272. return this._computedViewMatrix;
  14273. };
  14274. Camera.prototype._computeViewMatrix = function (force) {
  14275. if (!force && this._isSynchronizedViewMatrix()) {
  14276. return this._computedViewMatrix;
  14277. }
  14278. this._computedViewMatrix = this._getViewMatrix();
  14279. this._currentRenderId = this.getScene().getRenderId();
  14280. return this._computedViewMatrix;
  14281. };
  14282. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14283. this._doNotComputeProjectionMatrix = true;
  14284. if (projection !== undefined) {
  14285. this._projectionMatrix = projection;
  14286. }
  14287. };
  14288. ;
  14289. Camera.prototype.unfreezeProjectionMatrix = function () {
  14290. this._doNotComputeProjectionMatrix = false;
  14291. };
  14292. ;
  14293. Camera.prototype.getProjectionMatrix = function (force) {
  14294. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14295. return this._projectionMatrix;
  14296. }
  14297. this._refreshFrustumPlanes = true;
  14298. var engine = this.getEngine();
  14299. var scene = this.getScene();
  14300. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14301. if (this.minZ <= 0) {
  14302. this.minZ = 0.1;
  14303. }
  14304. if (scene.useRightHandedSystem) {
  14305. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14306. }
  14307. else {
  14308. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14309. }
  14310. return this._projectionMatrix;
  14311. }
  14312. var halfWidth = engine.getRenderWidth() / 2.0;
  14313. var halfHeight = engine.getRenderHeight() / 2.0;
  14314. if (scene.useRightHandedSystem) {
  14315. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14316. }
  14317. else {
  14318. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14319. }
  14320. return this._projectionMatrix;
  14321. };
  14322. Camera.prototype.getTranformationMatrix = function () {
  14323. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14324. return this._transformMatrix;
  14325. };
  14326. Camera.prototype.updateFrustumPlanes = function () {
  14327. if (!this._refreshFrustumPlanes) {
  14328. return;
  14329. }
  14330. this.getTranformationMatrix();
  14331. if (!this._frustumPlanes) {
  14332. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14333. }
  14334. else {
  14335. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14336. }
  14337. this._refreshFrustumPlanes = false;
  14338. };
  14339. Camera.prototype.isInFrustum = function (target) {
  14340. this.updateFrustumPlanes();
  14341. return target.isInFrustum(this._frustumPlanes);
  14342. };
  14343. Camera.prototype.isCompletelyInFrustum = function (target) {
  14344. this.updateFrustumPlanes();
  14345. return target.isCompletelyInFrustum(this._frustumPlanes);
  14346. };
  14347. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14348. if (length === void 0) { length = 100; }
  14349. if (!transform) {
  14350. transform = this.getWorldMatrix();
  14351. }
  14352. if (!origin) {
  14353. origin = this.position;
  14354. }
  14355. var forward = new BABYLON.Vector3(0, 0, 1);
  14356. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14357. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14358. return new BABYLON.Ray(origin, direction, length);
  14359. };
  14360. Camera.prototype.dispose = function () {
  14361. // Animations
  14362. this.getScene().stopAnimation(this);
  14363. // Remove from scene
  14364. this.getScene().removeCamera(this);
  14365. while (this._rigCameras.length > 0) {
  14366. this._rigCameras.pop().dispose();
  14367. }
  14368. // Postprocesses
  14369. var i = this._postProcesses.length;
  14370. while (--i >= 0) {
  14371. this._postProcesses[i].dispose(this);
  14372. }
  14373. _super.prototype.dispose.call(this);
  14374. };
  14375. Object.defineProperty(Camera.prototype, "leftCamera", {
  14376. // ---- Camera rigs section ----
  14377. get: function () {
  14378. if (this._rigCameras.length < 1) {
  14379. return undefined;
  14380. }
  14381. return this._rigCameras[0];
  14382. },
  14383. enumerable: true,
  14384. configurable: true
  14385. });
  14386. Object.defineProperty(Camera.prototype, "rightCamera", {
  14387. get: function () {
  14388. if (this._rigCameras.length < 2) {
  14389. return undefined;
  14390. }
  14391. return this._rigCameras[1];
  14392. },
  14393. enumerable: true,
  14394. configurable: true
  14395. });
  14396. Camera.prototype.getLeftTarget = function () {
  14397. if (this._rigCameras.length < 1) {
  14398. return undefined;
  14399. }
  14400. return this._rigCameras[0].getTarget();
  14401. };
  14402. Camera.prototype.getRightTarget = function () {
  14403. if (this._rigCameras.length < 2) {
  14404. return undefined;
  14405. }
  14406. return this._rigCameras[1].getTarget();
  14407. };
  14408. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14409. while (this._rigCameras.length > 0) {
  14410. this._rigCameras.pop().dispose();
  14411. }
  14412. this.cameraRigMode = mode;
  14413. this._cameraRigParams = {};
  14414. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14415. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14416. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14417. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14418. // create the rig cameras, unless none
  14419. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14420. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14421. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14422. }
  14423. switch (this.cameraRigMode) {
  14424. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14425. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14426. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14427. break;
  14428. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14429. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14430. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14431. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14432. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14433. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14434. break;
  14435. case Camera.RIG_MODE_VR:
  14436. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14437. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14438. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14439. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14440. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14441. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14442. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14443. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14444. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14445. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14446. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14447. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14448. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14449. if (metrics.compensateDistortion) {
  14450. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14451. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14452. }
  14453. break;
  14454. case Camera.RIG_MODE_WEBVR:
  14455. if (rigParams.vrDisplay) {
  14456. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14457. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14458. //Left eye
  14459. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14460. this._rigCameras[0].setCameraRigParameter("left", true);
  14461. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14462. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14463. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14464. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14465. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14466. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14467. this._rigCameras[0].parent = this;
  14468. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14469. //Right eye
  14470. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14471. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14472. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14473. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14474. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14475. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14476. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14477. this._rigCameras[1].parent = this;
  14478. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14479. }
  14480. break;
  14481. }
  14482. this._cascadePostProcessesToRigCams();
  14483. this.
  14484. update();
  14485. };
  14486. Camera.prototype._getVRProjectionMatrix = function () {
  14487. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14488. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14489. return this._projectionMatrix;
  14490. };
  14491. Camera.prototype._updateCameraRotationMatrix = function () {
  14492. //Here for WebVR
  14493. };
  14494. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14495. //Here for WebVR
  14496. };
  14497. /**
  14498. * This function MUST be overwritten by the different WebVR cameras available.
  14499. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14500. */
  14501. Camera.prototype._getWebVRProjectionMatrix = function () {
  14502. return BABYLON.Matrix.Identity();
  14503. };
  14504. /**
  14505. * This function MUST be overwritten by the different WebVR cameras available.
  14506. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14507. */
  14508. Camera.prototype._getWebVRViewMatrix = function () {
  14509. return BABYLON.Matrix.Identity();
  14510. };
  14511. Camera.prototype.setCameraRigParameter = function (name, value) {
  14512. if (!this._cameraRigParams) {
  14513. this._cameraRigParams = {};
  14514. }
  14515. this._cameraRigParams[name] = value;
  14516. //provisionnally:
  14517. if (name === "interaxialDistance") {
  14518. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14519. }
  14520. };
  14521. /**
  14522. * needs to be overridden by children so sub has required properties to be copied
  14523. */
  14524. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14525. return null;
  14526. };
  14527. /**
  14528. * May need to be overridden by children
  14529. */
  14530. Camera.prototype._updateRigCameras = function () {
  14531. for (var i = 0; i < this._rigCameras.length; i++) {
  14532. this._rigCameras[i].minZ = this.minZ;
  14533. this._rigCameras[i].maxZ = this.maxZ;
  14534. this._rigCameras[i].fov = this.fov;
  14535. }
  14536. // only update viewport when ANAGLYPH
  14537. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14538. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14539. }
  14540. };
  14541. Camera.prototype._setupInputs = function () {
  14542. };
  14543. Camera.prototype.serialize = function () {
  14544. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14545. // Type
  14546. serializationObject.type = this.getClassName();
  14547. // Parent
  14548. if (this.parent) {
  14549. serializationObject.parentId = this.parent.id;
  14550. }
  14551. if (this.inputs) {
  14552. this.inputs.serialize(serializationObject);
  14553. }
  14554. // Animations
  14555. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14556. serializationObject.ranges = this.serializeAnimationRanges();
  14557. return serializationObject;
  14558. };
  14559. Camera.prototype.clone = function (name) {
  14560. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14561. };
  14562. Camera.prototype.getDirection = function (localAxis) {
  14563. var result = BABYLON.Vector3.Zero();
  14564. this.getDirectionToRef(localAxis, result);
  14565. return result;
  14566. };
  14567. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14568. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14569. };
  14570. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14571. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14572. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14573. switch (type) {
  14574. case "ArcRotateCamera":
  14575. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14576. case "DeviceOrientationCamera":
  14577. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14578. case "FollowCamera":
  14579. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14580. case "ArcFollowCamera":
  14581. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14582. case "GamepadCamera":
  14583. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14584. case "TouchCamera":
  14585. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14586. case "VirtualJoysticksCamera":
  14587. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14588. case "WebVRFreeCamera":
  14589. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14590. case "WebVRGamepadCamera":
  14591. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14592. case "VRDeviceOrientationFreeCamera":
  14593. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14594. case "VRDeviceOrientationGamepadCamera":
  14595. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14596. case "AnaglyphArcRotateCamera":
  14597. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14598. case "AnaglyphFreeCamera":
  14599. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14600. case "AnaglyphGamepadCamera":
  14601. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14602. case "AnaglyphUniversalCamera":
  14603. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14604. case "StereoscopicArcRotateCamera":
  14605. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14606. case "StereoscopicFreeCamera":
  14607. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14608. case "StereoscopicGamepadCamera":
  14609. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14610. case "StereoscopicUniversalCamera":
  14611. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14612. case "FreeCamera":
  14613. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14614. default:
  14615. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14616. }
  14617. };
  14618. Camera.Parse = function (parsedCamera, scene) {
  14619. var type = parsedCamera.type;
  14620. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14621. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14622. // Parent
  14623. if (parsedCamera.parentId) {
  14624. camera._waitingParentId = parsedCamera.parentId;
  14625. }
  14626. //If camera has an input manager, let it parse inputs settings
  14627. if (camera.inputs) {
  14628. camera.inputs.parse(parsedCamera);
  14629. camera._setupInputs();
  14630. }
  14631. if (camera.setPosition) {
  14632. camera.position.copyFromFloats(0, 0, 0);
  14633. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  14634. }
  14635. // Target
  14636. if (parsedCamera.target) {
  14637. if (camera.setTarget) {
  14638. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14639. }
  14640. }
  14641. // Apply 3d rig, when found
  14642. if (parsedCamera.cameraRigMode) {
  14643. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14644. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14645. }
  14646. // Animations
  14647. if (parsedCamera.animations) {
  14648. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14649. var parsedAnimation = parsedCamera.animations[animationIndex];
  14650. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14651. }
  14652. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14653. }
  14654. if (parsedCamera.autoAnimate) {
  14655. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14656. }
  14657. return camera;
  14658. };
  14659. return Camera;
  14660. }(BABYLON.Node));
  14661. // Statics
  14662. Camera._PERSPECTIVE_CAMERA = 0;
  14663. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14664. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14665. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14666. Camera._RIG_MODE_NONE = 0;
  14667. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14668. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14669. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14670. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14671. Camera._RIG_MODE_VR = 20;
  14672. Camera._RIG_MODE_WEBVR = 21;
  14673. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14674. __decorate([
  14675. BABYLON.serializeAsVector3()
  14676. ], Camera.prototype, "position", void 0);
  14677. __decorate([
  14678. BABYLON.serializeAsVector3()
  14679. ], Camera.prototype, "upVector", void 0);
  14680. __decorate([
  14681. BABYLON.serialize()
  14682. ], Camera.prototype, "orthoLeft", void 0);
  14683. __decorate([
  14684. BABYLON.serialize()
  14685. ], Camera.prototype, "orthoRight", void 0);
  14686. __decorate([
  14687. BABYLON.serialize()
  14688. ], Camera.prototype, "orthoBottom", void 0);
  14689. __decorate([
  14690. BABYLON.serialize()
  14691. ], Camera.prototype, "orthoTop", void 0);
  14692. __decorate([
  14693. BABYLON.serialize()
  14694. ], Camera.prototype, "fov", void 0);
  14695. __decorate([
  14696. BABYLON.serialize()
  14697. ], Camera.prototype, "minZ", void 0);
  14698. __decorate([
  14699. BABYLON.serialize()
  14700. ], Camera.prototype, "maxZ", void 0);
  14701. __decorate([
  14702. BABYLON.serialize()
  14703. ], Camera.prototype, "inertia", void 0);
  14704. __decorate([
  14705. BABYLON.serialize()
  14706. ], Camera.prototype, "mode", void 0);
  14707. __decorate([
  14708. BABYLON.serialize()
  14709. ], Camera.prototype, "layerMask", void 0);
  14710. __decorate([
  14711. BABYLON.serialize()
  14712. ], Camera.prototype, "fovMode", void 0);
  14713. __decorate([
  14714. BABYLON.serialize()
  14715. ], Camera.prototype, "cameraRigMode", void 0);
  14716. __decorate([
  14717. BABYLON.serialize()
  14718. ], Camera.prototype, "interaxialDistance", void 0);
  14719. __decorate([
  14720. BABYLON.serialize()
  14721. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14722. BABYLON.Camera = Camera;
  14723. })(BABYLON || (BABYLON = {}));
  14724. //# sourceMappingURL=babylon.camera.js.map
  14725. var BABYLON;
  14726. (function (BABYLON) {
  14727. var RenderingManager = (function () {
  14728. function RenderingManager(scene) {
  14729. this._renderingGroups = new Array();
  14730. this._autoClearDepthStencil = {};
  14731. this._customOpaqueSortCompareFn = {};
  14732. this._customAlphaTestSortCompareFn = {};
  14733. this._customTransparentSortCompareFn = {};
  14734. this._renderinGroupInfo = null;
  14735. this._scene = scene;
  14736. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14737. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14738. }
  14739. }
  14740. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14741. if (depth === void 0) { depth = true; }
  14742. if (stencil === void 0) { stencil = true; }
  14743. if (this._depthStencilBufferAlreadyCleaned) {
  14744. return;
  14745. }
  14746. this._scene.getEngine().clear(null, false, depth, stencil);
  14747. this._depthStencilBufferAlreadyCleaned = true;
  14748. };
  14749. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14750. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14751. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14752. var info = null;
  14753. if (observable) {
  14754. if (!this._renderinGroupInfo) {
  14755. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14756. }
  14757. info = this._renderinGroupInfo;
  14758. info.scene = this._scene;
  14759. info.camera = this._scene.activeCamera;
  14760. }
  14761. // Dispatch sprites
  14762. if (renderSprites) {
  14763. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14764. var manager = this._scene.spriteManagers[index];
  14765. this.dispatchSprites(manager);
  14766. }
  14767. }
  14768. // Render
  14769. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14770. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14771. var renderingGroup = this._renderingGroups[index];
  14772. if (!renderingGroup && !observable)
  14773. continue;
  14774. this._currentIndex = index;
  14775. var renderingGroupMask = 0;
  14776. // Fire PRECLEAR stage
  14777. if (observable) {
  14778. renderingGroupMask = Math.pow(2, index);
  14779. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14780. info.renderingGroupId = index;
  14781. observable.notifyObservers(info, renderingGroupMask);
  14782. }
  14783. // Clear depth/stencil if needed
  14784. if (RenderingManager.AUTOCLEAR) {
  14785. var autoClear = this._autoClearDepthStencil[index];
  14786. if (autoClear && autoClear.autoClear) {
  14787. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14788. }
  14789. }
  14790. if (observable) {
  14791. // Fire PREOPAQUE stage
  14792. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14793. observable.notifyObservers(info, renderingGroupMask);
  14794. // Fire PRETRANSPARENT stage
  14795. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14796. observable.notifyObservers(info, renderingGroupMask);
  14797. }
  14798. if (renderingGroup)
  14799. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14800. // Fire POSTTRANSPARENT stage
  14801. if (observable) {
  14802. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14803. observable.notifyObservers(info, renderingGroupMask);
  14804. }
  14805. }
  14806. };
  14807. RenderingManager.prototype.reset = function () {
  14808. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14809. var renderingGroup = this._renderingGroups[index];
  14810. if (renderingGroup) {
  14811. renderingGroup.prepare();
  14812. }
  14813. }
  14814. };
  14815. RenderingManager.prototype.dispose = function () {
  14816. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14817. var renderingGroup = this._renderingGroups[index];
  14818. if (renderingGroup) {
  14819. renderingGroup.dispose();
  14820. }
  14821. }
  14822. this._renderingGroups.length = 0;
  14823. };
  14824. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14825. if (!this._renderingGroups[renderingGroupId]) {
  14826. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14827. }
  14828. };
  14829. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14830. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14831. this._prepareRenderingGroup(renderingGroupId);
  14832. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14833. };
  14834. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14835. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14836. this._prepareRenderingGroup(renderingGroupId);
  14837. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14838. };
  14839. RenderingManager.prototype.dispatch = function (subMesh) {
  14840. var mesh = subMesh.getMesh();
  14841. var renderingGroupId = mesh.renderingGroupId || 0;
  14842. this._prepareRenderingGroup(renderingGroupId);
  14843. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14844. };
  14845. /**
  14846. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14847. * This allowed control for front to back rendering or reversly depending of the special needs.
  14848. *
  14849. * @param renderingGroupId The rendering group id corresponding to its index
  14850. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14851. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14852. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14853. */
  14854. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14855. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14856. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14857. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14858. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14859. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14860. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14861. if (this._renderingGroups[renderingGroupId]) {
  14862. var group = this._renderingGroups[renderingGroupId];
  14863. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14864. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14865. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14866. }
  14867. };
  14868. /**
  14869. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14870. *
  14871. * @param renderingGroupId The rendering group id corresponding to its index
  14872. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14873. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14874. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14875. */
  14876. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14877. if (depth === void 0) { depth = true; }
  14878. if (stencil === void 0) { stencil = true; }
  14879. this._autoClearDepthStencil[renderingGroupId] = {
  14880. autoClear: autoClearDepthStencil,
  14881. depth: depth,
  14882. stencil: stencil
  14883. };
  14884. };
  14885. return RenderingManager;
  14886. }());
  14887. /**
  14888. * The max id used for rendering groups (not included)
  14889. */
  14890. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14891. /**
  14892. * The min id used for rendering groups (included)
  14893. */
  14894. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14895. /**
  14896. * Used to globally prevent autoclearing scenes.
  14897. */
  14898. RenderingManager.AUTOCLEAR = true;
  14899. BABYLON.RenderingManager = RenderingManager;
  14900. })(BABYLON || (BABYLON = {}));
  14901. //# sourceMappingURL=babylon.renderingManager.js.map
  14902. var BABYLON;
  14903. (function (BABYLON) {
  14904. var RenderingGroup = (function () {
  14905. /**
  14906. * Creates a new rendering group.
  14907. * @param index The rendering group index
  14908. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14909. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14910. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14911. */
  14912. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14913. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14914. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14915. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14916. this.index = index;
  14917. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14918. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14919. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14920. this._particleSystems = new BABYLON.SmartArray(256);
  14921. this._spriteManagers = new BABYLON.SmartArray(256);
  14922. this._edgesRenderers = new BABYLON.SmartArray(16);
  14923. this._scene = scene;
  14924. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14925. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14926. this.transparentSortCompareFn = transparentSortCompareFn;
  14927. }
  14928. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14929. /**
  14930. * Set the opaque sort comparison function.
  14931. * If null the sub meshes will be render in the order they were created
  14932. */
  14933. set: function (value) {
  14934. this._opaqueSortCompareFn = value;
  14935. if (value) {
  14936. this._renderOpaque = this.renderOpaqueSorted;
  14937. }
  14938. else {
  14939. this._renderOpaque = RenderingGroup.renderUnsorted;
  14940. }
  14941. },
  14942. enumerable: true,
  14943. configurable: true
  14944. });
  14945. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14946. /**
  14947. * Set the alpha test sort comparison function.
  14948. * If null the sub meshes will be render in the order they were created
  14949. */
  14950. set: function (value) {
  14951. this._alphaTestSortCompareFn = value;
  14952. if (value) {
  14953. this._renderAlphaTest = this.renderAlphaTestSorted;
  14954. }
  14955. else {
  14956. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14957. }
  14958. },
  14959. enumerable: true,
  14960. configurable: true
  14961. });
  14962. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14963. /**
  14964. * Set the transparent sort comparison function.
  14965. * If null the sub meshes will be render in the order they were created
  14966. */
  14967. set: function (value) {
  14968. if (value) {
  14969. this._transparentSortCompareFn = value;
  14970. }
  14971. else {
  14972. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14973. }
  14974. this._renderTransparent = this.renderTransparentSorted;
  14975. },
  14976. enumerable: true,
  14977. configurable: true
  14978. });
  14979. /**
  14980. * Render all the sub meshes contained in the group.
  14981. * @param customRenderFunction Used to override the default render behaviour of the group.
  14982. * @returns true if rendered some submeshes.
  14983. */
  14984. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14985. if (customRenderFunction) {
  14986. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14987. return;
  14988. }
  14989. var engine = this._scene.getEngine();
  14990. // Opaque
  14991. if (this._opaqueSubMeshes.length !== 0) {
  14992. this._renderOpaque(this._opaqueSubMeshes);
  14993. }
  14994. // Alpha test
  14995. if (this._alphaTestSubMeshes.length !== 0) {
  14996. engine.setAlphaTesting(true);
  14997. this._renderAlphaTest(this._alphaTestSubMeshes);
  14998. engine.setAlphaTesting(false);
  14999. }
  15000. var stencilState = engine.getStencilBuffer();
  15001. engine.setStencilBuffer(false);
  15002. // Sprites
  15003. if (renderSprites) {
  15004. this._renderSprites();
  15005. }
  15006. // Particles
  15007. if (renderParticles) {
  15008. this._renderParticles(activeMeshes);
  15009. }
  15010. if (this.onBeforeTransparentRendering) {
  15011. this.onBeforeTransparentRendering();
  15012. }
  15013. // Transparent
  15014. if (this._transparentSubMeshes.length !== 0) {
  15015. this._renderTransparent(this._transparentSubMeshes);
  15016. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15017. }
  15018. engine.setStencilBuffer(stencilState);
  15019. // Edges
  15020. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15021. this._edgesRenderers.data[edgesRendererIndex].render();
  15022. }
  15023. };
  15024. /**
  15025. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15026. * @param subMeshes The submeshes to render
  15027. */
  15028. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15029. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15030. };
  15031. /**
  15032. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15033. * @param subMeshes The submeshes to render
  15034. */
  15035. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15036. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15037. };
  15038. /**
  15039. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15040. * @param subMeshes The submeshes to render
  15041. */
  15042. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15043. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15044. };
  15045. /**
  15046. * Renders the submeshes in a specified order.
  15047. * @param subMeshes The submeshes to sort before render
  15048. * @param sortCompareFn The comparison function use to sort
  15049. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15050. * @param transparent Specifies to activate blending if true
  15051. */
  15052. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15053. var subIndex = 0;
  15054. var subMesh;
  15055. for (; subIndex < subMeshes.length; subIndex++) {
  15056. subMesh = subMeshes.data[subIndex];
  15057. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15058. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15059. }
  15060. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15061. sortedArray.sort(sortCompareFn);
  15062. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15063. subMesh = sortedArray[subIndex];
  15064. subMesh.render(transparent);
  15065. }
  15066. };
  15067. /**
  15068. * Renders the submeshes in the order they were dispatched (no sort applied).
  15069. * @param subMeshes The submeshes to render
  15070. */
  15071. RenderingGroup.renderUnsorted = function (subMeshes) {
  15072. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15073. var submesh = subMeshes.data[subIndex];
  15074. submesh.render(false);
  15075. }
  15076. };
  15077. /**
  15078. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15079. * are rendered back to front if in the same alpha index.
  15080. *
  15081. * @param a The first submesh
  15082. * @param b The second submesh
  15083. * @returns The result of the comparison
  15084. */
  15085. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15086. // Alpha index first
  15087. if (a._alphaIndex > b._alphaIndex) {
  15088. return 1;
  15089. }
  15090. if (a._alphaIndex < b._alphaIndex) {
  15091. return -1;
  15092. }
  15093. // Then distance to camera
  15094. return RenderingGroup.backToFrontSortCompare(a, b);
  15095. };
  15096. /**
  15097. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15098. * are rendered back to front.
  15099. *
  15100. * @param a The first submesh
  15101. * @param b The second submesh
  15102. * @returns The result of the comparison
  15103. */
  15104. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15105. // Then distance to camera
  15106. if (a._distanceToCamera < b._distanceToCamera) {
  15107. return 1;
  15108. }
  15109. if (a._distanceToCamera > b._distanceToCamera) {
  15110. return -1;
  15111. }
  15112. return 0;
  15113. };
  15114. /**
  15115. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15116. * are rendered front to back (prevent overdraw).
  15117. *
  15118. * @param a The first submesh
  15119. * @param b The second submesh
  15120. * @returns The result of the comparison
  15121. */
  15122. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15123. // Then distance to camera
  15124. if (a._distanceToCamera < b._distanceToCamera) {
  15125. return -1;
  15126. }
  15127. if (a._distanceToCamera > b._distanceToCamera) {
  15128. return 1;
  15129. }
  15130. return 0;
  15131. };
  15132. /**
  15133. * Resets the different lists of submeshes to prepare a new frame.
  15134. */
  15135. RenderingGroup.prototype.prepare = function () {
  15136. this._opaqueSubMeshes.reset();
  15137. this._transparentSubMeshes.reset();
  15138. this._alphaTestSubMeshes.reset();
  15139. this._particleSystems.reset();
  15140. this._spriteManagers.reset();
  15141. this._edgesRenderers.reset();
  15142. };
  15143. RenderingGroup.prototype.dispose = function () {
  15144. this._opaqueSubMeshes.dispose();
  15145. this._transparentSubMeshes.dispose();
  15146. this._alphaTestSubMeshes.dispose();
  15147. this._particleSystems.dispose();
  15148. this._spriteManagers.dispose();
  15149. this._edgesRenderers.dispose();
  15150. };
  15151. /**
  15152. * Inserts the submesh in its correct queue depending on its material.
  15153. * @param subMesh The submesh to dispatch
  15154. */
  15155. RenderingGroup.prototype.dispatch = function (subMesh) {
  15156. var material = subMesh.getMaterial();
  15157. var mesh = subMesh.getMesh();
  15158. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15159. this._transparentSubMeshes.push(subMesh);
  15160. }
  15161. else if (material.needAlphaTesting()) {
  15162. this._alphaTestSubMeshes.push(subMesh);
  15163. }
  15164. else {
  15165. this._opaqueSubMeshes.push(subMesh); // Opaque
  15166. }
  15167. if (mesh._edgesRenderer) {
  15168. this._edgesRenderers.push(mesh._edgesRenderer);
  15169. }
  15170. };
  15171. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15172. this._spriteManagers.push(spriteManager);
  15173. };
  15174. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15175. this._particleSystems.push(particleSystem);
  15176. };
  15177. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15178. if (this._particleSystems.length === 0) {
  15179. return;
  15180. }
  15181. // Particles
  15182. var activeCamera = this._scene.activeCamera;
  15183. this._scene._particlesDuration.beginMonitoring();
  15184. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15185. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15186. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15187. continue;
  15188. }
  15189. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15190. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15191. }
  15192. }
  15193. this._scene._particlesDuration.endMonitoring(false);
  15194. };
  15195. RenderingGroup.prototype._renderSprites = function () {
  15196. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15197. return;
  15198. }
  15199. // Sprites
  15200. var activeCamera = this._scene.activeCamera;
  15201. this._scene._spritesDuration.beginMonitoring();
  15202. for (var id = 0; id < this._spriteManagers.length; id++) {
  15203. var spriteManager = this._spriteManagers.data[id];
  15204. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15205. spriteManager.render();
  15206. }
  15207. }
  15208. this._scene._spritesDuration.endMonitoring(false);
  15209. };
  15210. return RenderingGroup;
  15211. }());
  15212. BABYLON.RenderingGroup = RenderingGroup;
  15213. })(BABYLON || (BABYLON = {}));
  15214. //# sourceMappingURL=babylon.renderingGroup.js.map
  15215. var BABYLON;
  15216. (function (BABYLON) {
  15217. var ClickInfo = (function () {
  15218. function ClickInfo() {
  15219. this._singleClick = false;
  15220. this._doubleClick = false;
  15221. this._hasSwiped = false;
  15222. this._ignore = false;
  15223. }
  15224. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15225. get: function () {
  15226. return this._singleClick;
  15227. },
  15228. set: function (b) {
  15229. this._singleClick = b;
  15230. },
  15231. enumerable: true,
  15232. configurable: true
  15233. });
  15234. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15235. get: function () {
  15236. return this._doubleClick;
  15237. },
  15238. set: function (b) {
  15239. this._doubleClick = b;
  15240. },
  15241. enumerable: true,
  15242. configurable: true
  15243. });
  15244. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15245. get: function () {
  15246. return this._hasSwiped;
  15247. },
  15248. set: function (b) {
  15249. this._hasSwiped = b;
  15250. },
  15251. enumerable: true,
  15252. configurable: true
  15253. });
  15254. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15255. get: function () {
  15256. return this._ignore;
  15257. },
  15258. set: function (b) {
  15259. this._ignore = b;
  15260. },
  15261. enumerable: true,
  15262. configurable: true
  15263. });
  15264. return ClickInfo;
  15265. }());
  15266. var PointerEventTypes = (function () {
  15267. function PointerEventTypes() {
  15268. }
  15269. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15270. get: function () {
  15271. return PointerEventTypes._POINTERDOWN;
  15272. },
  15273. enumerable: true,
  15274. configurable: true
  15275. });
  15276. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15277. get: function () {
  15278. return PointerEventTypes._POINTERUP;
  15279. },
  15280. enumerable: true,
  15281. configurable: true
  15282. });
  15283. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15284. get: function () {
  15285. return PointerEventTypes._POINTERMOVE;
  15286. },
  15287. enumerable: true,
  15288. configurable: true
  15289. });
  15290. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15291. get: function () {
  15292. return PointerEventTypes._POINTERWHEEL;
  15293. },
  15294. enumerable: true,
  15295. configurable: true
  15296. });
  15297. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15298. get: function () {
  15299. return PointerEventTypes._POINTERPICK;
  15300. },
  15301. enumerable: true,
  15302. configurable: true
  15303. });
  15304. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15305. get: function () {
  15306. return PointerEventTypes._POINTERTAP;
  15307. },
  15308. enumerable: true,
  15309. configurable: true
  15310. });
  15311. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15312. get: function () {
  15313. return PointerEventTypes._POINTERDOUBLETAP;
  15314. },
  15315. enumerable: true,
  15316. configurable: true
  15317. });
  15318. return PointerEventTypes;
  15319. }());
  15320. PointerEventTypes._POINTERDOWN = 0x01;
  15321. PointerEventTypes._POINTERUP = 0x02;
  15322. PointerEventTypes._POINTERMOVE = 0x04;
  15323. PointerEventTypes._POINTERWHEEL = 0x08;
  15324. PointerEventTypes._POINTERPICK = 0x10;
  15325. PointerEventTypes._POINTERTAP = 0x20;
  15326. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15327. BABYLON.PointerEventTypes = PointerEventTypes;
  15328. var PointerInfoBase = (function () {
  15329. function PointerInfoBase(type, event) {
  15330. this.type = type;
  15331. this.event = event;
  15332. }
  15333. return PointerInfoBase;
  15334. }());
  15335. BABYLON.PointerInfoBase = PointerInfoBase;
  15336. /**
  15337. * This class is used to store pointer related info for the onPrePointerObservable event.
  15338. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15339. */
  15340. var PointerInfoPre = (function (_super) {
  15341. __extends(PointerInfoPre, _super);
  15342. function PointerInfoPre(type, event, localX, localY) {
  15343. var _this = _super.call(this, type, event) || this;
  15344. _this.skipOnPointerObservable = false;
  15345. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15346. return _this;
  15347. }
  15348. return PointerInfoPre;
  15349. }(PointerInfoBase));
  15350. BABYLON.PointerInfoPre = PointerInfoPre;
  15351. /**
  15352. * This type contains all the data related to a pointer event in Babylon.js.
  15353. * 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.
  15354. */
  15355. var PointerInfo = (function (_super) {
  15356. __extends(PointerInfo, _super);
  15357. function PointerInfo(type, event, pickInfo) {
  15358. var _this = _super.call(this, type, event) || this;
  15359. _this.pickInfo = pickInfo;
  15360. return _this;
  15361. }
  15362. return PointerInfo;
  15363. }(PointerInfoBase));
  15364. BABYLON.PointerInfo = PointerInfo;
  15365. /**
  15366. * This class is used by the onRenderingGroupObservable
  15367. */
  15368. var RenderingGroupInfo = (function () {
  15369. function RenderingGroupInfo() {
  15370. }
  15371. return RenderingGroupInfo;
  15372. }());
  15373. /**
  15374. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15375. * This stage will be fired no matter what
  15376. */
  15377. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15378. /**
  15379. * Called before opaque object are rendered.
  15380. * This stage will be fired only if there's 3D Opaque content to render
  15381. */
  15382. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15383. /**
  15384. * Called after the opaque objects are rendered and before the transparent ones
  15385. * This stage will be fired only if there's 3D transparent content to render
  15386. */
  15387. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15388. /**
  15389. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15390. * This stage will be fired no matter what
  15391. */
  15392. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15393. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15394. /**
  15395. * Represents a scene to be rendered by the engine.
  15396. * @see http://doc.babylonjs.com/page.php?p=21911
  15397. */
  15398. var Scene = (function () {
  15399. /**
  15400. * @constructor
  15401. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15402. */
  15403. function Scene(engine) {
  15404. // Members
  15405. this.autoClear = true;
  15406. this.autoClearDepthAndStencil = true;
  15407. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15408. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15409. this.forceWireframe = false;
  15410. this._forcePointsCloud = false;
  15411. this.forceShowBoundingBoxes = false;
  15412. this.animationsEnabled = true;
  15413. this.constantlyUpdateMeshUnderPointer = false;
  15414. this.hoverCursor = "pointer";
  15415. // Metadata
  15416. this.metadata = null;
  15417. // Events
  15418. /**
  15419. * An event triggered when the scene is disposed.
  15420. * @type {BABYLON.Observable}
  15421. */
  15422. this.onDisposeObservable = new BABYLON.Observable();
  15423. /**
  15424. * An event triggered before rendering the scene
  15425. * @type {BABYLON.Observable}
  15426. */
  15427. this.onBeforeRenderObservable = new BABYLON.Observable();
  15428. /**
  15429. * An event triggered after rendering the scene
  15430. * @type {BABYLON.Observable}
  15431. */
  15432. this.onAfterRenderObservable = new BABYLON.Observable();
  15433. /**
  15434. * An event triggered when the scene is ready
  15435. * @type {BABYLON.Observable}
  15436. */
  15437. this.onReadyObservable = new BABYLON.Observable();
  15438. /**
  15439. * An event triggered before rendering a camera
  15440. * @type {BABYLON.Observable}
  15441. */
  15442. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15443. /**
  15444. * An event triggered after rendering a camera
  15445. * @type {BABYLON.Observable}
  15446. */
  15447. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15448. /**
  15449. * An event triggered when a camera is created
  15450. * @type {BABYLON.Observable}
  15451. */
  15452. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15453. /**
  15454. * An event triggered when a camera is removed
  15455. * @type {BABYLON.Observable}
  15456. */
  15457. this.onCameraRemovedObservable = new BABYLON.Observable();
  15458. /**
  15459. * An event triggered when a light is created
  15460. * @type {BABYLON.Observable}
  15461. */
  15462. this.onNewLightAddedObservable = new BABYLON.Observable();
  15463. /**
  15464. * An event triggered when a light is removed
  15465. * @type {BABYLON.Observable}
  15466. */
  15467. this.onLightRemovedObservable = new BABYLON.Observable();
  15468. /**
  15469. * An event triggered when a geometry is created
  15470. * @type {BABYLON.Observable}
  15471. */
  15472. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15473. /**
  15474. * An event triggered when a geometry is removed
  15475. * @type {BABYLON.Observable}
  15476. */
  15477. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15478. /**
  15479. * An event triggered when a mesh is created
  15480. * @type {BABYLON.Observable}
  15481. */
  15482. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15483. /**
  15484. * An event triggered when a mesh is removed
  15485. * @type {BABYLON.Observable}
  15486. */
  15487. this.onMeshRemovedObservable = new BABYLON.Observable();
  15488. /**
  15489. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15490. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15491. * 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)
  15492. */
  15493. this.onRenderingGroupObservable = new BABYLON.Observable();
  15494. // Animations
  15495. this.animations = [];
  15496. /**
  15497. * 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).
  15498. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15499. */
  15500. this.onPrePointerObservable = new BABYLON.Observable();
  15501. /**
  15502. * Observable event triggered each time an input event is received from the rendering canvas
  15503. */
  15504. this.onPointerObservable = new BABYLON.Observable();
  15505. this._meshPickProceed = false;
  15506. this._previousHasSwiped = false;
  15507. this._currentPickResult = null;
  15508. this._previousPickResult = null;
  15509. this._isButtonPressed = false;
  15510. this._doubleClickOccured = false;
  15511. 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
  15512. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15513. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15514. this._startingPointerTime = 0;
  15515. this._previousStartingPointerTime = 0;
  15516. // Coordinate system
  15517. /**
  15518. * use right-handed coordinate system on this scene.
  15519. * @type {boolean}
  15520. */
  15521. this._useRightHandedSystem = false;
  15522. // Fog
  15523. /**
  15524. * is fog enabled on this scene.
  15525. * @type {boolean}
  15526. */
  15527. this._fogEnabled = true;
  15528. this._fogMode = Scene.FOGMODE_NONE;
  15529. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15530. this.fogDensity = 0.1;
  15531. this.fogStart = 0;
  15532. this.fogEnd = 1000.0;
  15533. // Lights
  15534. /**
  15535. * is shadow enabled on this scene.
  15536. * @type {boolean}
  15537. */
  15538. this._shadowsEnabled = true;
  15539. /**
  15540. * is light enabled on this scene.
  15541. * @type {boolean}
  15542. */
  15543. this._lightsEnabled = true;
  15544. /**
  15545. * All of the lights added to this scene.
  15546. * @see BABYLON.Light
  15547. * @type {BABYLON.Light[]}
  15548. */
  15549. this.lights = new Array();
  15550. // Cameras
  15551. /**
  15552. * All of the cameras added to this scene.
  15553. * @see BABYLON.Camera
  15554. * @type {BABYLON.Camera[]}
  15555. */
  15556. this.cameras = new Array();
  15557. this.activeCameras = new Array();
  15558. // Meshes
  15559. /**
  15560. * All of the (abstract) meshes added to this scene.
  15561. * @see BABYLON.AbstractMesh
  15562. * @type {BABYLON.AbstractMesh[]}
  15563. */
  15564. this.meshes = new Array();
  15565. // Geometries
  15566. this._geometries = new Array();
  15567. this.materials = new Array();
  15568. this.multiMaterials = new Array();
  15569. // Textures
  15570. this._texturesEnabled = true;
  15571. this.textures = new Array();
  15572. // Particles
  15573. this.particlesEnabled = true;
  15574. this.particleSystems = new Array();
  15575. // Sprites
  15576. this.spritesEnabled = true;
  15577. this.spriteManagers = new Array();
  15578. // Layers
  15579. this.layers = new Array();
  15580. this.highlightLayers = new Array();
  15581. // Skeletons
  15582. this._skeletonsEnabled = true;
  15583. this.skeletons = new Array();
  15584. // Morph targets
  15585. this.morphTargetManagers = new Array();
  15586. // Lens flares
  15587. this.lensFlaresEnabled = true;
  15588. this.lensFlareSystems = new Array();
  15589. // Collisions
  15590. this.collisionsEnabled = true;
  15591. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15592. // Postprocesses
  15593. this.postProcessesEnabled = true;
  15594. // Customs render targets
  15595. this.renderTargetsEnabled = true;
  15596. this.dumpNextRenderTargets = false;
  15597. this.customRenderTargets = new Array();
  15598. // Imported meshes
  15599. this.importedMeshesFiles = new Array();
  15600. // Probes
  15601. this.probesEnabled = true;
  15602. this.reflectionProbes = new Array();
  15603. this._actionManagers = new Array();
  15604. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15605. // Procedural textures
  15606. this.proceduralTexturesEnabled = true;
  15607. this._proceduralTextures = new Array();
  15608. this.soundTracks = new Array();
  15609. this._audioEnabled = true;
  15610. this._headphone = false;
  15611. // Performance counters
  15612. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15613. this._totalLightsCounter = new BABYLON.PerfCounter();
  15614. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15615. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15616. this._totalVertices = new BABYLON.PerfCounter();
  15617. this._activeIndices = new BABYLON.PerfCounter();
  15618. this._activeParticles = new BABYLON.PerfCounter();
  15619. this._lastFrameDuration = new BABYLON.PerfCounter();
  15620. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15621. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15622. this._particlesDuration = new BABYLON.PerfCounter();
  15623. this._renderDuration = new BABYLON.PerfCounter();
  15624. this._spritesDuration = new BABYLON.PerfCounter();
  15625. this._activeBones = new BABYLON.PerfCounter();
  15626. this._animationTime = 0;
  15627. this.animationTimeScale = 1;
  15628. this._renderId = 0;
  15629. this._executeWhenReadyTimeoutId = -1;
  15630. this._intermediateRendering = false;
  15631. this._viewUpdateFlag = -1;
  15632. this._projectionUpdateFlag = -1;
  15633. this._toBeDisposed = new BABYLON.SmartArray(256);
  15634. this._pendingData = []; //ANY
  15635. this._activeMeshes = new BABYLON.SmartArray(256);
  15636. this._processedMaterials = new BABYLON.SmartArray(256);
  15637. this._renderTargets = new BABYLON.SmartArray(256);
  15638. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15639. this._activeSkeletons = new BABYLON.SmartArray(32);
  15640. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15641. this._activeAnimatables = new Array();
  15642. this._transformMatrix = BABYLON.Matrix.Zero();
  15643. this.requireLightSorting = false;
  15644. this._uniqueIdCounter = 0;
  15645. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15646. this._engine.scenes.push(this);
  15647. this._uid = null;
  15648. this._renderingManager = new BABYLON.RenderingManager(this);
  15649. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15650. if (BABYLON.OutlineRenderer) {
  15651. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15652. }
  15653. this.attachControl();
  15654. if (BABYLON.SoundTrack) {
  15655. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15656. }
  15657. //simplification queue
  15658. if (BABYLON.SimplificationQueue) {
  15659. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15660. }
  15661. //collision coordinator initialization. For now legacy per default.
  15662. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15663. // Uniform Buffer
  15664. this._createUbo();
  15665. // Default Image processing definition.
  15666. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  15667. }
  15668. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15669. get: function () {
  15670. return Scene._FOGMODE_NONE;
  15671. },
  15672. enumerable: true,
  15673. configurable: true
  15674. });
  15675. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15676. get: function () {
  15677. return Scene._FOGMODE_EXP;
  15678. },
  15679. enumerable: true,
  15680. configurable: true
  15681. });
  15682. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15683. get: function () {
  15684. return Scene._FOGMODE_EXP2;
  15685. },
  15686. enumerable: true,
  15687. configurable: true
  15688. });
  15689. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15690. get: function () {
  15691. return Scene._FOGMODE_LINEAR;
  15692. },
  15693. enumerable: true,
  15694. configurable: true
  15695. });
  15696. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15697. /**
  15698. * Texture used in all pbr material as the reflection texture.
  15699. * As in the majority of the scene they are the same (exception for multi room and so on),
  15700. * this is easier to reference from here than from all the materials.
  15701. */
  15702. get: function () {
  15703. return this._environmentTexture;
  15704. },
  15705. /**
  15706. * Texture used in all pbr material as the reflection texture.
  15707. * As in the majority of the scene they are the same (exception for multi room and so on),
  15708. * this is easier to set here than in all the materials.
  15709. */
  15710. set: function (value) {
  15711. this._environmentTexture = value;
  15712. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15713. },
  15714. enumerable: true,
  15715. configurable: true
  15716. });
  15717. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  15718. /**
  15719. * Default image processing configuration used either in the rendering
  15720. * Forward main pass or through the imageProcessingPostProcess if present.
  15721. * As in the majority of the scene they are the same (exception for multi camera),
  15722. * this is easier to reference from here than from all the materials and post process.
  15723. *
  15724. * No setter as we it is a shared configuration, you can set the values instead.
  15725. */
  15726. get: function () {
  15727. return this._imageProcessingConfiguration;
  15728. },
  15729. enumerable: true,
  15730. configurable: true
  15731. });
  15732. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15733. get: function () {
  15734. return this._forcePointsCloud;
  15735. },
  15736. set: function (value) {
  15737. if (this._forcePointsCloud === value) {
  15738. return;
  15739. }
  15740. this._forcePointsCloud = value;
  15741. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15742. },
  15743. enumerable: true,
  15744. configurable: true
  15745. });
  15746. Object.defineProperty(Scene.prototype, "onDispose", {
  15747. set: function (callback) {
  15748. if (this._onDisposeObserver) {
  15749. this.onDisposeObservable.remove(this._onDisposeObserver);
  15750. }
  15751. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15752. },
  15753. enumerable: true,
  15754. configurable: true
  15755. });
  15756. Object.defineProperty(Scene.prototype, "beforeRender", {
  15757. set: function (callback) {
  15758. if (this._onBeforeRenderObserver) {
  15759. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15760. }
  15761. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15762. },
  15763. enumerable: true,
  15764. configurable: true
  15765. });
  15766. Object.defineProperty(Scene.prototype, "afterRender", {
  15767. set: function (callback) {
  15768. if (this._onAfterRenderObserver) {
  15769. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15770. }
  15771. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15772. },
  15773. enumerable: true,
  15774. configurable: true
  15775. });
  15776. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15777. set: function (callback) {
  15778. if (this._onBeforeCameraRenderObserver) {
  15779. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15780. }
  15781. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15782. },
  15783. enumerable: true,
  15784. configurable: true
  15785. });
  15786. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15787. set: function (callback) {
  15788. if (this._onAfterCameraRenderObserver) {
  15789. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15790. }
  15791. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15792. },
  15793. enumerable: true,
  15794. configurable: true
  15795. });
  15796. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15797. get: function () {
  15798. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15799. },
  15800. enumerable: true,
  15801. configurable: true
  15802. });
  15803. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15804. get: function () {
  15805. return this._useRightHandedSystem;
  15806. },
  15807. set: function (value) {
  15808. if (this._useRightHandedSystem === value) {
  15809. return;
  15810. }
  15811. this._useRightHandedSystem = value;
  15812. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15813. },
  15814. enumerable: true,
  15815. configurable: true
  15816. });
  15817. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15818. get: function () {
  15819. return this._fogEnabled;
  15820. },
  15821. set: function (value) {
  15822. if (this._fogEnabled === value) {
  15823. return;
  15824. }
  15825. this._fogEnabled = value;
  15826. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15827. },
  15828. enumerable: true,
  15829. configurable: true
  15830. });
  15831. Object.defineProperty(Scene.prototype, "fogMode", {
  15832. get: function () {
  15833. return this._fogMode;
  15834. },
  15835. set: function (value) {
  15836. if (this._fogMode === value) {
  15837. return;
  15838. }
  15839. this._fogMode = value;
  15840. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15841. },
  15842. enumerable: true,
  15843. configurable: true
  15844. });
  15845. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15846. get: function () {
  15847. return this._shadowsEnabled;
  15848. },
  15849. set: function (value) {
  15850. if (this._shadowsEnabled === value) {
  15851. return;
  15852. }
  15853. this._shadowsEnabled = value;
  15854. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15855. },
  15856. enumerable: true,
  15857. configurable: true
  15858. });
  15859. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15860. get: function () {
  15861. return this._lightsEnabled;
  15862. },
  15863. set: function (value) {
  15864. if (this._lightsEnabled === value) {
  15865. return;
  15866. }
  15867. this._lightsEnabled = value;
  15868. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15869. },
  15870. enumerable: true,
  15871. configurable: true
  15872. });
  15873. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15874. get: function () {
  15875. if (!this._defaultMaterial) {
  15876. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15877. }
  15878. return this._defaultMaterial;
  15879. },
  15880. set: function (value) {
  15881. this._defaultMaterial = value;
  15882. },
  15883. enumerable: true,
  15884. configurable: true
  15885. });
  15886. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15887. get: function () {
  15888. return this._texturesEnabled;
  15889. },
  15890. set: function (value) {
  15891. if (this._texturesEnabled === value) {
  15892. return;
  15893. }
  15894. this._texturesEnabled = value;
  15895. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15896. },
  15897. enumerable: true,
  15898. configurable: true
  15899. });
  15900. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15901. get: function () {
  15902. return this._skeletonsEnabled;
  15903. },
  15904. set: function (value) {
  15905. if (this._skeletonsEnabled === value) {
  15906. return;
  15907. }
  15908. this._skeletonsEnabled = value;
  15909. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15910. },
  15911. enumerable: true,
  15912. configurable: true
  15913. });
  15914. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15915. get: function () {
  15916. if (!this._postProcessRenderPipelineManager) {
  15917. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15918. }
  15919. return this._postProcessRenderPipelineManager;
  15920. },
  15921. enumerable: true,
  15922. configurable: true
  15923. });
  15924. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15925. get: function () {
  15926. return this._frustumPlanes;
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. Object.defineProperty(Scene.prototype, "debugLayer", {
  15932. // Properties
  15933. get: function () {
  15934. if (!this._debugLayer) {
  15935. this._debugLayer = new BABYLON.DebugLayer(this);
  15936. }
  15937. return this._debugLayer;
  15938. },
  15939. enumerable: true,
  15940. configurable: true
  15941. });
  15942. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15943. get: function () {
  15944. return this._workerCollisions;
  15945. },
  15946. set: function (enabled) {
  15947. if (!BABYLON.CollisionCoordinatorLegacy) {
  15948. return;
  15949. }
  15950. enabled = (enabled && !!Worker);
  15951. this._workerCollisions = enabled;
  15952. if (this.collisionCoordinator) {
  15953. this.collisionCoordinator.destroy();
  15954. }
  15955. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15956. this.collisionCoordinator.init(this);
  15957. },
  15958. enumerable: true,
  15959. configurable: true
  15960. });
  15961. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15962. get: function () {
  15963. return this._selectionOctree;
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15969. /**
  15970. * The mesh that is currently under the pointer.
  15971. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15972. */
  15973. get: function () {
  15974. return this._pointerOverMesh;
  15975. },
  15976. enumerable: true,
  15977. configurable: true
  15978. });
  15979. Object.defineProperty(Scene.prototype, "pointerX", {
  15980. /**
  15981. * Current on-screen X position of the pointer
  15982. * @return {number} X position of the pointer
  15983. */
  15984. get: function () {
  15985. return this._pointerX;
  15986. },
  15987. enumerable: true,
  15988. configurable: true
  15989. });
  15990. Object.defineProperty(Scene.prototype, "pointerY", {
  15991. /**
  15992. * Current on-screen Y position of the pointer
  15993. * @return {number} Y position of the pointer
  15994. */
  15995. get: function () {
  15996. return this._pointerY;
  15997. },
  15998. enumerable: true,
  15999. configurable: true
  16000. });
  16001. Scene.prototype.getCachedMaterial = function () {
  16002. return this._cachedMaterial;
  16003. };
  16004. Scene.prototype.getCachedEffect = function () {
  16005. return this._cachedEffect;
  16006. };
  16007. Scene.prototype.getCachedVisibility = function () {
  16008. return this._cachedVisibility;
  16009. };
  16010. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  16011. if (visibility === void 0) { visibility = 0; }
  16012. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16013. };
  16014. Scene.prototype.getBoundingBoxRenderer = function () {
  16015. if (!this._boundingBoxRenderer) {
  16016. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16017. }
  16018. return this._boundingBoxRenderer;
  16019. };
  16020. Scene.prototype.getOutlineRenderer = function () {
  16021. return this._outlineRenderer;
  16022. };
  16023. Scene.prototype.getEngine = function () {
  16024. return this._engine;
  16025. };
  16026. Scene.prototype.getTotalVertices = function () {
  16027. return this._totalVertices.current;
  16028. };
  16029. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16030. get: function () {
  16031. return this._totalVertices;
  16032. },
  16033. enumerable: true,
  16034. configurable: true
  16035. });
  16036. Scene.prototype.getActiveIndices = function () {
  16037. return this._activeIndices.current;
  16038. };
  16039. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16040. get: function () {
  16041. return this._activeIndices;
  16042. },
  16043. enumerable: true,
  16044. configurable: true
  16045. });
  16046. Scene.prototype.getActiveParticles = function () {
  16047. return this._activeParticles.current;
  16048. };
  16049. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16050. get: function () {
  16051. return this._activeParticles;
  16052. },
  16053. enumerable: true,
  16054. configurable: true
  16055. });
  16056. Scene.prototype.getActiveBones = function () {
  16057. return this._activeBones.current;
  16058. };
  16059. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16060. get: function () {
  16061. return this._activeBones;
  16062. },
  16063. enumerable: true,
  16064. configurable: true
  16065. });
  16066. // Stats
  16067. Scene.prototype.getLastFrameDuration = function () {
  16068. return this._lastFrameDuration.current;
  16069. };
  16070. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16071. get: function () {
  16072. return this._lastFrameDuration;
  16073. },
  16074. enumerable: true,
  16075. configurable: true
  16076. });
  16077. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16078. return this._evaluateActiveMeshesDuration.current;
  16079. };
  16080. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16081. get: function () {
  16082. return this._evaluateActiveMeshesDuration;
  16083. },
  16084. enumerable: true,
  16085. configurable: true
  16086. });
  16087. Scene.prototype.getActiveMeshes = function () {
  16088. return this._activeMeshes;
  16089. };
  16090. Scene.prototype.getRenderTargetsDuration = function () {
  16091. return this._renderTargetsDuration.current;
  16092. };
  16093. Scene.prototype.getRenderDuration = function () {
  16094. return this._renderDuration.current;
  16095. };
  16096. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16097. get: function () {
  16098. return this._renderDuration;
  16099. },
  16100. enumerable: true,
  16101. configurable: true
  16102. });
  16103. Scene.prototype.getParticlesDuration = function () {
  16104. return this._particlesDuration.current;
  16105. };
  16106. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16107. get: function () {
  16108. return this._particlesDuration;
  16109. },
  16110. enumerable: true,
  16111. configurable: true
  16112. });
  16113. Scene.prototype.getSpritesDuration = function () {
  16114. return this._spritesDuration.current;
  16115. };
  16116. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16117. get: function () {
  16118. return this._spritesDuration;
  16119. },
  16120. enumerable: true,
  16121. configurable: true
  16122. });
  16123. Scene.prototype.getAnimationRatio = function () {
  16124. return this._animationRatio;
  16125. };
  16126. Scene.prototype.getRenderId = function () {
  16127. return this._renderId;
  16128. };
  16129. Scene.prototype.incrementRenderId = function () {
  16130. this._renderId++;
  16131. };
  16132. Scene.prototype._updatePointerPosition = function (evt) {
  16133. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16134. this._pointerX = evt.clientX - canvasRect.left;
  16135. this._pointerY = evt.clientY - canvasRect.top;
  16136. this._unTranslatedPointerX = this._pointerX;
  16137. this._unTranslatedPointerY = this._pointerY;
  16138. if (this.cameraToUseForPointers) {
  16139. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16140. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16141. }
  16142. };
  16143. Scene.prototype._createUbo = function () {
  16144. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16145. this._sceneUbo.addUniform("viewProjection", 16);
  16146. this._sceneUbo.addUniform("view", 16);
  16147. };
  16148. // Pointers handling
  16149. /**
  16150. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16151. * @param attachUp defines if you want to attach events to pointerup
  16152. * @param attachDown defines if you want to attach events to pointerdown
  16153. * @param attachMove defines if you want to attach events to pointermove
  16154. */
  16155. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16156. var _this = this;
  16157. if (attachUp === void 0) { attachUp = true; }
  16158. if (attachDown === void 0) { attachDown = true; }
  16159. if (attachMove === void 0) { attachMove = true; }
  16160. this._initActionManager = function (act, clickInfo) {
  16161. if (!_this._meshPickProceed) {
  16162. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16163. _this._currentPickResult = pickResult;
  16164. if (pickResult) {
  16165. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16166. }
  16167. _this._meshPickProceed = true;
  16168. }
  16169. return act;
  16170. };
  16171. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16172. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16173. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16174. btn !== _this._previousButtonPressed) {
  16175. _this._doubleClickOccured = false;
  16176. clickInfo.singleClick = true;
  16177. clickInfo.ignore = false;
  16178. cb(clickInfo, _this._currentPickResult);
  16179. }
  16180. };
  16181. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16182. var clickInfo = new ClickInfo();
  16183. _this._currentPickResult = null;
  16184. var act;
  16185. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16186. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16187. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16188. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16189. act = _this._initActionManager(act, clickInfo);
  16190. if (act)
  16191. checkPicking = act.hasPickTriggers;
  16192. }
  16193. if (checkPicking) {
  16194. var btn = evt.button;
  16195. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16196. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16197. if (!clickInfo.hasSwiped) {
  16198. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16199. if (!checkSingleClickImmediately) {
  16200. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16201. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16202. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16203. act = _this._initActionManager(act, clickInfo);
  16204. if (act)
  16205. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16206. }
  16207. }
  16208. if (checkSingleClickImmediately) {
  16209. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16210. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16211. btn !== _this._previousButtonPressed) {
  16212. clickInfo.singleClick = true;
  16213. cb(clickInfo, _this._currentPickResult);
  16214. }
  16215. }
  16216. else {
  16217. // wait that no double click has been raised during the double click delay
  16218. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16219. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16220. }
  16221. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16222. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16223. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16224. act = _this._initActionManager(act, clickInfo);
  16225. if (act)
  16226. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16227. }
  16228. if (checkDoubleClick) {
  16229. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16230. if (btn === _this._previousButtonPressed &&
  16231. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16232. !_this._doubleClickOccured) {
  16233. // pointer has not moved for 2 clicks, it's a double click
  16234. if (!clickInfo.hasSwiped &&
  16235. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16236. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16237. _this._previousStartingPointerTime = 0;
  16238. _this._doubleClickOccured = true;
  16239. clickInfo.doubleClick = true;
  16240. clickInfo.ignore = false;
  16241. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16242. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16243. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16244. cb(clickInfo, _this._currentPickResult);
  16245. }
  16246. else {
  16247. _this._doubleClickOccured = false;
  16248. _this._previousStartingPointerTime = _this._startingPointerTime;
  16249. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16250. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16251. _this._previousButtonPressed = btn;
  16252. _this._previousHasSwiped = clickInfo.hasSwiped;
  16253. if (Scene.ExclusiveDoubleClickMode) {
  16254. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16255. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16256. }
  16257. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16258. cb(clickInfo, _this._previousPickResult);
  16259. }
  16260. else {
  16261. cb(clickInfo, _this._currentPickResult);
  16262. }
  16263. }
  16264. }
  16265. else {
  16266. _this._doubleClickOccured = false;
  16267. _this._previousStartingPointerTime = _this._startingPointerTime;
  16268. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16269. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16270. _this._previousButtonPressed = btn;
  16271. _this._previousHasSwiped = clickInfo.hasSwiped;
  16272. }
  16273. }
  16274. }
  16275. }
  16276. clickInfo.ignore = true;
  16277. cb(clickInfo, _this._currentPickResult);
  16278. };
  16279. var spritePredicate = function (sprite) {
  16280. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16281. };
  16282. this._onPointerMove = function (evt) {
  16283. _this._updatePointerPosition(evt);
  16284. // PreObservable support
  16285. if (_this.onPrePointerObservable.hasObservers()) {
  16286. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16287. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16288. _this.onPrePointerObservable.notifyObservers(pi, type);
  16289. if (pi.skipOnPointerObservable) {
  16290. return;
  16291. }
  16292. }
  16293. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16294. return;
  16295. }
  16296. var canvas = _this._engine.getRenderingCanvas();
  16297. if (!_this.pointerMovePredicate) {
  16298. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16299. }
  16300. // Meshes
  16301. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16302. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16303. _this.setPointerOverSprite(null);
  16304. _this.setPointerOverMesh(pickResult.pickedMesh);
  16305. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16306. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16307. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16308. }
  16309. else {
  16310. canvas.style.cursor = _this.hoverCursor;
  16311. }
  16312. }
  16313. else {
  16314. canvas.style.cursor = "";
  16315. }
  16316. }
  16317. else {
  16318. _this.setPointerOverMesh(null);
  16319. // Sprites
  16320. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16321. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16322. _this.setPointerOverSprite(pickResult.pickedSprite);
  16323. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16324. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16325. }
  16326. else {
  16327. canvas.style.cursor = _this.hoverCursor;
  16328. }
  16329. }
  16330. else {
  16331. _this.setPointerOverSprite(null);
  16332. // Restore pointer
  16333. canvas.style.cursor = "";
  16334. }
  16335. }
  16336. if (_this.onPointerMove) {
  16337. _this.onPointerMove(evt, pickResult);
  16338. }
  16339. if (_this.onPointerObservable.hasObservers()) {
  16340. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16341. var pi = new PointerInfo(type, evt, pickResult);
  16342. _this.onPointerObservable.notifyObservers(pi, type);
  16343. }
  16344. };
  16345. this._onPointerDown = function (evt) {
  16346. _this._isButtonPressed = true;
  16347. _this._pickedDownMesh = null;
  16348. _this._meshPickProceed = false;
  16349. _this._updatePointerPosition(evt);
  16350. // PreObservable support
  16351. if (_this.onPrePointerObservable.hasObservers()) {
  16352. var type = PointerEventTypes.POINTERDOWN;
  16353. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16354. _this.onPrePointerObservable.notifyObservers(pi, type);
  16355. if (pi.skipOnPointerObservable) {
  16356. return;
  16357. }
  16358. }
  16359. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16360. return;
  16361. }
  16362. _this._startingPointerPosition.x = _this._pointerX;
  16363. _this._startingPointerPosition.y = _this._pointerY;
  16364. _this._startingPointerTime = new Date().getTime();
  16365. if (!_this.pointerDownPredicate) {
  16366. _this.pointerDownPredicate = function (mesh) {
  16367. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16368. };
  16369. }
  16370. // Meshes
  16371. _this._pickedDownMesh = null;
  16372. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16373. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16374. _this._pickedDownMesh = pickResult.pickedMesh;
  16375. var actionManager = pickResult.pickedMesh.actionManager;
  16376. if (actionManager) {
  16377. if (actionManager.hasPickTriggers) {
  16378. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16379. switch (evt.button) {
  16380. case 0:
  16381. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16382. break;
  16383. case 1:
  16384. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16385. break;
  16386. case 2:
  16387. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16388. break;
  16389. }
  16390. }
  16391. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16392. window.setTimeout((function () {
  16393. var _this = this;
  16394. 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);
  16395. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16396. if (this._isButtonPressed &&
  16397. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16398. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16399. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16400. this._startingPointerTime = 0;
  16401. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16402. }
  16403. }
  16404. }).bind(_this), Scene.LongPressDelay);
  16405. }
  16406. }
  16407. }
  16408. if (_this.onPointerDown) {
  16409. _this.onPointerDown(evt, pickResult);
  16410. }
  16411. if (_this.onPointerObservable.hasObservers()) {
  16412. var type = PointerEventTypes.POINTERDOWN;
  16413. var pi = new PointerInfo(type, evt, pickResult);
  16414. _this.onPointerObservable.notifyObservers(pi, type);
  16415. }
  16416. // Sprites
  16417. _this._pickedDownSprite = null;
  16418. if (_this.spriteManagers.length > 0) {
  16419. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16420. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16421. if (pickResult.pickedSprite.actionManager) {
  16422. _this._pickedDownSprite = pickResult.pickedSprite;
  16423. switch (evt.button) {
  16424. case 0:
  16425. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16426. break;
  16427. case 1:
  16428. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16429. break;
  16430. case 2:
  16431. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16432. break;
  16433. }
  16434. if (pickResult.pickedSprite.actionManager) {
  16435. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16436. }
  16437. }
  16438. }
  16439. }
  16440. };
  16441. this._onPointerUp = function (evt) {
  16442. _this._isButtonPressed = false;
  16443. _this._pickedUpMesh = null;
  16444. _this._meshPickProceed = false;
  16445. _this._updatePointerPosition(evt);
  16446. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16447. // PreObservable support
  16448. if (this.onPrePointerObservable.hasObservers()) {
  16449. if (!clickInfo.ignore) {
  16450. if (!clickInfo.hasSwiped) {
  16451. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16452. var type = PointerEventTypes.POINTERTAP;
  16453. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16454. this.onPrePointerObservable.notifyObservers(pi, type);
  16455. if (pi.skipOnPointerObservable) {
  16456. return;
  16457. }
  16458. }
  16459. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16460. var type = PointerEventTypes.POINTERDOUBLETAP;
  16461. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16462. this.onPrePointerObservable.notifyObservers(pi, type);
  16463. if (pi.skipOnPointerObservable) {
  16464. return;
  16465. }
  16466. }
  16467. }
  16468. }
  16469. else {
  16470. var type = PointerEventTypes.POINTERUP;
  16471. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16472. this.onPrePointerObservable.notifyObservers(pi, type);
  16473. if (pi.skipOnPointerObservable) {
  16474. return;
  16475. }
  16476. }
  16477. }
  16478. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16479. return;
  16480. }
  16481. if (!this.pointerUpPredicate) {
  16482. this.pointerUpPredicate = function (mesh) {
  16483. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16484. };
  16485. }
  16486. // Meshes
  16487. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16488. this._initActionManager(null, clickInfo);
  16489. }
  16490. if (!pickResult) {
  16491. pickResult = this._currentPickResult;
  16492. }
  16493. if (pickResult && pickResult && pickResult.pickedMesh) {
  16494. this._pickedUpMesh = pickResult.pickedMesh;
  16495. if (this._pickedDownMesh === this._pickedUpMesh) {
  16496. if (this.onPointerPick) {
  16497. this.onPointerPick(evt, pickResult);
  16498. }
  16499. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16500. var type = PointerEventTypes.POINTERPICK;
  16501. var pi = new PointerInfo(type, evt, pickResult);
  16502. this.onPointerObservable.notifyObservers(pi, type);
  16503. }
  16504. }
  16505. if (pickResult.pickedMesh.actionManager) {
  16506. if (clickInfo.ignore) {
  16507. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16508. }
  16509. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16510. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16511. }
  16512. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16513. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16514. }
  16515. }
  16516. }
  16517. if (this._pickedDownMesh &&
  16518. this._pickedDownMesh.actionManager &&
  16519. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16520. this._pickedDownMesh !== this._pickedUpMesh) {
  16521. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16522. }
  16523. if (this.onPointerUp) {
  16524. this.onPointerUp(evt, pickResult);
  16525. }
  16526. if (this.onPointerObservable.hasObservers()) {
  16527. if (!clickInfo.ignore) {
  16528. if (!clickInfo.hasSwiped) {
  16529. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16530. var type = PointerEventTypes.POINTERTAP;
  16531. var pi = new PointerInfo(type, evt, pickResult);
  16532. this.onPointerObservable.notifyObservers(pi, type);
  16533. }
  16534. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16535. var type = PointerEventTypes.POINTERDOUBLETAP;
  16536. var pi = new PointerInfo(type, evt, pickResult);
  16537. this.onPointerObservable.notifyObservers(pi, type);
  16538. }
  16539. }
  16540. }
  16541. else {
  16542. var type = PointerEventTypes.POINTERUP;
  16543. var pi = new PointerInfo(type, evt, pickResult);
  16544. this.onPointerObservable.notifyObservers(pi, type);
  16545. }
  16546. }
  16547. // Sprites
  16548. if (this.spriteManagers.length > 0) {
  16549. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16550. if (pickResult.hit && pickResult.pickedSprite) {
  16551. if (pickResult.pickedSprite.actionManager) {
  16552. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16553. if (pickResult.pickedSprite.actionManager) {
  16554. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16555. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16556. }
  16557. }
  16558. }
  16559. }
  16560. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16561. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16562. }
  16563. }
  16564. this._previousPickResult = this._currentPickResult;
  16565. }).bind(_this));
  16566. };
  16567. this._onKeyDown = function (evt) {
  16568. if (_this.actionManager) {
  16569. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16570. }
  16571. };
  16572. this._onKeyUp = function (evt) {
  16573. if (_this.actionManager) {
  16574. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16575. }
  16576. };
  16577. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16578. var canvas = this._engine.getRenderingCanvas();
  16579. if (attachMove) {
  16580. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16581. // Wheel
  16582. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16583. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16584. }
  16585. if (attachDown) {
  16586. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16587. }
  16588. if (attachUp) {
  16589. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16590. }
  16591. canvas.tabIndex = 1;
  16592. canvas.addEventListener("keydown", this._onKeyDown, false);
  16593. canvas.addEventListener("keyup", this._onKeyUp, false);
  16594. };
  16595. Scene.prototype.detachControl = function () {
  16596. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16597. var canvas = this._engine.getRenderingCanvas();
  16598. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16599. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16600. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16601. // Wheel
  16602. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16603. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16604. canvas.removeEventListener("keydown", this._onKeyDown);
  16605. canvas.removeEventListener("keyup", this._onKeyUp);
  16606. };
  16607. // Ready
  16608. Scene.prototype.isReady = function () {
  16609. if (this._pendingData.length > 0) {
  16610. return false;
  16611. }
  16612. var index;
  16613. // Geometries
  16614. for (index = 0; index < this._geometries.length; index++) {
  16615. var geometry = this._geometries[index];
  16616. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16617. return false;
  16618. }
  16619. }
  16620. // Meshes
  16621. for (index = 0; index < this.meshes.length; index++) {
  16622. var mesh = this.meshes[index];
  16623. if (!mesh.isEnabled()) {
  16624. continue;
  16625. }
  16626. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16627. continue;
  16628. }
  16629. if (!mesh.isReady()) {
  16630. return false;
  16631. }
  16632. var mat = mesh.material;
  16633. if (mat) {
  16634. if (!mat.isReady(mesh)) {
  16635. return false;
  16636. }
  16637. }
  16638. }
  16639. return true;
  16640. };
  16641. Scene.prototype.resetCachedMaterial = function () {
  16642. this._cachedMaterial = null;
  16643. this._cachedEffect = null;
  16644. this._cachedVisibility = null;
  16645. };
  16646. Scene.prototype.registerBeforeRender = function (func) {
  16647. this.onBeforeRenderObservable.add(func);
  16648. };
  16649. Scene.prototype.unregisterBeforeRender = function (func) {
  16650. this.onBeforeRenderObservable.removeCallback(func);
  16651. };
  16652. Scene.prototype.registerAfterRender = function (func) {
  16653. this.onAfterRenderObservable.add(func);
  16654. };
  16655. Scene.prototype.unregisterAfterRender = function (func) {
  16656. this.onAfterRenderObservable.removeCallback(func);
  16657. };
  16658. Scene.prototype._addPendingData = function (data) {
  16659. this._pendingData.push(data);
  16660. };
  16661. Scene.prototype._removePendingData = function (data) {
  16662. var index = this._pendingData.indexOf(data);
  16663. if (index !== -1) {
  16664. this._pendingData.splice(index, 1);
  16665. }
  16666. };
  16667. Scene.prototype.getWaitingItemsCount = function () {
  16668. return this._pendingData.length;
  16669. };
  16670. /**
  16671. * Registers a function to be executed when the scene is ready.
  16672. * @param {Function} func - the function to be executed.
  16673. */
  16674. Scene.prototype.executeWhenReady = function (func) {
  16675. var _this = this;
  16676. this.onReadyObservable.add(func);
  16677. if (this._executeWhenReadyTimeoutId !== -1) {
  16678. return;
  16679. }
  16680. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16681. _this._checkIsReady();
  16682. }, 150);
  16683. };
  16684. Scene.prototype._checkIsReady = function () {
  16685. var _this = this;
  16686. if (this.isReady()) {
  16687. this.onReadyObservable.notifyObservers(this);
  16688. this.onReadyObservable.clear();
  16689. this._executeWhenReadyTimeoutId = -1;
  16690. return;
  16691. }
  16692. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16693. _this._checkIsReady();
  16694. }, 150);
  16695. };
  16696. // Animations
  16697. /**
  16698. * Will start the animation sequence of a given target
  16699. * @param target - the target
  16700. * @param {number} from - from which frame should animation start
  16701. * @param {number} to - till which frame should animation run.
  16702. * @param {boolean} [loop] - should the animation loop
  16703. * @param {number} [speedRatio] - the speed in which to run the animation
  16704. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16705. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16706. * @return {BABYLON.Animatable} the animatable object created for this animation
  16707. * @see BABYLON.Animatable
  16708. * @see http://doc.babylonjs.com/page.php?p=22081
  16709. */
  16710. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16711. if (speedRatio === void 0) { speedRatio = 1.0; }
  16712. if (from > to && speedRatio > 0) {
  16713. speedRatio *= -1;
  16714. }
  16715. this.stopAnimation(target);
  16716. if (!animatable) {
  16717. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16718. }
  16719. // Local animations
  16720. if (target.animations) {
  16721. animatable.appendAnimations(target, target.animations);
  16722. }
  16723. // Children animations
  16724. if (target.getAnimatables) {
  16725. var animatables = target.getAnimatables();
  16726. for (var index = 0; index < animatables.length; index++) {
  16727. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16728. }
  16729. }
  16730. animatable.reset();
  16731. return animatable;
  16732. };
  16733. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16734. if (speedRatio === undefined) {
  16735. speedRatio = 1.0;
  16736. }
  16737. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16738. return animatable;
  16739. };
  16740. Scene.prototype.getAnimatableByTarget = function (target) {
  16741. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16742. if (this._activeAnimatables[index].target === target) {
  16743. return this._activeAnimatables[index];
  16744. }
  16745. }
  16746. return null;
  16747. };
  16748. Object.defineProperty(Scene.prototype, "Animatables", {
  16749. get: function () {
  16750. return this._activeAnimatables;
  16751. },
  16752. enumerable: true,
  16753. configurable: true
  16754. });
  16755. /**
  16756. * Will stop the animation of the given target
  16757. * @param target - the target
  16758. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16759. * @see beginAnimation
  16760. */
  16761. Scene.prototype.stopAnimation = function (target, animationName) {
  16762. var animatable = this.getAnimatableByTarget(target);
  16763. if (animatable) {
  16764. animatable.stop(animationName);
  16765. }
  16766. };
  16767. Scene.prototype._animate = function () {
  16768. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16769. return;
  16770. }
  16771. // Getting time
  16772. var now = BABYLON.Tools.Now;
  16773. if (!this._animationTimeLast) {
  16774. if (this._pendingData.length > 0) {
  16775. return;
  16776. }
  16777. this._animationTimeLast = now;
  16778. }
  16779. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16780. this._animationTime += deltaTime;
  16781. this._animationTimeLast = now;
  16782. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16783. this._activeAnimatables[index]._animate(this._animationTime);
  16784. }
  16785. };
  16786. // Matrix
  16787. Scene.prototype.getViewMatrix = function () {
  16788. return this._viewMatrix;
  16789. };
  16790. Scene.prototype.getProjectionMatrix = function () {
  16791. return this._projectionMatrix;
  16792. };
  16793. Scene.prototype.getTransformMatrix = function () {
  16794. return this._transformMatrix;
  16795. };
  16796. Scene.prototype.setTransformMatrix = function (view, projection) {
  16797. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16798. return;
  16799. }
  16800. this._viewUpdateFlag = view.updateFlag;
  16801. this._projectionUpdateFlag = projection.updateFlag;
  16802. this._viewMatrix = view;
  16803. this._projectionMatrix = projection;
  16804. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16805. // Update frustum
  16806. if (!this._frustumPlanes) {
  16807. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16808. }
  16809. else {
  16810. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16811. }
  16812. if (this._sceneUbo.useUbo) {
  16813. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16814. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16815. this._sceneUbo.update();
  16816. }
  16817. };
  16818. Scene.prototype.getSceneUniformBuffer = function () {
  16819. return this._sceneUbo;
  16820. };
  16821. // Methods
  16822. Scene.prototype.getUniqueId = function () {
  16823. var result = this._uniqueIdCounter;
  16824. this._uniqueIdCounter++;
  16825. return result;
  16826. };
  16827. Scene.prototype.addMesh = function (newMesh) {
  16828. newMesh.uniqueId = this.getUniqueId();
  16829. var position = this.meshes.push(newMesh);
  16830. //notify the collision coordinator
  16831. if (this.collisionCoordinator) {
  16832. this.collisionCoordinator.onMeshAdded(newMesh);
  16833. }
  16834. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16835. };
  16836. Scene.prototype.removeMesh = function (toRemove) {
  16837. var index = this.meshes.indexOf(toRemove);
  16838. if (index !== -1) {
  16839. // Remove from the scene if mesh found
  16840. this.meshes.splice(index, 1);
  16841. }
  16842. //notify the collision coordinator
  16843. if (this.collisionCoordinator) {
  16844. this.collisionCoordinator.onMeshRemoved(toRemove);
  16845. }
  16846. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16847. return index;
  16848. };
  16849. Scene.prototype.removeSkeleton = function (toRemove) {
  16850. var index = this.skeletons.indexOf(toRemove);
  16851. if (index !== -1) {
  16852. // Remove from the scene if found
  16853. this.skeletons.splice(index, 1);
  16854. }
  16855. return index;
  16856. };
  16857. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16858. var index = this.morphTargetManagers.indexOf(toRemove);
  16859. if (index !== -1) {
  16860. // Remove from the scene if found
  16861. this.morphTargetManagers.splice(index, 1);
  16862. }
  16863. return index;
  16864. };
  16865. Scene.prototype.removeLight = function (toRemove) {
  16866. var index = this.lights.indexOf(toRemove);
  16867. if (index !== -1) {
  16868. // Remove from the scene if mesh found
  16869. this.lights.splice(index, 1);
  16870. this.sortLightsByPriority();
  16871. }
  16872. this.onLightRemovedObservable.notifyObservers(toRemove);
  16873. return index;
  16874. };
  16875. Scene.prototype.removeCamera = function (toRemove) {
  16876. var index = this.cameras.indexOf(toRemove);
  16877. if (index !== -1) {
  16878. // Remove from the scene if mesh found
  16879. this.cameras.splice(index, 1);
  16880. }
  16881. // Remove from activeCameras
  16882. var index2 = this.activeCameras.indexOf(toRemove);
  16883. if (index2 !== -1) {
  16884. // Remove from the scene if mesh found
  16885. this.activeCameras.splice(index2, 1);
  16886. }
  16887. // Reset the activeCamera
  16888. if (this.activeCamera === toRemove) {
  16889. if (this.cameras.length > 0) {
  16890. this.activeCamera = this.cameras[0];
  16891. }
  16892. else {
  16893. this.activeCamera = null;
  16894. }
  16895. }
  16896. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16897. return index;
  16898. };
  16899. Scene.prototype.addLight = function (newLight) {
  16900. newLight.uniqueId = this.getUniqueId();
  16901. this.lights.push(newLight);
  16902. this.sortLightsByPriority();
  16903. this.onNewLightAddedObservable.notifyObservers(newLight);
  16904. };
  16905. Scene.prototype.sortLightsByPriority = function () {
  16906. if (this.requireLightSorting) {
  16907. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16908. }
  16909. };
  16910. Scene.prototype.addCamera = function (newCamera) {
  16911. newCamera.uniqueId = this.getUniqueId();
  16912. var position = this.cameras.push(newCamera);
  16913. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16914. };
  16915. /**
  16916. * Switch active camera
  16917. * @param {Camera} newCamera - new active camera
  16918. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16919. */
  16920. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16921. if (attachControl === void 0) { attachControl = true; }
  16922. var canvas = this._engine.getRenderingCanvas();
  16923. this.activeCamera.detachControl(canvas);
  16924. this.activeCamera = newCamera;
  16925. if (attachControl) {
  16926. newCamera.attachControl(canvas);
  16927. }
  16928. };
  16929. /**
  16930. * sets the active camera of the scene using its ID
  16931. * @param {string} id - the camera's ID
  16932. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16933. * @see activeCamera
  16934. */
  16935. Scene.prototype.setActiveCameraByID = function (id) {
  16936. var camera = this.getCameraByID(id);
  16937. if (camera) {
  16938. this.activeCamera = camera;
  16939. return camera;
  16940. }
  16941. return null;
  16942. };
  16943. /**
  16944. * sets the active camera of the scene using its name
  16945. * @param {string} name - the camera's name
  16946. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16947. * @see activeCamera
  16948. */
  16949. Scene.prototype.setActiveCameraByName = function (name) {
  16950. var camera = this.getCameraByName(name);
  16951. if (camera) {
  16952. this.activeCamera = camera;
  16953. return camera;
  16954. }
  16955. return null;
  16956. };
  16957. /**
  16958. * get a material using its id
  16959. * @param {string} the material's ID
  16960. * @return {BABYLON.Material|null} the material or null if none found.
  16961. */
  16962. Scene.prototype.getMaterialByID = function (id) {
  16963. for (var index = 0; index < this.materials.length; index++) {
  16964. if (this.materials[index].id === id) {
  16965. return this.materials[index];
  16966. }
  16967. }
  16968. return null;
  16969. };
  16970. /**
  16971. * get a material using its name
  16972. * @param {string} the material's name
  16973. * @return {BABYLON.Material|null} the material or null if none found.
  16974. */
  16975. Scene.prototype.getMaterialByName = function (name) {
  16976. for (var index = 0; index < this.materials.length; index++) {
  16977. if (this.materials[index].name === name) {
  16978. return this.materials[index];
  16979. }
  16980. }
  16981. return null;
  16982. };
  16983. Scene.prototype.getLensFlareSystemByName = function (name) {
  16984. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16985. if (this.lensFlareSystems[index].name === name) {
  16986. return this.lensFlareSystems[index];
  16987. }
  16988. }
  16989. return null;
  16990. };
  16991. Scene.prototype.getLensFlareSystemByID = function (id) {
  16992. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16993. if (this.lensFlareSystems[index].id === id) {
  16994. return this.lensFlareSystems[index];
  16995. }
  16996. }
  16997. return null;
  16998. };
  16999. Scene.prototype.getCameraByID = function (id) {
  17000. for (var index = 0; index < this.cameras.length; index++) {
  17001. if (this.cameras[index].id === id) {
  17002. return this.cameras[index];
  17003. }
  17004. }
  17005. return null;
  17006. };
  17007. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17008. for (var index = 0; index < this.cameras.length; index++) {
  17009. if (this.cameras[index].uniqueId === uniqueId) {
  17010. return this.cameras[index];
  17011. }
  17012. }
  17013. return null;
  17014. };
  17015. /**
  17016. * get a camera using its name
  17017. * @param {string} the camera's name
  17018. * @return {BABYLON.Camera|null} the camera or null if none found.
  17019. */
  17020. Scene.prototype.getCameraByName = function (name) {
  17021. for (var index = 0; index < this.cameras.length; index++) {
  17022. if (this.cameras[index].name === name) {
  17023. return this.cameras[index];
  17024. }
  17025. }
  17026. return null;
  17027. };
  17028. /**
  17029. * get a bone using its id
  17030. * @param {string} the bone's id
  17031. * @return {BABYLON.Bone|null} the bone or null if not found
  17032. */
  17033. Scene.prototype.getBoneByID = function (id) {
  17034. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17035. var skeleton = this.skeletons[skeletonIndex];
  17036. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17037. if (skeleton.bones[boneIndex].id === id) {
  17038. return skeleton.bones[boneIndex];
  17039. }
  17040. }
  17041. }
  17042. return null;
  17043. };
  17044. /**
  17045. * get a bone using its id
  17046. * @param {string} the bone's name
  17047. * @return {BABYLON.Bone|null} the bone or null if not found
  17048. */
  17049. Scene.prototype.getBoneByName = function (name) {
  17050. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17051. var skeleton = this.skeletons[skeletonIndex];
  17052. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17053. if (skeleton.bones[boneIndex].name === name) {
  17054. return skeleton.bones[boneIndex];
  17055. }
  17056. }
  17057. }
  17058. return null;
  17059. };
  17060. /**
  17061. * get a light node using its name
  17062. * @param {string} the light's name
  17063. * @return {BABYLON.Light|null} the light or null if none found.
  17064. */
  17065. Scene.prototype.getLightByName = function (name) {
  17066. for (var index = 0; index < this.lights.length; index++) {
  17067. if (this.lights[index].name === name) {
  17068. return this.lights[index];
  17069. }
  17070. }
  17071. return null;
  17072. };
  17073. /**
  17074. * get a light node using its ID
  17075. * @param {string} the light's id
  17076. * @return {BABYLON.Light|null} the light or null if none found.
  17077. */
  17078. Scene.prototype.getLightByID = function (id) {
  17079. for (var index = 0; index < this.lights.length; index++) {
  17080. if (this.lights[index].id === id) {
  17081. return this.lights[index];
  17082. }
  17083. }
  17084. return null;
  17085. };
  17086. /**
  17087. * get a light node using its scene-generated unique ID
  17088. * @param {number} the light's unique id
  17089. * @return {BABYLON.Light|null} the light or null if none found.
  17090. */
  17091. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17092. for (var index = 0; index < this.lights.length; index++) {
  17093. if (this.lights[index].uniqueId === uniqueId) {
  17094. return this.lights[index];
  17095. }
  17096. }
  17097. return null;
  17098. };
  17099. /**
  17100. * get a particle system by id
  17101. * @param id {number} the particle system id
  17102. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17103. */
  17104. Scene.prototype.getParticleSystemByID = function (id) {
  17105. for (var index = 0; index < this.particleSystems.length; index++) {
  17106. if (this.particleSystems[index].id === id) {
  17107. return this.particleSystems[index];
  17108. }
  17109. }
  17110. return null;
  17111. };
  17112. /**
  17113. * get a geometry using its ID
  17114. * @param {string} the geometry's id
  17115. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17116. */
  17117. Scene.prototype.getGeometryByID = function (id) {
  17118. for (var index = 0; index < this._geometries.length; index++) {
  17119. if (this._geometries[index].id === id) {
  17120. return this._geometries[index];
  17121. }
  17122. }
  17123. return null;
  17124. };
  17125. /**
  17126. * add a new geometry to this scene.
  17127. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17128. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17129. * @return {boolean} was the geometry added or not
  17130. */
  17131. Scene.prototype.pushGeometry = function (geometry, force) {
  17132. if (!force && this.getGeometryByID(geometry.id)) {
  17133. return false;
  17134. }
  17135. this._geometries.push(geometry);
  17136. //notify the collision coordinator
  17137. if (this.collisionCoordinator) {
  17138. this.collisionCoordinator.onGeometryAdded(geometry);
  17139. }
  17140. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17141. return true;
  17142. };
  17143. /**
  17144. * Removes an existing geometry
  17145. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17146. * @return {boolean} was the geometry removed or not
  17147. */
  17148. Scene.prototype.removeGeometry = function (geometry) {
  17149. var index = this._geometries.indexOf(geometry);
  17150. if (index > -1) {
  17151. this._geometries.splice(index, 1);
  17152. //notify the collision coordinator
  17153. if (this.collisionCoordinator) {
  17154. this.collisionCoordinator.onGeometryDeleted(geometry);
  17155. }
  17156. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17157. return true;
  17158. }
  17159. return false;
  17160. };
  17161. Scene.prototype.getGeometries = function () {
  17162. return this._geometries;
  17163. };
  17164. /**
  17165. * Get the first added mesh found of a given ID
  17166. * @param {string} id - the id to search for
  17167. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17168. */
  17169. Scene.prototype.getMeshByID = function (id) {
  17170. for (var index = 0; index < this.meshes.length; index++) {
  17171. if (this.meshes[index].id === id) {
  17172. return this.meshes[index];
  17173. }
  17174. }
  17175. return null;
  17176. };
  17177. Scene.prototype.getMeshesByID = function (id) {
  17178. return this.meshes.filter(function (m) {
  17179. return m.id === id;
  17180. });
  17181. };
  17182. /**
  17183. * Get a mesh with its auto-generated unique id
  17184. * @param {number} uniqueId - the unique id to search for
  17185. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17186. */
  17187. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17188. for (var index = 0; index < this.meshes.length; index++) {
  17189. if (this.meshes[index].uniqueId === uniqueId) {
  17190. return this.meshes[index];
  17191. }
  17192. }
  17193. return null;
  17194. };
  17195. /**
  17196. * Get a the last added mesh found of a given ID
  17197. * @param {string} id - the id to search for
  17198. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17199. */
  17200. Scene.prototype.getLastMeshByID = function (id) {
  17201. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17202. if (this.meshes[index].id === id) {
  17203. return this.meshes[index];
  17204. }
  17205. }
  17206. return null;
  17207. };
  17208. /**
  17209. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17210. * @param {string} id - the id to search for
  17211. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17212. */
  17213. Scene.prototype.getLastEntryByID = function (id) {
  17214. var index;
  17215. for (index = this.meshes.length - 1; index >= 0; index--) {
  17216. if (this.meshes[index].id === id) {
  17217. return this.meshes[index];
  17218. }
  17219. }
  17220. for (index = this.cameras.length - 1; index >= 0; index--) {
  17221. if (this.cameras[index].id === id) {
  17222. return this.cameras[index];
  17223. }
  17224. }
  17225. for (index = this.lights.length - 1; index >= 0; index--) {
  17226. if (this.lights[index].id === id) {
  17227. return this.lights[index];
  17228. }
  17229. }
  17230. return null;
  17231. };
  17232. Scene.prototype.getNodeByID = function (id) {
  17233. var mesh = this.getMeshByID(id);
  17234. if (mesh) {
  17235. return mesh;
  17236. }
  17237. var light = this.getLightByID(id);
  17238. if (light) {
  17239. return light;
  17240. }
  17241. var camera = this.getCameraByID(id);
  17242. if (camera) {
  17243. return camera;
  17244. }
  17245. var bone = this.getBoneByID(id);
  17246. return bone;
  17247. };
  17248. Scene.prototype.getNodeByName = function (name) {
  17249. var mesh = this.getMeshByName(name);
  17250. if (mesh) {
  17251. return mesh;
  17252. }
  17253. var light = this.getLightByName(name);
  17254. if (light) {
  17255. return light;
  17256. }
  17257. var camera = this.getCameraByName(name);
  17258. if (camera) {
  17259. return camera;
  17260. }
  17261. var bone = this.getBoneByName(name);
  17262. return bone;
  17263. };
  17264. Scene.prototype.getMeshByName = function (name) {
  17265. for (var index = 0; index < this.meshes.length; index++) {
  17266. if (this.meshes[index].name === name) {
  17267. return this.meshes[index];
  17268. }
  17269. }
  17270. return null;
  17271. };
  17272. Scene.prototype.getSoundByName = function (name) {
  17273. var index;
  17274. if (BABYLON.AudioEngine) {
  17275. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17276. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17277. return this.mainSoundTrack.soundCollection[index];
  17278. }
  17279. }
  17280. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17281. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17282. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17283. return this.soundTracks[sdIndex].soundCollection[index];
  17284. }
  17285. }
  17286. }
  17287. }
  17288. return null;
  17289. };
  17290. Scene.prototype.getLastSkeletonByID = function (id) {
  17291. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17292. if (this.skeletons[index].id === id) {
  17293. return this.skeletons[index];
  17294. }
  17295. }
  17296. return null;
  17297. };
  17298. Scene.prototype.getSkeletonById = function (id) {
  17299. for (var index = 0; index < this.skeletons.length; index++) {
  17300. if (this.skeletons[index].id === id) {
  17301. return this.skeletons[index];
  17302. }
  17303. }
  17304. return null;
  17305. };
  17306. Scene.prototype.getSkeletonByName = function (name) {
  17307. for (var index = 0; index < this.skeletons.length; index++) {
  17308. if (this.skeletons[index].name === name) {
  17309. return this.skeletons[index];
  17310. }
  17311. }
  17312. return null;
  17313. };
  17314. Scene.prototype.getMorphTargetManagerById = function (id) {
  17315. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17316. if (this.morphTargetManagers[index].uniqueId === id) {
  17317. return this.morphTargetManagers[index];
  17318. }
  17319. }
  17320. return null;
  17321. };
  17322. Scene.prototype.isActiveMesh = function (mesh) {
  17323. return (this._activeMeshes.indexOf(mesh) !== -1);
  17324. };
  17325. /**
  17326. * Return a the first highlight layer of the scene with a given name.
  17327. * @param name The name of the highlight layer to look for.
  17328. * @return The highlight layer if found otherwise null.
  17329. */
  17330. Scene.prototype.getHighlightLayerByName = function (name) {
  17331. for (var index = 0; index < this.highlightLayers.length; index++) {
  17332. if (this.highlightLayers[index].name === name) {
  17333. return this.highlightLayers[index];
  17334. }
  17335. }
  17336. return null;
  17337. };
  17338. Object.defineProperty(Scene.prototype, "uid", {
  17339. /**
  17340. * Return a unique id as a string which can serve as an identifier for the scene
  17341. */
  17342. get: function () {
  17343. if (!this._uid) {
  17344. this._uid = BABYLON.Tools.RandomId();
  17345. }
  17346. return this._uid;
  17347. },
  17348. enumerable: true,
  17349. configurable: true
  17350. });
  17351. /**
  17352. * Add an externaly attached data from its key.
  17353. * This method call will fail and return false, if such key already exists.
  17354. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17355. * @param key the unique key that identifies the data
  17356. * @param data the data object to associate to the key for this Engine instance
  17357. * @return true if no such key were already present and the data was added successfully, false otherwise
  17358. */
  17359. Scene.prototype.addExternalData = function (key, data) {
  17360. if (!this._externalData) {
  17361. this._externalData = new BABYLON.StringDictionary();
  17362. }
  17363. return this._externalData.add(key, data);
  17364. };
  17365. /**
  17366. * Get an externaly attached data from its key
  17367. * @param key the unique key that identifies the data
  17368. * @return the associated data, if present (can be null), or undefined if not present
  17369. */
  17370. Scene.prototype.getExternalData = function (key) {
  17371. if (!this._externalData) {
  17372. return null;
  17373. }
  17374. return this._externalData.get(key);
  17375. };
  17376. /**
  17377. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17378. * @param key the unique key that identifies the data
  17379. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17380. * @return the associated data, can be null if the factory returned null.
  17381. */
  17382. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17383. if (!this._externalData) {
  17384. this._externalData = new BABYLON.StringDictionary();
  17385. }
  17386. return this._externalData.getOrAddWithFactory(key, factory);
  17387. };
  17388. /**
  17389. * Remove an externaly attached data from the Engine instance
  17390. * @param key the unique key that identifies the data
  17391. * @return true if the data was successfully removed, false if it doesn't exist
  17392. */
  17393. Scene.prototype.removeExternalData = function (key) {
  17394. return this._externalData.remove(key);
  17395. };
  17396. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17397. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17398. var material = subMesh.getMaterial();
  17399. if (mesh.showSubMeshesBoundingBox) {
  17400. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17401. }
  17402. if (material) {
  17403. // Render targets
  17404. if (material.getRenderTargetTextures) {
  17405. if (this._processedMaterials.indexOf(material) === -1) {
  17406. this._processedMaterials.push(material);
  17407. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17408. }
  17409. }
  17410. // Dispatch
  17411. this._activeIndices.addCount(subMesh.indexCount, false);
  17412. this._renderingManager.dispatch(subMesh);
  17413. }
  17414. }
  17415. };
  17416. Scene.prototype._isInIntermediateRendering = function () {
  17417. return this._intermediateRendering;
  17418. };
  17419. Scene.prototype._evaluateActiveMeshes = function () {
  17420. this.activeCamera._activeMeshes.reset();
  17421. this._activeMeshes.reset();
  17422. this._renderingManager.reset();
  17423. this._processedMaterials.reset();
  17424. this._activeParticleSystems.reset();
  17425. this._activeSkeletons.reset();
  17426. this._softwareSkinnedMeshes.reset();
  17427. if (this._boundingBoxRenderer) {
  17428. this._boundingBoxRenderer.reset();
  17429. }
  17430. // Meshes
  17431. var meshes;
  17432. var len;
  17433. if (this._selectionOctree) {
  17434. var selection = this._selectionOctree.select(this._frustumPlanes);
  17435. meshes = selection.data;
  17436. len = selection.length;
  17437. }
  17438. else {
  17439. len = this.meshes.length;
  17440. meshes = this.meshes;
  17441. }
  17442. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17443. var mesh = meshes[meshIndex];
  17444. if (mesh.isBlocked) {
  17445. continue;
  17446. }
  17447. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17448. if (!mesh.isReady() || !mesh.isEnabled()) {
  17449. continue;
  17450. }
  17451. mesh.computeWorldMatrix();
  17452. // Intersections
  17453. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17454. this._meshesForIntersections.pushNoDuplicate(mesh);
  17455. }
  17456. // Switch to current LOD
  17457. var meshLOD = mesh.getLOD(this.activeCamera);
  17458. if (!meshLOD) {
  17459. continue;
  17460. }
  17461. mesh._preActivate();
  17462. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17463. this._activeMeshes.push(mesh);
  17464. this.activeCamera._activeMeshes.push(mesh);
  17465. mesh._activate(this._renderId);
  17466. this._activeMesh(mesh, meshLOD);
  17467. }
  17468. }
  17469. // Particle systems
  17470. this._particlesDuration.beginMonitoring();
  17471. var beforeParticlesDate = BABYLON.Tools.Now;
  17472. if (this.particlesEnabled) {
  17473. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17474. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17475. var particleSystem = this.particleSystems[particleIndex];
  17476. if (!particleSystem.isStarted()) {
  17477. continue;
  17478. }
  17479. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17480. this._activeParticleSystems.push(particleSystem);
  17481. particleSystem.animate();
  17482. this._renderingManager.dispatchParticles(particleSystem);
  17483. }
  17484. }
  17485. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17486. }
  17487. this._particlesDuration.endMonitoring(false);
  17488. };
  17489. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17490. if (mesh.skeleton && this.skeletonsEnabled) {
  17491. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17492. mesh.skeleton.prepare();
  17493. }
  17494. if (!mesh.computeBonesUsingShaders) {
  17495. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17496. }
  17497. }
  17498. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17499. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17500. }
  17501. if (mesh && mesh.subMeshes) {
  17502. // Submeshes Octrees
  17503. var len;
  17504. var subMeshes;
  17505. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17506. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17507. len = intersections.length;
  17508. subMeshes = intersections.data;
  17509. }
  17510. else {
  17511. subMeshes = mesh.subMeshes;
  17512. len = subMeshes.length;
  17513. }
  17514. for (var subIndex = 0; subIndex < len; subIndex++) {
  17515. var subMesh = subMeshes[subIndex];
  17516. this._evaluateSubMesh(subMesh, mesh);
  17517. }
  17518. }
  17519. };
  17520. Scene.prototype.updateTransformMatrix = function (force) {
  17521. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17522. };
  17523. Scene.prototype._renderForCamera = function (camera) {
  17524. var engine = this._engine;
  17525. var startTime = BABYLON.Tools.Now;
  17526. this.activeCamera = camera;
  17527. if (!this.activeCamera)
  17528. throw new Error("Active camera not set");
  17529. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17530. // Viewport
  17531. engine.setViewport(this.activeCamera.viewport);
  17532. // Camera
  17533. this.resetCachedMaterial();
  17534. this._renderId++;
  17535. this.updateTransformMatrix();
  17536. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17537. // Meshes
  17538. this._evaluateActiveMeshesDuration.beginMonitoring();
  17539. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17540. this._evaluateActiveMeshes();
  17541. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17542. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17543. // Software skinning
  17544. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17545. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17546. mesh.applySkeleton(mesh.skeleton);
  17547. }
  17548. // Render targets
  17549. this._renderTargetsDuration.beginMonitoring();
  17550. var needsRestoreFrameBuffer = false;
  17551. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17552. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  17553. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  17554. }
  17555. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17556. this._intermediateRendering = true;
  17557. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17558. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17559. var renderTarget = this._renderTargets.data[renderIndex];
  17560. if (renderTarget._shouldRender()) {
  17561. this._renderId++;
  17562. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17563. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17564. }
  17565. }
  17566. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17567. this._intermediateRendering = false;
  17568. this._renderId++;
  17569. needsRestoreFrameBuffer = true; // Restore back buffer
  17570. }
  17571. // Render HighlightLayer Texture
  17572. var stencilState = this._engine.getStencilBuffer();
  17573. var renderhighlights = false;
  17574. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17575. this._intermediateRendering = true;
  17576. for (var i = 0; i < this.highlightLayers.length; i++) {
  17577. var highlightLayer = this.highlightLayers[i];
  17578. if (highlightLayer.shouldRender() &&
  17579. (!highlightLayer.camera ||
  17580. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17581. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17582. renderhighlights = true;
  17583. var renderTarget = highlightLayer._mainTexture;
  17584. if (renderTarget._shouldRender()) {
  17585. this._renderId++;
  17586. renderTarget.render(false, false);
  17587. needsRestoreFrameBuffer = true;
  17588. }
  17589. }
  17590. }
  17591. this._intermediateRendering = false;
  17592. this._renderId++;
  17593. }
  17594. if (needsRestoreFrameBuffer) {
  17595. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17596. }
  17597. this._renderTargetsDuration.endMonitoring(false);
  17598. // Prepare Frame
  17599. this.postProcessManager._prepareFrame();
  17600. this._renderDuration.beginMonitoring();
  17601. // Backgrounds
  17602. var layerIndex;
  17603. var layer;
  17604. if (this.layers.length) {
  17605. engine.setDepthBuffer(false);
  17606. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17607. layer = this.layers[layerIndex];
  17608. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17609. layer.render();
  17610. }
  17611. }
  17612. engine.setDepthBuffer(true);
  17613. }
  17614. // Render
  17615. BABYLON.Tools.StartPerformanceCounter("Main render");
  17616. // Activate HighlightLayer stencil
  17617. if (renderhighlights) {
  17618. this._engine.setStencilBuffer(true);
  17619. }
  17620. this._renderingManager.render(null, null, true, true);
  17621. // Restore HighlightLayer stencil
  17622. if (renderhighlights) {
  17623. this._engine.setStencilBuffer(stencilState);
  17624. }
  17625. BABYLON.Tools.EndPerformanceCounter("Main render");
  17626. // Bounding boxes
  17627. if (this._boundingBoxRenderer) {
  17628. this._boundingBoxRenderer.render();
  17629. }
  17630. // Lens flares
  17631. if (this.lensFlaresEnabled) {
  17632. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17633. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17634. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17635. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17636. lensFlareSystem.render();
  17637. }
  17638. }
  17639. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17640. }
  17641. // Foregrounds
  17642. if (this.layers.length) {
  17643. engine.setDepthBuffer(false);
  17644. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17645. layer = this.layers[layerIndex];
  17646. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17647. layer.render();
  17648. }
  17649. }
  17650. engine.setDepthBuffer(true);
  17651. }
  17652. // Highlight Layer
  17653. if (renderhighlights) {
  17654. engine.setDepthBuffer(false);
  17655. for (var i = 0; i < this.highlightLayers.length; i++) {
  17656. if (this.highlightLayers[i].shouldRender()) {
  17657. this.highlightLayers[i].render();
  17658. }
  17659. }
  17660. engine.setDepthBuffer(true);
  17661. }
  17662. this._renderDuration.endMonitoring(false);
  17663. // Finalize frame
  17664. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17665. // Update camera
  17666. this.activeCamera._updateFromScene();
  17667. // Reset some special arrays
  17668. this._renderTargets.reset();
  17669. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17670. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17671. };
  17672. Scene.prototype._processSubCameras = function (camera) {
  17673. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17674. this._renderForCamera(camera);
  17675. return;
  17676. }
  17677. // rig cameras
  17678. for (var index = 0; index < camera._rigCameras.length; index++) {
  17679. this._renderForCamera(camera._rigCameras[index]);
  17680. }
  17681. this.activeCamera = camera;
  17682. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17683. // Update camera
  17684. this.activeCamera._updateFromScene();
  17685. };
  17686. Scene.prototype._checkIntersections = function () {
  17687. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17688. var sourceMesh = this._meshesForIntersections.data[index];
  17689. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17690. var action = sourceMesh.actionManager.actions[actionIndex];
  17691. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17692. var parameters = action.getTriggerParameter();
  17693. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17694. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17695. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17696. if (areIntersecting && currentIntersectionInProgress === -1) {
  17697. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17698. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17699. sourceMesh._intersectionsInProgress.push(otherMesh);
  17700. }
  17701. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17702. sourceMesh._intersectionsInProgress.push(otherMesh);
  17703. }
  17704. }
  17705. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17706. //They intersected, and now they don't.
  17707. //is this trigger an exit trigger? execute an event.
  17708. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17709. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17710. }
  17711. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17712. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17713. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17714. }
  17715. }
  17716. }
  17717. }
  17718. }
  17719. };
  17720. Scene.prototype.render = function () {
  17721. if (this.isDisposed) {
  17722. return;
  17723. }
  17724. this._lastFrameDuration.beginMonitoring();
  17725. this._particlesDuration.fetchNewFrame();
  17726. this._spritesDuration.fetchNewFrame();
  17727. this._activeParticles.fetchNewFrame();
  17728. this._renderDuration.fetchNewFrame();
  17729. this._renderTargetsDuration.fetchNewFrame();
  17730. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17731. this._totalVertices.fetchNewFrame();
  17732. this._activeIndices.fetchNewFrame();
  17733. this._activeBones.fetchNewFrame();
  17734. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17735. this._meshesForIntersections.reset();
  17736. this.resetCachedMaterial();
  17737. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17738. // Actions
  17739. if (this.actionManager) {
  17740. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17741. }
  17742. //Simplification Queue
  17743. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17744. this.simplificationQueue.executeNext();
  17745. }
  17746. // Animations
  17747. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17748. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17749. this._animate();
  17750. // Physics
  17751. if (this._physicsEngine) {
  17752. BABYLON.Tools.StartPerformanceCounter("Physics");
  17753. this._physicsEngine._step(deltaTime / 1000.0);
  17754. BABYLON.Tools.EndPerformanceCounter("Physics");
  17755. }
  17756. // Before render
  17757. this.onBeforeRenderObservable.notifyObservers(this);
  17758. // Customs render targets
  17759. this._renderTargetsDuration.beginMonitoring();
  17760. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17761. var engine = this.getEngine();
  17762. var currentActiveCamera = this.activeCamera;
  17763. if (this.renderTargetsEnabled) {
  17764. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17765. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17766. var renderTarget = this.customRenderTargets[customIndex];
  17767. if (renderTarget._shouldRender()) {
  17768. this._renderId++;
  17769. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17770. if (!this.activeCamera)
  17771. throw new Error("Active camera not set");
  17772. // Viewport
  17773. engine.setViewport(this.activeCamera.viewport);
  17774. // Camera
  17775. this.updateTransformMatrix();
  17776. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17777. }
  17778. }
  17779. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17780. this._renderId++;
  17781. }
  17782. // Restore back buffer
  17783. if (this.customRenderTargets.length > 0) {
  17784. engine.restoreDefaultFramebuffer();
  17785. }
  17786. this._renderTargetsDuration.endMonitoring();
  17787. this.activeCamera = currentActiveCamera;
  17788. // Procedural textures
  17789. if (this.proceduralTexturesEnabled) {
  17790. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17791. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17792. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17793. if (proceduralTexture._shouldRender()) {
  17794. proceduralTexture.render();
  17795. }
  17796. }
  17797. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17798. }
  17799. // Clear
  17800. if (this.autoClearDepthAndStencil || this.autoClear) {
  17801. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17802. }
  17803. // Shadows
  17804. if (this.shadowsEnabled) {
  17805. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17806. var light = this.lights[lightIndex];
  17807. var shadowGenerator = light.getShadowGenerator();
  17808. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17809. var shadowMap = shadowGenerator.getShadowMap();
  17810. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17811. this._renderTargets.push(shadowMap);
  17812. }
  17813. }
  17814. }
  17815. }
  17816. // Depth renderer
  17817. if (this._depthRenderer) {
  17818. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17819. }
  17820. // Geometry renderer
  17821. if (this._geometryBufferRenderer) {
  17822. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17823. }
  17824. // RenderPipeline
  17825. if (this._postProcessRenderPipelineManager) {
  17826. this._postProcessRenderPipelineManager.update();
  17827. }
  17828. // Multi-cameras?
  17829. if (this.activeCameras.length > 0) {
  17830. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17831. if (cameraIndex > 0) {
  17832. this._engine.clear(null, false, true, true);
  17833. }
  17834. this._processSubCameras(this.activeCameras[cameraIndex]);
  17835. }
  17836. }
  17837. else {
  17838. if (!this.activeCamera) {
  17839. throw new Error("No camera defined");
  17840. }
  17841. this._processSubCameras(this.activeCamera);
  17842. }
  17843. // Intersection checks
  17844. this._checkIntersections();
  17845. // Update the audio listener attached to the camera
  17846. if (BABYLON.AudioEngine) {
  17847. this._updateAudioParameters();
  17848. }
  17849. // After render
  17850. if (this.afterRender) {
  17851. this.afterRender();
  17852. }
  17853. this.onAfterRenderObservable.notifyObservers(this);
  17854. // Cleaning
  17855. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17856. this._toBeDisposed.data[index].dispose();
  17857. this._toBeDisposed[index] = null;
  17858. }
  17859. this._toBeDisposed.reset();
  17860. if (this.dumpNextRenderTargets) {
  17861. this.dumpNextRenderTargets = false;
  17862. }
  17863. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17864. this._lastFrameDuration.endMonitoring();
  17865. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17866. this._totalLightsCounter.addCount(this.lights.length, true);
  17867. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17868. this._totalTexturesCounter.addCount(this.textures.length, true);
  17869. this._activeBones.addCount(0, true);
  17870. this._activeIndices.addCount(0, true);
  17871. this._activeParticles.addCount(0, true);
  17872. };
  17873. Scene.prototype._updateAudioParameters = function () {
  17874. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17875. return;
  17876. }
  17877. var listeningCamera;
  17878. var audioEngine = BABYLON.Engine.audioEngine;
  17879. if (this.activeCameras.length > 0) {
  17880. listeningCamera = this.activeCameras[0];
  17881. }
  17882. else {
  17883. listeningCamera = this.activeCamera;
  17884. }
  17885. if (listeningCamera && audioEngine.canUseWebAudio) {
  17886. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17887. // for VR cameras
  17888. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  17889. listeningCamera = listeningCamera.rigCameras[0];
  17890. }
  17891. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17892. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17893. cameraDirection.normalize();
  17894. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17895. var i;
  17896. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17897. var sound = this.mainSoundTrack.soundCollection[i];
  17898. if (sound.useCustomAttenuation) {
  17899. sound.updateDistanceFromListener();
  17900. }
  17901. }
  17902. for (i = 0; i < this.soundTracks.length; i++) {
  17903. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17904. sound = this.soundTracks[i].soundCollection[j];
  17905. if (sound.useCustomAttenuation) {
  17906. sound.updateDistanceFromListener();
  17907. }
  17908. }
  17909. }
  17910. }
  17911. };
  17912. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17913. // Audio
  17914. get: function () {
  17915. return this._audioEnabled;
  17916. },
  17917. set: function (value) {
  17918. this._audioEnabled = value;
  17919. if (BABYLON.AudioEngine) {
  17920. if (this._audioEnabled) {
  17921. this._enableAudio();
  17922. }
  17923. else {
  17924. this._disableAudio();
  17925. }
  17926. }
  17927. },
  17928. enumerable: true,
  17929. configurable: true
  17930. });
  17931. Scene.prototype._disableAudio = function () {
  17932. var i;
  17933. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17934. this.mainSoundTrack.soundCollection[i].pause();
  17935. }
  17936. for (i = 0; i < this.soundTracks.length; i++) {
  17937. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17938. this.soundTracks[i].soundCollection[j].pause();
  17939. }
  17940. }
  17941. };
  17942. Scene.prototype._enableAudio = function () {
  17943. var i;
  17944. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17945. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17946. this.mainSoundTrack.soundCollection[i].play();
  17947. }
  17948. }
  17949. for (i = 0; i < this.soundTracks.length; i++) {
  17950. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17951. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17952. this.soundTracks[i].soundCollection[j].play();
  17953. }
  17954. }
  17955. }
  17956. };
  17957. Object.defineProperty(Scene.prototype, "headphone", {
  17958. get: function () {
  17959. return this._headphone;
  17960. },
  17961. set: function (value) {
  17962. this._headphone = value;
  17963. if (BABYLON.AudioEngine) {
  17964. if (this._headphone) {
  17965. this._switchAudioModeForHeadphones();
  17966. }
  17967. else {
  17968. this._switchAudioModeForNormalSpeakers();
  17969. }
  17970. }
  17971. },
  17972. enumerable: true,
  17973. configurable: true
  17974. });
  17975. Scene.prototype._switchAudioModeForHeadphones = function () {
  17976. this.mainSoundTrack.switchPanningModelToHRTF();
  17977. for (var i = 0; i < this.soundTracks.length; i++) {
  17978. this.soundTracks[i].switchPanningModelToHRTF();
  17979. }
  17980. };
  17981. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17982. this.mainSoundTrack.switchPanningModelToEqualPower();
  17983. for (var i = 0; i < this.soundTracks.length; i++) {
  17984. this.soundTracks[i].switchPanningModelToEqualPower();
  17985. }
  17986. };
  17987. Scene.prototype.enableDepthRenderer = function () {
  17988. if (this._depthRenderer) {
  17989. return this._depthRenderer;
  17990. }
  17991. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17992. return this._depthRenderer;
  17993. };
  17994. Scene.prototype.disableDepthRenderer = function () {
  17995. if (!this._depthRenderer) {
  17996. return;
  17997. }
  17998. this._depthRenderer.dispose();
  17999. this._depthRenderer = null;
  18000. };
  18001. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18002. if (ratio === void 0) { ratio = 1; }
  18003. if (this._geometryBufferRenderer) {
  18004. return this._geometryBufferRenderer;
  18005. }
  18006. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18007. if (!this._geometryBufferRenderer.isSupported) {
  18008. this._geometryBufferRenderer = null;
  18009. }
  18010. return this._geometryBufferRenderer;
  18011. };
  18012. Scene.prototype.disableGeometryBufferRenderer = function () {
  18013. if (!this._geometryBufferRenderer) {
  18014. return;
  18015. }
  18016. this._geometryBufferRenderer.dispose();
  18017. this._geometryBufferRenderer = null;
  18018. };
  18019. Scene.prototype.freezeMaterials = function () {
  18020. for (var i = 0; i < this.materials.length; i++) {
  18021. this.materials[i].freeze();
  18022. }
  18023. };
  18024. Scene.prototype.unfreezeMaterials = function () {
  18025. for (var i = 0; i < this.materials.length; i++) {
  18026. this.materials[i].unfreeze();
  18027. }
  18028. };
  18029. Scene.prototype.dispose = function () {
  18030. this.beforeRender = null;
  18031. this.afterRender = null;
  18032. this.skeletons = [];
  18033. this.morphTargetManagers = [];
  18034. this.importedMeshesFiles = new Array();
  18035. if (this._depthRenderer) {
  18036. this._depthRenderer.dispose();
  18037. }
  18038. // Smart arrays
  18039. if (this.activeCamera) {
  18040. this.activeCamera._activeMeshes.dispose();
  18041. this.activeCamera = null;
  18042. }
  18043. this._activeMeshes.dispose();
  18044. this._renderingManager.dispose();
  18045. this._processedMaterials.dispose();
  18046. this._activeParticleSystems.dispose();
  18047. this._activeSkeletons.dispose();
  18048. this._softwareSkinnedMeshes.dispose();
  18049. if (this._boundingBoxRenderer) {
  18050. this._boundingBoxRenderer.dispose();
  18051. }
  18052. this._meshesForIntersections.dispose();
  18053. this._toBeDisposed.dispose();
  18054. // Debug layer
  18055. if (this._debugLayer) {
  18056. this._debugLayer.hide();
  18057. }
  18058. // Events
  18059. this.onDisposeObservable.notifyObservers(this);
  18060. this.onDisposeObservable.clear();
  18061. this.onBeforeRenderObservable.clear();
  18062. this.onAfterRenderObservable.clear();
  18063. this.detachControl();
  18064. // Release sounds & sounds tracks
  18065. if (BABYLON.AudioEngine) {
  18066. this.disposeSounds();
  18067. }
  18068. // Detach cameras
  18069. var canvas = this._engine.getRenderingCanvas();
  18070. var index;
  18071. for (index = 0; index < this.cameras.length; index++) {
  18072. this.cameras[index].detachControl(canvas);
  18073. }
  18074. // Release lights
  18075. while (this.lights.length) {
  18076. this.lights[0].dispose();
  18077. }
  18078. // Release meshes
  18079. while (this.meshes.length) {
  18080. this.meshes[0].dispose(true);
  18081. }
  18082. // Release cameras
  18083. while (this.cameras.length) {
  18084. this.cameras[0].dispose();
  18085. }
  18086. // Release materials
  18087. while (this.materials.length) {
  18088. this.materials[0].dispose();
  18089. }
  18090. // Release particles
  18091. while (this.particleSystems.length) {
  18092. this.particleSystems[0].dispose();
  18093. }
  18094. // Release sprites
  18095. while (this.spriteManagers.length) {
  18096. this.spriteManagers[0].dispose();
  18097. }
  18098. // Release layers
  18099. while (this.layers.length) {
  18100. this.layers[0].dispose();
  18101. }
  18102. while (this.highlightLayers.length) {
  18103. this.highlightLayers[0].dispose();
  18104. }
  18105. // Release textures
  18106. while (this.textures.length) {
  18107. this.textures[0].dispose();
  18108. }
  18109. // Release UBO
  18110. this._sceneUbo.dispose();
  18111. // Post-processes
  18112. this.postProcessManager.dispose();
  18113. // Physics
  18114. if (this._physicsEngine) {
  18115. this.disablePhysicsEngine();
  18116. }
  18117. // Remove from engine
  18118. index = this._engine.scenes.indexOf(this);
  18119. if (index > -1) {
  18120. this._engine.scenes.splice(index, 1);
  18121. }
  18122. this._engine.wipeCaches();
  18123. this._engine = null;
  18124. };
  18125. Object.defineProperty(Scene.prototype, "isDisposed", {
  18126. get: function () {
  18127. return !this._engine;
  18128. },
  18129. enumerable: true,
  18130. configurable: true
  18131. });
  18132. // Release sounds & sounds tracks
  18133. Scene.prototype.disposeSounds = function () {
  18134. this.mainSoundTrack.dispose();
  18135. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18136. this.soundTracks[scIndex].dispose();
  18137. }
  18138. };
  18139. // Octrees
  18140. Scene.prototype.getWorldExtends = function () {
  18141. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18142. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18143. for (var index = 0; index < this.meshes.length; index++) {
  18144. var mesh = this.meshes[index];
  18145. mesh.computeWorldMatrix(true);
  18146. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18147. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18148. BABYLON.Tools.CheckExtends(minBox, min, max);
  18149. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18150. }
  18151. return {
  18152. min: min,
  18153. max: max
  18154. };
  18155. };
  18156. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18157. if (maxCapacity === void 0) { maxCapacity = 64; }
  18158. if (maxDepth === void 0) { maxDepth = 2; }
  18159. if (!this._selectionOctree) {
  18160. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18161. }
  18162. var worldExtends = this.getWorldExtends();
  18163. // Update octree
  18164. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18165. return this._selectionOctree;
  18166. };
  18167. // Picking
  18168. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18169. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18170. var engine = this._engine;
  18171. if (!camera) {
  18172. if (!this.activeCamera)
  18173. throw new Error("Active camera not set");
  18174. camera = this.activeCamera;
  18175. }
  18176. var cameraViewport = camera.viewport;
  18177. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18178. // Moving coordinates to local viewport world
  18179. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18180. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18181. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18182. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18183. };
  18184. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18185. if (!BABYLON.PickingInfo) {
  18186. return null;
  18187. }
  18188. var engine = this._engine;
  18189. if (!camera) {
  18190. if (!this.activeCamera)
  18191. throw new Error("Active camera not set");
  18192. camera = this.activeCamera;
  18193. }
  18194. var cameraViewport = camera.viewport;
  18195. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18196. var identity = BABYLON.Matrix.Identity();
  18197. // Moving coordinates to local viewport world
  18198. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18199. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18200. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18201. };
  18202. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18203. if (!BABYLON.PickingInfo) {
  18204. return null;
  18205. }
  18206. var pickingInfo = null;
  18207. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18208. var mesh = this.meshes[meshIndex];
  18209. if (predicate) {
  18210. if (!predicate(mesh)) {
  18211. continue;
  18212. }
  18213. }
  18214. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18215. continue;
  18216. }
  18217. var world = mesh.getWorldMatrix();
  18218. var ray = rayFunction(world);
  18219. var result = mesh.intersects(ray, fastCheck);
  18220. if (!result || !result.hit)
  18221. continue;
  18222. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18223. continue;
  18224. pickingInfo = result;
  18225. if (fastCheck) {
  18226. break;
  18227. }
  18228. }
  18229. return pickingInfo || new BABYLON.PickingInfo();
  18230. };
  18231. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18232. if (!BABYLON.PickingInfo) {
  18233. return null;
  18234. }
  18235. var pickingInfos = new Array();
  18236. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18237. var mesh = this.meshes[meshIndex];
  18238. if (predicate) {
  18239. if (!predicate(mesh)) {
  18240. continue;
  18241. }
  18242. }
  18243. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18244. continue;
  18245. }
  18246. var world = mesh.getWorldMatrix();
  18247. var ray = rayFunction(world);
  18248. var result = mesh.intersects(ray, false);
  18249. if (!result || !result.hit)
  18250. continue;
  18251. pickingInfos.push(result);
  18252. }
  18253. return pickingInfos;
  18254. };
  18255. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18256. if (!BABYLON.PickingInfo) {
  18257. return null;
  18258. }
  18259. var pickingInfo = null;
  18260. camera = camera || this.activeCamera;
  18261. if (this.spriteManagers.length > 0) {
  18262. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18263. var spriteManager = this.spriteManagers[spriteIndex];
  18264. if (!spriteManager.isPickable) {
  18265. continue;
  18266. }
  18267. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18268. if (!result || !result.hit)
  18269. continue;
  18270. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18271. continue;
  18272. pickingInfo = result;
  18273. if (fastCheck) {
  18274. break;
  18275. }
  18276. }
  18277. }
  18278. return pickingInfo || new BABYLON.PickingInfo();
  18279. };
  18280. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18281. /// <param name="x">X position on screen</param>
  18282. /// <param name="y">Y position on screen</param>
  18283. /// <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>
  18284. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18285. /// <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>
  18286. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18287. var _this = this;
  18288. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18289. };
  18290. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18291. /// <param name="x">X position on screen</param>
  18292. /// <param name="y">Y position on screen</param>
  18293. /// <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>
  18294. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18295. /// <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>
  18296. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18297. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18298. };
  18299. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18300. var _this = this;
  18301. return this._internalPick(function (world) {
  18302. if (!_this._pickWithRayInverseMatrix) {
  18303. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18304. }
  18305. world.invertToRef(_this._pickWithRayInverseMatrix);
  18306. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18307. }, predicate, fastCheck);
  18308. };
  18309. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18310. /// <param name="x">X position on screen</param>
  18311. /// <param name="y">Y position on screen</param>
  18312. /// <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>
  18313. /// <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>
  18314. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18315. var _this = this;
  18316. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18317. };
  18318. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18319. /// <param name="ray">Ray to use</param>
  18320. /// <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>
  18321. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18322. var _this = this;
  18323. return this._internalMultiPick(function (world) {
  18324. if (!_this._pickWithRayInverseMatrix) {
  18325. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18326. }
  18327. world.invertToRef(_this._pickWithRayInverseMatrix);
  18328. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18329. }, predicate);
  18330. };
  18331. Scene.prototype.setPointerOverMesh = function (mesh) {
  18332. if (this._pointerOverMesh === mesh) {
  18333. return;
  18334. }
  18335. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18336. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18337. }
  18338. this._pointerOverMesh = mesh;
  18339. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18340. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18341. }
  18342. };
  18343. Scene.prototype.getPointerOverMesh = function () {
  18344. return this._pointerOverMesh;
  18345. };
  18346. Scene.prototype.setPointerOverSprite = function (sprite) {
  18347. if (this._pointerOverSprite === sprite) {
  18348. return;
  18349. }
  18350. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18351. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18352. }
  18353. this._pointerOverSprite = sprite;
  18354. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18355. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18356. }
  18357. };
  18358. Scene.prototype.getPointerOverSprite = function () {
  18359. return this._pointerOverSprite;
  18360. };
  18361. // Physics
  18362. Scene.prototype.getPhysicsEngine = function () {
  18363. return this._physicsEngine;
  18364. };
  18365. /**
  18366. * Enables physics to the current scene
  18367. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18368. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18369. * @return {boolean} was the physics engine initialized
  18370. */
  18371. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18372. if (this._physicsEngine) {
  18373. return true;
  18374. }
  18375. try {
  18376. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18377. return true;
  18378. }
  18379. catch (e) {
  18380. BABYLON.Tools.Error(e.message);
  18381. return false;
  18382. }
  18383. };
  18384. Scene.prototype.disablePhysicsEngine = function () {
  18385. if (!this._physicsEngine) {
  18386. return;
  18387. }
  18388. this._physicsEngine.dispose();
  18389. this._physicsEngine = undefined;
  18390. };
  18391. Scene.prototype.isPhysicsEnabled = function () {
  18392. return this._physicsEngine !== undefined;
  18393. };
  18394. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18395. var mesh = compound.parts[0].mesh;
  18396. mesh.physicsImpostor.dispose();
  18397. mesh.physicsImpostor = null;
  18398. };
  18399. // Misc.
  18400. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18401. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18402. // Light
  18403. if (this.lights.length === 0) {
  18404. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18405. }
  18406. // Camera
  18407. if (!this.activeCamera) {
  18408. var worldExtends = this.getWorldExtends();
  18409. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18410. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18411. var camera;
  18412. var radius = worldSize.length() * 1.5;
  18413. if (createArcRotateCamera) {
  18414. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18415. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18416. arcRotateCamera.wheelPrecision = 100 / radius;
  18417. camera = arcRotateCamera;
  18418. }
  18419. else {
  18420. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18421. freeCamera.setTarget(worldCenter);
  18422. camera = freeCamera;
  18423. }
  18424. camera.minZ = radius * 0.01;
  18425. camera.maxZ = radius * 100;
  18426. camera.speed = radius * 0.2;
  18427. this.activeCamera = camera;
  18428. }
  18429. };
  18430. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18431. if (pbr === void 0) { pbr = false; }
  18432. if (environmentTexture) {
  18433. this.environmentTexture = environmentTexture;
  18434. }
  18435. if (!this.environmentTexture) {
  18436. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18437. return;
  18438. }
  18439. if (!this.environmentTexture) {
  18440. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18441. return;
  18442. }
  18443. // Skybox
  18444. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18445. if (pbr) {
  18446. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18447. hdrSkyboxMaterial.backFaceCulling = false;
  18448. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18449. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18450. hdrSkyboxMaterial.microSurface = 1.0;
  18451. hdrSkyboxMaterial.disableLighting = true;
  18452. hdrSkybox.infiniteDistance = true;
  18453. hdrSkybox.material = hdrSkyboxMaterial;
  18454. }
  18455. else {
  18456. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18457. skyboxMaterial.backFaceCulling = false;
  18458. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18459. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18460. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18461. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18462. skyboxMaterial.disableLighting = true;
  18463. hdrSkybox.infiniteDistance = true;
  18464. hdrSkybox.material = skyboxMaterial;
  18465. }
  18466. return hdrSkybox;
  18467. };
  18468. // Tags
  18469. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18470. if (tagsQuery === undefined) {
  18471. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18472. return list;
  18473. }
  18474. var listByTags = [];
  18475. forEach = forEach || (function (item) { return; });
  18476. for (var i in list) {
  18477. var item = list[i];
  18478. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18479. listByTags.push(item);
  18480. forEach(item);
  18481. }
  18482. }
  18483. return listByTags;
  18484. };
  18485. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18486. return this._getByTags(this.meshes, tagsQuery, forEach);
  18487. };
  18488. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18489. return this._getByTags(this.cameras, tagsQuery, forEach);
  18490. };
  18491. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18492. return this._getByTags(this.lights, tagsQuery, forEach);
  18493. };
  18494. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18495. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18496. };
  18497. /**
  18498. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18499. * This allowed control for front to back rendering or reversly depending of the special needs.
  18500. *
  18501. * @param renderingGroupId The rendering group id corresponding to its index
  18502. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18503. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18504. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18505. */
  18506. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18507. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18508. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18509. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18510. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18511. };
  18512. /**
  18513. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18514. *
  18515. * @param renderingGroupId The rendering group id corresponding to its index
  18516. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18517. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18518. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18519. */
  18520. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18521. if (depth === void 0) { depth = true; }
  18522. if (stencil === void 0) { stencil = true; }
  18523. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18524. };
  18525. /**
  18526. * Will flag all materials as dirty to trigger new shader compilation
  18527. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18528. */
  18529. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18530. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18531. var material = _a[_i];
  18532. if (predicate && !predicate(material)) {
  18533. continue;
  18534. }
  18535. material.markAsDirty(flag);
  18536. }
  18537. };
  18538. return Scene;
  18539. }());
  18540. // Statics
  18541. Scene._FOGMODE_NONE = 0;
  18542. Scene._FOGMODE_EXP = 1;
  18543. Scene._FOGMODE_EXP2 = 2;
  18544. Scene._FOGMODE_LINEAR = 3;
  18545. Scene.MinDeltaTime = 1.0;
  18546. Scene.MaxDeltaTime = 1000.0;
  18547. Scene.DragMovementThreshold = 10; // in pixels
  18548. Scene.LongPressDelay = 500; // in milliseconds
  18549. Scene.DoubleClickDelay = 300; // in milliseconds
  18550. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18551. BABYLON.Scene = Scene;
  18552. })(BABYLON || (BABYLON = {}));
  18553. //# sourceMappingURL=babylon.scene.js.map
  18554. var BABYLON;
  18555. (function (BABYLON) {
  18556. var Buffer = (function () {
  18557. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18558. if (engine instanceof BABYLON.Mesh) {
  18559. this._engine = engine.getScene().getEngine();
  18560. }
  18561. else {
  18562. this._engine = engine;
  18563. }
  18564. this._updatable = updatable;
  18565. this._data = data;
  18566. this._strideSize = stride;
  18567. if (!postponeInternalCreation) {
  18568. this.create();
  18569. }
  18570. this._instanced = instanced;
  18571. this._instanceDivisor = instanced ? 1 : 0;
  18572. }
  18573. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18574. // a lot of these parameters are ignored as they are overriden by the buffer
  18575. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18576. };
  18577. // Properties
  18578. Buffer.prototype.isUpdatable = function () {
  18579. return this._updatable;
  18580. };
  18581. Buffer.prototype.getData = function () {
  18582. return this._data;
  18583. };
  18584. Buffer.prototype.getBuffer = function () {
  18585. return this._buffer;
  18586. };
  18587. Buffer.prototype.getStrideSize = function () {
  18588. return this._strideSize;
  18589. };
  18590. Buffer.prototype.getIsInstanced = function () {
  18591. return this._instanced;
  18592. };
  18593. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  18594. get: function () {
  18595. return this._instanceDivisor;
  18596. },
  18597. set: function (value) {
  18598. this._instanceDivisor = value;
  18599. if (value == 0) {
  18600. this._instanced = false;
  18601. }
  18602. else {
  18603. this._instanced = true;
  18604. }
  18605. },
  18606. enumerable: true,
  18607. configurable: true
  18608. });
  18609. // Methods
  18610. Buffer.prototype.create = function (data) {
  18611. if (!data && this._buffer) {
  18612. return; // nothing to do
  18613. }
  18614. data = data || this._data;
  18615. if (!this._buffer) {
  18616. if (this._updatable) {
  18617. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18618. this._data = data;
  18619. }
  18620. else {
  18621. this._buffer = this._engine.createVertexBuffer(data);
  18622. }
  18623. }
  18624. else if (this._updatable) {
  18625. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18626. this._data = data;
  18627. }
  18628. };
  18629. Buffer.prototype.update = function (data) {
  18630. this.create(data);
  18631. };
  18632. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18633. if (!this._buffer) {
  18634. return;
  18635. }
  18636. if (this._updatable) {
  18637. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18638. this._data = null;
  18639. }
  18640. };
  18641. Buffer.prototype.dispose = function () {
  18642. if (!this._buffer) {
  18643. return;
  18644. }
  18645. if (this._engine._releaseBuffer(this._buffer)) {
  18646. this._buffer = null;
  18647. }
  18648. };
  18649. return Buffer;
  18650. }());
  18651. BABYLON.Buffer = Buffer;
  18652. })(BABYLON || (BABYLON = {}));
  18653. //# sourceMappingURL=babylon.buffer.js.map
  18654. var BABYLON;
  18655. (function (BABYLON) {
  18656. var VertexBuffer = (function () {
  18657. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18658. if (!stride) {
  18659. // Deduce stride from kind
  18660. switch (kind) {
  18661. case VertexBuffer.PositionKind:
  18662. stride = 3;
  18663. break;
  18664. case VertexBuffer.NormalKind:
  18665. stride = 3;
  18666. break;
  18667. case VertexBuffer.UVKind:
  18668. case VertexBuffer.UV2Kind:
  18669. case VertexBuffer.UV3Kind:
  18670. case VertexBuffer.UV4Kind:
  18671. case VertexBuffer.UV5Kind:
  18672. case VertexBuffer.UV6Kind:
  18673. stride = 2;
  18674. break;
  18675. case VertexBuffer.TangentKind:
  18676. case VertexBuffer.ColorKind:
  18677. stride = 4;
  18678. break;
  18679. case VertexBuffer.MatricesIndicesKind:
  18680. case VertexBuffer.MatricesIndicesExtraKind:
  18681. stride = 4;
  18682. break;
  18683. case VertexBuffer.MatricesWeightsKind:
  18684. case VertexBuffer.MatricesWeightsExtraKind:
  18685. stride = 4;
  18686. break;
  18687. }
  18688. }
  18689. if (data instanceof BABYLON.Buffer) {
  18690. if (!stride) {
  18691. stride = data.getStrideSize();
  18692. }
  18693. this._buffer = data;
  18694. this._ownsBuffer = false;
  18695. }
  18696. else {
  18697. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18698. this._ownsBuffer = true;
  18699. }
  18700. this._stride = stride;
  18701. this._offset = offset ? offset : 0;
  18702. this._size = size ? size : stride;
  18703. this._kind = kind;
  18704. }
  18705. /**
  18706. * Returns the kind of the VertexBuffer (string).
  18707. */
  18708. VertexBuffer.prototype.getKind = function () {
  18709. return this._kind;
  18710. };
  18711. // Properties
  18712. /**
  18713. * Boolean : is the VertexBuffer updatable ?
  18714. */
  18715. VertexBuffer.prototype.isUpdatable = function () {
  18716. return this._buffer.isUpdatable();
  18717. };
  18718. /**
  18719. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18720. */
  18721. VertexBuffer.prototype.getData = function () {
  18722. return this._buffer.getData();
  18723. };
  18724. /**
  18725. * Returns the WebGLBuffer associated to the VertexBuffer.
  18726. */
  18727. VertexBuffer.prototype.getBuffer = function () {
  18728. return this._buffer.getBuffer();
  18729. };
  18730. /**
  18731. * Returns the stride of the VertexBuffer (integer).
  18732. */
  18733. VertexBuffer.prototype.getStrideSize = function () {
  18734. return this._stride;
  18735. };
  18736. /**
  18737. * Returns the offset (integer).
  18738. */
  18739. VertexBuffer.prototype.getOffset = function () {
  18740. return this._offset;
  18741. };
  18742. /**
  18743. * Returns the VertexBuffer total size (integer).
  18744. */
  18745. VertexBuffer.prototype.getSize = function () {
  18746. return this._size;
  18747. };
  18748. /**
  18749. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18750. */
  18751. VertexBuffer.prototype.getIsInstanced = function () {
  18752. return this._buffer.getIsInstanced();
  18753. };
  18754. /**
  18755. * Returns the instancing divisor, zero for non-instanced (integer).
  18756. */
  18757. VertexBuffer.prototype.getInstanceDivisor = function () {
  18758. return this._buffer.instanceDivisor;
  18759. };
  18760. // Methods
  18761. /**
  18762. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18763. * Returns the created WebGLBuffer.
  18764. */
  18765. VertexBuffer.prototype.create = function (data) {
  18766. return this._buffer.create(data);
  18767. };
  18768. /**
  18769. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18770. * Returns the updated WebGLBuffer.
  18771. */
  18772. VertexBuffer.prototype.update = function (data) {
  18773. return this._buffer.update(data);
  18774. };
  18775. /**
  18776. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18777. * Returns the directly updated WebGLBuffer.
  18778. */
  18779. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18780. return this._buffer.updateDirectly(data, offset);
  18781. };
  18782. /**
  18783. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18784. */
  18785. VertexBuffer.prototype.dispose = function () {
  18786. if (this._ownsBuffer) {
  18787. this._buffer.dispose();
  18788. }
  18789. };
  18790. Object.defineProperty(VertexBuffer, "PositionKind", {
  18791. get: function () {
  18792. return VertexBuffer._PositionKind;
  18793. },
  18794. enumerable: true,
  18795. configurable: true
  18796. });
  18797. Object.defineProperty(VertexBuffer, "NormalKind", {
  18798. get: function () {
  18799. return VertexBuffer._NormalKind;
  18800. },
  18801. enumerable: true,
  18802. configurable: true
  18803. });
  18804. Object.defineProperty(VertexBuffer, "TangentKind", {
  18805. get: function () {
  18806. return VertexBuffer._TangentKind;
  18807. },
  18808. enumerable: true,
  18809. configurable: true
  18810. });
  18811. Object.defineProperty(VertexBuffer, "UVKind", {
  18812. get: function () {
  18813. return VertexBuffer._UVKind;
  18814. },
  18815. enumerable: true,
  18816. configurable: true
  18817. });
  18818. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18819. get: function () {
  18820. return VertexBuffer._UV2Kind;
  18821. },
  18822. enumerable: true,
  18823. configurable: true
  18824. });
  18825. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18826. get: function () {
  18827. return VertexBuffer._UV3Kind;
  18828. },
  18829. enumerable: true,
  18830. configurable: true
  18831. });
  18832. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18833. get: function () {
  18834. return VertexBuffer._UV4Kind;
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18840. get: function () {
  18841. return VertexBuffer._UV5Kind;
  18842. },
  18843. enumerable: true,
  18844. configurable: true
  18845. });
  18846. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18847. get: function () {
  18848. return VertexBuffer._UV6Kind;
  18849. },
  18850. enumerable: true,
  18851. configurable: true
  18852. });
  18853. Object.defineProperty(VertexBuffer, "ColorKind", {
  18854. get: function () {
  18855. return VertexBuffer._ColorKind;
  18856. },
  18857. enumerable: true,
  18858. configurable: true
  18859. });
  18860. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18861. get: function () {
  18862. return VertexBuffer._MatricesIndicesKind;
  18863. },
  18864. enumerable: true,
  18865. configurable: true
  18866. });
  18867. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18868. get: function () {
  18869. return VertexBuffer._MatricesWeightsKind;
  18870. },
  18871. enumerable: true,
  18872. configurable: true
  18873. });
  18874. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18875. get: function () {
  18876. return VertexBuffer._MatricesIndicesExtraKind;
  18877. },
  18878. enumerable: true,
  18879. configurable: true
  18880. });
  18881. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18882. get: function () {
  18883. return VertexBuffer._MatricesWeightsExtraKind;
  18884. },
  18885. enumerable: true,
  18886. configurable: true
  18887. });
  18888. return VertexBuffer;
  18889. }());
  18890. // Enums
  18891. VertexBuffer._PositionKind = "position";
  18892. VertexBuffer._NormalKind = "normal";
  18893. VertexBuffer._TangentKind = "tangent";
  18894. VertexBuffer._UVKind = "uv";
  18895. VertexBuffer._UV2Kind = "uv2";
  18896. VertexBuffer._UV3Kind = "uv3";
  18897. VertexBuffer._UV4Kind = "uv4";
  18898. VertexBuffer._UV5Kind = "uv5";
  18899. VertexBuffer._UV6Kind = "uv6";
  18900. VertexBuffer._ColorKind = "color";
  18901. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18902. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18903. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18904. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18905. BABYLON.VertexBuffer = VertexBuffer;
  18906. })(BABYLON || (BABYLON = {}));
  18907. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18908. var BABYLON;
  18909. (function (BABYLON) {
  18910. var BaseTexture = (function () {
  18911. function BaseTexture(scene) {
  18912. this._hasAlpha = false;
  18913. this.getAlphaFromRGB = false;
  18914. this.level = 1;
  18915. this.coordinatesIndex = 0;
  18916. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18917. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18918. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18919. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18920. this.isCube = false;
  18921. this.isRenderTarget = false;
  18922. this.animations = new Array();
  18923. /**
  18924. * An event triggered when the texture is disposed.
  18925. * @type {BABYLON.Observable}
  18926. */
  18927. this.onDisposeObservable = new BABYLON.Observable();
  18928. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18929. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18930. this._scene.textures.push(this);
  18931. this._uid = null;
  18932. }
  18933. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18934. get: function () {
  18935. return this._hasAlpha;
  18936. },
  18937. set: function (value) {
  18938. if (this._hasAlpha === value) {
  18939. return;
  18940. }
  18941. this._hasAlpha = value;
  18942. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18943. },
  18944. enumerable: true,
  18945. configurable: true
  18946. });
  18947. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18948. get: function () {
  18949. return this._coordinatesMode;
  18950. },
  18951. set: function (value) {
  18952. if (this._coordinatesMode === value) {
  18953. return;
  18954. }
  18955. this._coordinatesMode = value;
  18956. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18957. },
  18958. enumerable: true,
  18959. configurable: true
  18960. });
  18961. Object.defineProperty(BaseTexture.prototype, "uid", {
  18962. get: function () {
  18963. if (!this._uid) {
  18964. this._uid = BABYLON.Tools.RandomId();
  18965. }
  18966. return this._uid;
  18967. },
  18968. enumerable: true,
  18969. configurable: true
  18970. });
  18971. BaseTexture.prototype.toString = function () {
  18972. return this.name;
  18973. };
  18974. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18975. set: function (callback) {
  18976. if (this._onDisposeObserver) {
  18977. this.onDisposeObservable.remove(this._onDisposeObserver);
  18978. }
  18979. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18980. },
  18981. enumerable: true,
  18982. configurable: true
  18983. });
  18984. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18985. get: function () {
  18986. return true;
  18987. },
  18988. enumerable: true,
  18989. configurable: true
  18990. });
  18991. BaseTexture.prototype.getScene = function () {
  18992. return this._scene;
  18993. };
  18994. BaseTexture.prototype.getTextureMatrix = function () {
  18995. return null;
  18996. };
  18997. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18998. return null;
  18999. };
  19000. BaseTexture.prototype.getInternalTexture = function () {
  19001. return this._texture;
  19002. };
  19003. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  19004. return !this.isBlocking || this.isReady();
  19005. };
  19006. BaseTexture.prototype.isReady = function () {
  19007. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19008. this.delayLoad();
  19009. return false;
  19010. }
  19011. if (this._texture) {
  19012. return this._texture.isReady;
  19013. }
  19014. return false;
  19015. };
  19016. BaseTexture.prototype.getSize = function () {
  19017. if (this._texture._width) {
  19018. return new BABYLON.Size(this._texture._width, this._texture._height);
  19019. }
  19020. if (this._texture._size) {
  19021. return new BABYLON.Size(this._texture._size, this._texture._size);
  19022. }
  19023. return BABYLON.Size.Zero();
  19024. };
  19025. BaseTexture.prototype.getBaseSize = function () {
  19026. if (!this.isReady() || !this._texture)
  19027. return BABYLON.Size.Zero();
  19028. if (this._texture._size) {
  19029. return new BABYLON.Size(this._texture._size, this._texture._size);
  19030. }
  19031. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19032. };
  19033. BaseTexture.prototype.scale = function (ratio) {
  19034. };
  19035. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19036. get: function () {
  19037. return false;
  19038. },
  19039. enumerable: true,
  19040. configurable: true
  19041. });
  19042. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19043. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19044. for (var index = 0; index < texturesCache.length; index++) {
  19045. var texturesCacheEntry = texturesCache[index];
  19046. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19047. texturesCache.splice(index, 1);
  19048. return;
  19049. }
  19050. }
  19051. };
  19052. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19053. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19054. for (var index = 0; index < texturesCache.length; index++) {
  19055. var texturesCacheEntry = texturesCache[index];
  19056. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19057. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19058. texturesCacheEntry.references++;
  19059. return texturesCacheEntry;
  19060. }
  19061. }
  19062. }
  19063. return null;
  19064. };
  19065. BaseTexture.prototype.delayLoad = function () {
  19066. };
  19067. BaseTexture.prototype.clone = function () {
  19068. return null;
  19069. };
  19070. Object.defineProperty(BaseTexture.prototype, "textureType", {
  19071. get: function () {
  19072. if (!this._texture) {
  19073. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19074. }
  19075. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19076. },
  19077. enumerable: true,
  19078. configurable: true
  19079. });
  19080. BaseTexture.prototype.readPixels = function (faceIndex, lodIndex) {
  19081. if (faceIndex === void 0) { faceIndex = 0; }
  19082. if (lodIndex === void 0) { lodIndex = 0; }
  19083. if (!this._texture) {
  19084. return null;
  19085. }
  19086. var size = this.getSize();
  19087. var engine = this.getScene().getEngine();
  19088. if (this._texture.isCube) {
  19089. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex, lodIndex);
  19090. }
  19091. return engine._readTexturePixels(this._texture, size.width, size.height, -1, lodIndex);
  19092. };
  19093. BaseTexture.prototype.releaseInternalTexture = function () {
  19094. if (this._texture) {
  19095. this._scene.getEngine().releaseInternalTexture(this._texture);
  19096. delete this._texture;
  19097. }
  19098. };
  19099. BaseTexture.prototype.dispose = function () {
  19100. // Animations
  19101. this.getScene().stopAnimation(this);
  19102. // Remove from scene
  19103. this._scene._removePendingData(this);
  19104. var index = this._scene.textures.indexOf(this);
  19105. if (index >= 0) {
  19106. this._scene.textures.splice(index, 1);
  19107. }
  19108. if (this._texture === undefined) {
  19109. return;
  19110. }
  19111. // Release
  19112. this.releaseInternalTexture();
  19113. // Callback
  19114. this.onDisposeObservable.notifyObservers(this);
  19115. this.onDisposeObservable.clear();
  19116. };
  19117. BaseTexture.prototype.serialize = function () {
  19118. if (!this.name) {
  19119. return null;
  19120. }
  19121. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19122. // Animations
  19123. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19124. return serializationObject;
  19125. };
  19126. BaseTexture.WhenAllReady = function (textures, onLoad) {
  19127. var numReady = 0;
  19128. var _loop_1 = function () {
  19129. texture = textures[i];
  19130. if (texture.isReady()) {
  19131. if (++numReady === textures.length) {
  19132. onLoad();
  19133. }
  19134. }
  19135. else {
  19136. observable = texture.onLoadObservable;
  19137. var callback_1 = function () {
  19138. observable.removeCallback(callback_1);
  19139. if (++numReady === textures.length) {
  19140. onLoad();
  19141. }
  19142. };
  19143. observable.add(callback_1);
  19144. }
  19145. };
  19146. var texture, observable;
  19147. for (var i = 0; i < textures.length; i++) {
  19148. _loop_1();
  19149. }
  19150. };
  19151. return BaseTexture;
  19152. }());
  19153. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19154. __decorate([
  19155. BABYLON.serialize()
  19156. ], BaseTexture.prototype, "name", void 0);
  19157. __decorate([
  19158. BABYLON.serialize("hasAlpha")
  19159. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19160. __decorate([
  19161. BABYLON.serialize()
  19162. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19163. __decorate([
  19164. BABYLON.serialize()
  19165. ], BaseTexture.prototype, "level", void 0);
  19166. __decorate([
  19167. BABYLON.serialize()
  19168. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19169. __decorate([
  19170. BABYLON.serialize("coordinatesMode")
  19171. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19172. __decorate([
  19173. BABYLON.serialize()
  19174. ], BaseTexture.prototype, "wrapU", void 0);
  19175. __decorate([
  19176. BABYLON.serialize()
  19177. ], BaseTexture.prototype, "wrapV", void 0);
  19178. __decorate([
  19179. BABYLON.serialize()
  19180. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19181. __decorate([
  19182. BABYLON.serialize()
  19183. ], BaseTexture.prototype, "isCube", void 0);
  19184. __decorate([
  19185. BABYLON.serialize()
  19186. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19187. BABYLON.BaseTexture = BaseTexture;
  19188. })(BABYLON || (BABYLON = {}));
  19189. //# sourceMappingURL=babylon.baseTexture.js.map
  19190. var BABYLON;
  19191. (function (BABYLON) {
  19192. var Texture = (function (_super) {
  19193. __extends(Texture, _super);
  19194. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19195. if (noMipmap === void 0) { noMipmap = false; }
  19196. if (invertY === void 0) { invertY = true; }
  19197. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19198. if (onLoad === void 0) { onLoad = null; }
  19199. if (onError === void 0) { onError = null; }
  19200. if (buffer === void 0) { buffer = null; }
  19201. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19202. var _this = _super.call(this, scene) || this;
  19203. _this.uOffset = 0;
  19204. _this.vOffset = 0;
  19205. _this.uScale = 1.0;
  19206. _this.vScale = 1.0;
  19207. _this.uAng = 0;
  19208. _this.vAng = 0;
  19209. _this.wAng = 0;
  19210. _this._isBlocking = true;
  19211. _this.name = url;
  19212. _this.url = url;
  19213. _this._noMipmap = noMipmap;
  19214. _this._invertY = invertY;
  19215. _this._samplingMode = samplingMode;
  19216. _this._buffer = buffer;
  19217. _this._deleteBuffer = deleteBuffer;
  19218. _this._format = format;
  19219. scene = _this.getScene();
  19220. var load = function () {
  19221. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19222. _this.onLoadObservable.notifyObservers(_this);
  19223. }
  19224. if (onLoad) {
  19225. onLoad();
  19226. }
  19227. if (!_this.isBlocking) {
  19228. scene.resetCachedMaterial();
  19229. }
  19230. };
  19231. if (!url) {
  19232. _this._delayedOnLoad = load;
  19233. _this._delayedOnError = onError;
  19234. return _this;
  19235. }
  19236. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19237. if (!_this._texture) {
  19238. if (!scene.useDelayedTextureLoading) {
  19239. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19240. if (deleteBuffer) {
  19241. delete _this._buffer;
  19242. }
  19243. }
  19244. else {
  19245. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19246. _this._delayedOnLoad = load;
  19247. _this._delayedOnError = onError;
  19248. }
  19249. }
  19250. else {
  19251. if (_this._texture.isReady) {
  19252. BABYLON.Tools.SetImmediate(function () { return load(); });
  19253. }
  19254. else {
  19255. _this._texture.onLoadedCallbacks.push(load);
  19256. }
  19257. }
  19258. return _this;
  19259. }
  19260. Object.defineProperty(Texture.prototype, "noMipmap", {
  19261. get: function () {
  19262. return this._noMipmap;
  19263. },
  19264. enumerable: true,
  19265. configurable: true
  19266. });
  19267. Object.defineProperty(Texture.prototype, "isBlocking", {
  19268. get: function () {
  19269. return this._isBlocking;
  19270. },
  19271. set: function (value) {
  19272. this._isBlocking = value;
  19273. },
  19274. enumerable: true,
  19275. configurable: true
  19276. });
  19277. Texture.prototype.updateURL = function (url) {
  19278. this.url = url;
  19279. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19280. this.delayLoad();
  19281. };
  19282. Texture.prototype.delayLoad = function () {
  19283. var _this = this;
  19284. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19285. return;
  19286. }
  19287. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19288. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19289. if (!this._texture) {
  19290. 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);
  19291. if (this._deleteBuffer) {
  19292. delete this._buffer;
  19293. }
  19294. }
  19295. else {
  19296. if (this._texture.isReady) {
  19297. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19298. }
  19299. else {
  19300. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19301. }
  19302. }
  19303. };
  19304. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19305. if (!this._texture) {
  19306. return;
  19307. }
  19308. this._samplingMode = samplingMode;
  19309. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19310. };
  19311. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19312. x *= this.uScale;
  19313. y *= this.vScale;
  19314. x -= 0.5 * this.uScale;
  19315. y -= 0.5 * this.vScale;
  19316. z -= 0.5;
  19317. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19318. t.x += 0.5 * this.uScale + this.uOffset;
  19319. t.y += 0.5 * this.vScale + this.vOffset;
  19320. t.z += 0.5;
  19321. };
  19322. Texture.prototype.getTextureMatrix = function () {
  19323. if (this.uOffset === this._cachedUOffset &&
  19324. this.vOffset === this._cachedVOffset &&
  19325. this.uScale === this._cachedUScale &&
  19326. this.vScale === this._cachedVScale &&
  19327. this.uAng === this._cachedUAng &&
  19328. this.vAng === this._cachedVAng &&
  19329. this.wAng === this._cachedWAng) {
  19330. return this._cachedTextureMatrix;
  19331. }
  19332. this._cachedUOffset = this.uOffset;
  19333. this._cachedVOffset = this.vOffset;
  19334. this._cachedUScale = this.uScale;
  19335. this._cachedVScale = this.vScale;
  19336. this._cachedUAng = this.uAng;
  19337. this._cachedVAng = this.vAng;
  19338. this._cachedWAng = this.wAng;
  19339. if (!this._cachedTextureMatrix) {
  19340. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19341. this._rowGenerationMatrix = new BABYLON.Matrix();
  19342. this._t0 = BABYLON.Vector3.Zero();
  19343. this._t1 = BABYLON.Vector3.Zero();
  19344. this._t2 = BABYLON.Vector3.Zero();
  19345. }
  19346. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19347. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19348. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19349. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19350. this._t1.subtractInPlace(this._t0);
  19351. this._t2.subtractInPlace(this._t0);
  19352. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19353. this._cachedTextureMatrix.m[0] = this._t1.x;
  19354. this._cachedTextureMatrix.m[1] = this._t1.y;
  19355. this._cachedTextureMatrix.m[2] = this._t1.z;
  19356. this._cachedTextureMatrix.m[4] = this._t2.x;
  19357. this._cachedTextureMatrix.m[5] = this._t2.y;
  19358. this._cachedTextureMatrix.m[6] = this._t2.z;
  19359. this._cachedTextureMatrix.m[8] = this._t0.x;
  19360. this._cachedTextureMatrix.m[9] = this._t0.y;
  19361. this._cachedTextureMatrix.m[10] = this._t0.z;
  19362. return this._cachedTextureMatrix;
  19363. };
  19364. Texture.prototype.getReflectionTextureMatrix = function () {
  19365. if (this.uOffset === this._cachedUOffset &&
  19366. this.vOffset === this._cachedVOffset &&
  19367. this.uScale === this._cachedUScale &&
  19368. this.vScale === this._cachedVScale &&
  19369. this.coordinatesMode === this._cachedCoordinatesMode) {
  19370. return this._cachedTextureMatrix;
  19371. }
  19372. if (!this._cachedTextureMatrix) {
  19373. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19374. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19375. }
  19376. this._cachedCoordinatesMode = this.coordinatesMode;
  19377. switch (this.coordinatesMode) {
  19378. case Texture.PLANAR_MODE:
  19379. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19380. this._cachedTextureMatrix[0] = this.uScale;
  19381. this._cachedTextureMatrix[5] = this.vScale;
  19382. this._cachedTextureMatrix[12] = this.uOffset;
  19383. this._cachedTextureMatrix[13] = this.vOffset;
  19384. break;
  19385. case Texture.PROJECTION_MODE:
  19386. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19387. this._projectionModeMatrix.m[0] = 0.5;
  19388. this._projectionModeMatrix.m[5] = -0.5;
  19389. this._projectionModeMatrix.m[10] = 0.0;
  19390. this._projectionModeMatrix.m[12] = 0.5;
  19391. this._projectionModeMatrix.m[13] = 0.5;
  19392. this._projectionModeMatrix.m[14] = 1.0;
  19393. this._projectionModeMatrix.m[15] = 1.0;
  19394. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19395. break;
  19396. default:
  19397. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19398. break;
  19399. }
  19400. return this._cachedTextureMatrix;
  19401. };
  19402. Texture.prototype.clone = function () {
  19403. var _this = this;
  19404. return BABYLON.SerializationHelper.Clone(function () {
  19405. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19406. }, this);
  19407. };
  19408. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19409. get: function () {
  19410. if (!this._onLoadObservable) {
  19411. this._onLoadObservable = new BABYLON.Observable();
  19412. }
  19413. return this._onLoadObservable;
  19414. },
  19415. enumerable: true,
  19416. configurable: true
  19417. });
  19418. // Statics
  19419. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19420. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19421. if (onLoad === void 0) { onLoad = null; }
  19422. if (onError === void 0) { onError = null; }
  19423. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19424. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19425. };
  19426. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19427. if (parsedTexture.customType) {
  19428. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19429. // Update Sampling Mode
  19430. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19431. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19432. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19433. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19434. }
  19435. }
  19436. return parsedCustomTexture;
  19437. }
  19438. if (parsedTexture.isCube) {
  19439. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19440. }
  19441. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19442. return null;
  19443. }
  19444. var texture = BABYLON.SerializationHelper.Parse(function () {
  19445. if (parsedTexture.mirrorPlane) {
  19446. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19447. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19448. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19449. return mirrorTexture;
  19450. }
  19451. else if (parsedTexture.isRenderTarget) {
  19452. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19453. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19454. return renderTargetTexture;
  19455. }
  19456. else {
  19457. var texture;
  19458. if (parsedTexture.base64String) {
  19459. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19460. }
  19461. else {
  19462. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19463. }
  19464. return texture;
  19465. }
  19466. }, parsedTexture, scene);
  19467. // Update Sampling Mode
  19468. if (parsedTexture.samplingMode) {
  19469. var sampling = parsedTexture.samplingMode;
  19470. if (texture._samplingMode !== sampling) {
  19471. texture.updateSamplingMode(sampling);
  19472. }
  19473. }
  19474. // Animations
  19475. if (parsedTexture.animations) {
  19476. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19477. var parsedAnimation = parsedTexture.animations[animationIndex];
  19478. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19479. }
  19480. }
  19481. return texture;
  19482. };
  19483. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19484. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19485. if (noMipmap === void 0) { noMipmap = false; }
  19486. if (invertY === void 0) { invertY = true; }
  19487. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19488. if (onLoad === void 0) { onLoad = null; }
  19489. if (onError === void 0) { onError = null; }
  19490. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19491. if (name.substr(0, 5) !== "data:") {
  19492. name = "data:" + name;
  19493. }
  19494. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19495. };
  19496. return Texture;
  19497. }(BABYLON.BaseTexture));
  19498. // Constants
  19499. Texture.NEAREST_SAMPLINGMODE = 1;
  19500. Texture.BILINEAR_SAMPLINGMODE = 2;
  19501. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19502. Texture.EXPLICIT_MODE = 0;
  19503. Texture.SPHERICAL_MODE = 1;
  19504. Texture.PLANAR_MODE = 2;
  19505. Texture.CUBIC_MODE = 3;
  19506. Texture.PROJECTION_MODE = 4;
  19507. Texture.SKYBOX_MODE = 5;
  19508. Texture.INVCUBIC_MODE = 6;
  19509. Texture.EQUIRECTANGULAR_MODE = 7;
  19510. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19511. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19512. Texture.CLAMP_ADDRESSMODE = 0;
  19513. Texture.WRAP_ADDRESSMODE = 1;
  19514. Texture.MIRROR_ADDRESSMODE = 2;
  19515. __decorate([
  19516. BABYLON.serialize()
  19517. ], Texture.prototype, "url", void 0);
  19518. __decorate([
  19519. BABYLON.serialize()
  19520. ], Texture.prototype, "uOffset", void 0);
  19521. __decorate([
  19522. BABYLON.serialize()
  19523. ], Texture.prototype, "vOffset", void 0);
  19524. __decorate([
  19525. BABYLON.serialize()
  19526. ], Texture.prototype, "uScale", void 0);
  19527. __decorate([
  19528. BABYLON.serialize()
  19529. ], Texture.prototype, "vScale", void 0);
  19530. __decorate([
  19531. BABYLON.serialize()
  19532. ], Texture.prototype, "uAng", void 0);
  19533. __decorate([
  19534. BABYLON.serialize()
  19535. ], Texture.prototype, "vAng", void 0);
  19536. __decorate([
  19537. BABYLON.serialize()
  19538. ], Texture.prototype, "wAng", void 0);
  19539. __decorate([
  19540. BABYLON.serialize()
  19541. ], Texture.prototype, "isBlocking", null);
  19542. BABYLON.Texture = Texture;
  19543. })(BABYLON || (BABYLON = {}));
  19544. //# sourceMappingURL=babylon.texture.js.map
  19545. var BABYLON;
  19546. (function (BABYLON) {
  19547. var _InstancesBatch = (function () {
  19548. function _InstancesBatch() {
  19549. this.mustReturn = false;
  19550. this.visibleInstances = new Array();
  19551. this.renderSelf = new Array();
  19552. }
  19553. return _InstancesBatch;
  19554. }());
  19555. BABYLON._InstancesBatch = _InstancesBatch;
  19556. var Mesh = (function (_super) {
  19557. __extends(Mesh, _super);
  19558. /**
  19559. * @constructor
  19560. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19561. * @param {Scene} scene The scene to add this mesh to.
  19562. * @param {Node} parent The parent of this mesh, if it has one
  19563. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19564. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19565. * When false, achieved by calling a clone(), also passing False.
  19566. * This will make creation of children, recursive.
  19567. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19568. */
  19569. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19570. if (parent === void 0) { parent = null; }
  19571. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19572. var _this = _super.call(this, name, scene) || this;
  19573. // Events
  19574. /**
  19575. * An event triggered before rendering the mesh
  19576. * @type {BABYLON.Observable}
  19577. */
  19578. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19579. /**
  19580. * An event triggered after rendering the mesh
  19581. * @type {BABYLON.Observable}
  19582. */
  19583. _this.onAfterRenderObservable = new BABYLON.Observable();
  19584. /**
  19585. * An event triggered before drawing the mesh
  19586. * @type {BABYLON.Observable}
  19587. */
  19588. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19589. // Members
  19590. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19591. _this.instances = new Array();
  19592. _this._LODLevels = new Array();
  19593. _this._visibleInstances = {};
  19594. _this._renderIdForInstances = new Array();
  19595. _this._batchCache = new _InstancesBatch();
  19596. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19597. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19598. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19599. // Will be used to save a source mesh reference, If any
  19600. _this._source = null;
  19601. if (source) {
  19602. // Source mesh
  19603. _this._source = source;
  19604. // Geometry
  19605. if (source._geometry) {
  19606. source._geometry.applyToMesh(_this);
  19607. }
  19608. // Deep copy
  19609. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19610. // Parent
  19611. _this.parent = source.parent;
  19612. // Pivot
  19613. _this.setPivotMatrix(source.getPivotMatrix());
  19614. _this.id = name + "." + source.id;
  19615. // Material
  19616. _this.material = source.material;
  19617. var index;
  19618. if (!doNotCloneChildren) {
  19619. // Children
  19620. for (index = 0; index < scene.meshes.length; index++) {
  19621. var mesh = scene.meshes[index];
  19622. if (mesh.parent === source) {
  19623. // doNotCloneChildren is always going to be False
  19624. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19625. }
  19626. }
  19627. }
  19628. // Physics clone
  19629. var physicsEngine = _this.getScene().getPhysicsEngine();
  19630. if (clonePhysicsImpostor && physicsEngine) {
  19631. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19632. if (impostor) {
  19633. _this.physicsImpostor = impostor.clone(_this);
  19634. }
  19635. }
  19636. // Particles
  19637. for (index = 0; index < scene.particleSystems.length; index++) {
  19638. var system = scene.particleSystems[index];
  19639. if (system.emitter === source) {
  19640. system.clone(system.name, _this);
  19641. }
  19642. }
  19643. _this.computeWorldMatrix(true);
  19644. }
  19645. // Parent
  19646. if (parent !== null) {
  19647. _this.parent = parent;
  19648. }
  19649. return _this;
  19650. }
  19651. Object.defineProperty(Mesh, "FRONTSIDE", {
  19652. /**
  19653. * Mesh side orientation : usually the external or front surface
  19654. */
  19655. get: function () {
  19656. return Mesh._FRONTSIDE;
  19657. },
  19658. enumerable: true,
  19659. configurable: true
  19660. });
  19661. Object.defineProperty(Mesh, "BACKSIDE", {
  19662. /**
  19663. * Mesh side orientation : usually the internal or back surface
  19664. */
  19665. get: function () {
  19666. return Mesh._BACKSIDE;
  19667. },
  19668. enumerable: true,
  19669. configurable: true
  19670. });
  19671. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19672. /**
  19673. * Mesh side orientation : both internal and external or front and back surfaces
  19674. */
  19675. get: function () {
  19676. return Mesh._DOUBLESIDE;
  19677. },
  19678. enumerable: true,
  19679. configurable: true
  19680. });
  19681. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19682. /**
  19683. * Mesh side orientation : by default, `FRONTSIDE`
  19684. */
  19685. get: function () {
  19686. return Mesh._DEFAULTSIDE;
  19687. },
  19688. enumerable: true,
  19689. configurable: true
  19690. });
  19691. Object.defineProperty(Mesh, "NO_CAP", {
  19692. /**
  19693. * Mesh cap setting : no cap
  19694. */
  19695. get: function () {
  19696. return Mesh._NO_CAP;
  19697. },
  19698. enumerable: true,
  19699. configurable: true
  19700. });
  19701. Object.defineProperty(Mesh, "CAP_START", {
  19702. /**
  19703. * Mesh cap setting : one cap at the beginning of the mesh
  19704. */
  19705. get: function () {
  19706. return Mesh._CAP_START;
  19707. },
  19708. enumerable: true,
  19709. configurable: true
  19710. });
  19711. Object.defineProperty(Mesh, "CAP_END", {
  19712. /**
  19713. * Mesh cap setting : one cap at the end of the mesh
  19714. */
  19715. get: function () {
  19716. return Mesh._CAP_END;
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Object.defineProperty(Mesh, "CAP_ALL", {
  19722. /**
  19723. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19724. */
  19725. get: function () {
  19726. return Mesh._CAP_ALL;
  19727. },
  19728. enumerable: true,
  19729. configurable: true
  19730. });
  19731. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19732. set: function (callback) {
  19733. if (this._onBeforeDrawObserver) {
  19734. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19735. }
  19736. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19742. get: function () {
  19743. return this._morphTargetManager;
  19744. },
  19745. set: function (value) {
  19746. if (this._morphTargetManager === value) {
  19747. return;
  19748. }
  19749. this._morphTargetManager = value;
  19750. this._syncGeometryWithMorphTargetManager();
  19751. },
  19752. enumerable: true,
  19753. configurable: true
  19754. });
  19755. Object.defineProperty(Mesh.prototype, "source", {
  19756. get: function () {
  19757. return this._source;
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. // Methods
  19763. /**
  19764. * Returns the string "Mesh".
  19765. */
  19766. Mesh.prototype.getClassName = function () {
  19767. return "Mesh";
  19768. };
  19769. /**
  19770. * Returns a string.
  19771. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19772. */
  19773. Mesh.prototype.toString = function (fullDetails) {
  19774. var ret = _super.prototype.toString.call(this, fullDetails);
  19775. ret += ", n vertices: " + this.getTotalVertices();
  19776. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19777. if (this.animations) {
  19778. for (var i = 0; i < this.animations.length; i++) {
  19779. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19780. }
  19781. }
  19782. if (fullDetails) {
  19783. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19784. }
  19785. return ret;
  19786. };
  19787. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19788. /**
  19789. * True if the mesh has some Levels Of Details (LOD).
  19790. * Returns a boolean.
  19791. */
  19792. get: function () {
  19793. return this._LODLevels.length > 0;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Mesh.prototype._sortLODLevels = function () {
  19799. this._LODLevels.sort(function (a, b) {
  19800. if (a.distance < b.distance) {
  19801. return 1;
  19802. }
  19803. if (a.distance > b.distance) {
  19804. return -1;
  19805. }
  19806. return 0;
  19807. });
  19808. };
  19809. /**
  19810. * Add a mesh as LOD level triggered at the given distance.
  19811. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19812. * @param {number} distance The distance from the center of the object to show this level
  19813. * @param {Mesh} mesh The mesh to be added as LOD level
  19814. * @return {Mesh} This mesh (for chaining)
  19815. */
  19816. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19817. if (mesh && mesh._masterMesh) {
  19818. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19819. return this;
  19820. }
  19821. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19822. this._LODLevels.push(level);
  19823. if (mesh) {
  19824. mesh._masterMesh = this;
  19825. }
  19826. this._sortLODLevels();
  19827. return this;
  19828. };
  19829. /**
  19830. * Returns the LOD level mesh at the passed distance or null if not found.
  19831. * It is related to the method `addLODLevel(distance, mesh)`.
  19832. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19833. * Returns an object Mesh or `null`.
  19834. */
  19835. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19836. for (var index = 0; index < this._LODLevels.length; index++) {
  19837. var level = this._LODLevels[index];
  19838. if (level.distance === distance) {
  19839. return level.mesh;
  19840. }
  19841. }
  19842. return null;
  19843. };
  19844. /**
  19845. * Remove a mesh from the LOD array
  19846. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19847. * @param {Mesh} mesh The mesh to be removed.
  19848. * @return {Mesh} This mesh (for chaining)
  19849. */
  19850. Mesh.prototype.removeLODLevel = function (mesh) {
  19851. for (var index = 0; index < this._LODLevels.length; index++) {
  19852. if (this._LODLevels[index].mesh === mesh) {
  19853. this._LODLevels.splice(index, 1);
  19854. if (mesh) {
  19855. mesh._masterMesh = null;
  19856. }
  19857. }
  19858. }
  19859. this._sortLODLevels();
  19860. return this;
  19861. };
  19862. /**
  19863. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19864. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19865. */
  19866. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19867. if (!this._LODLevels || this._LODLevels.length === 0) {
  19868. return this;
  19869. }
  19870. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19871. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19872. if (this.onLODLevelSelection) {
  19873. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19874. }
  19875. return this;
  19876. }
  19877. for (var index = 0; index < this._LODLevels.length; index++) {
  19878. var level = this._LODLevels[index];
  19879. if (level.distance < distanceToCamera) {
  19880. if (level.mesh) {
  19881. level.mesh._preActivate();
  19882. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19883. }
  19884. if (this.onLODLevelSelection) {
  19885. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19886. }
  19887. return level.mesh;
  19888. }
  19889. }
  19890. if (this.onLODLevelSelection) {
  19891. this.onLODLevelSelection(distanceToCamera, this, this);
  19892. }
  19893. return this;
  19894. };
  19895. Object.defineProperty(Mesh.prototype, "geometry", {
  19896. /**
  19897. * Returns the mesh internal Geometry object.
  19898. */
  19899. get: function () {
  19900. return this._geometry;
  19901. },
  19902. enumerable: true,
  19903. configurable: true
  19904. });
  19905. /**
  19906. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19907. */
  19908. Mesh.prototype.getTotalVertices = function () {
  19909. if (!this._geometry) {
  19910. return 0;
  19911. }
  19912. return this._geometry.getTotalVertices();
  19913. };
  19914. /**
  19915. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19916. * 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.
  19917. * You can force the copy with forceCopy === true
  19918. * Returns null if the mesh has no geometry or no vertex buffer.
  19919. * Possible `kind` values :
  19920. * - BABYLON.VertexBuffer.PositionKind
  19921. * - BABYLON.VertexBuffer.UVKind
  19922. * - BABYLON.VertexBuffer.UV2Kind
  19923. * - BABYLON.VertexBuffer.UV3Kind
  19924. * - BABYLON.VertexBuffer.UV4Kind
  19925. * - BABYLON.VertexBuffer.UV5Kind
  19926. * - BABYLON.VertexBuffer.UV6Kind
  19927. * - BABYLON.VertexBuffer.ColorKind
  19928. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19929. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19930. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19931. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19932. */
  19933. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19934. if (!this._geometry) {
  19935. return null;
  19936. }
  19937. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19938. };
  19939. /**
  19940. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19941. * Returns `undefined` if the mesh has no geometry.
  19942. * Possible `kind` values :
  19943. * - BABYLON.VertexBuffer.PositionKind
  19944. * - BABYLON.VertexBuffer.UVKind
  19945. * - BABYLON.VertexBuffer.UV2Kind
  19946. * - BABYLON.VertexBuffer.UV3Kind
  19947. * - BABYLON.VertexBuffer.UV4Kind
  19948. * - BABYLON.VertexBuffer.UV5Kind
  19949. * - BABYLON.VertexBuffer.UV6Kind
  19950. * - BABYLON.VertexBuffer.ColorKind
  19951. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19952. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19953. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19954. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19955. */
  19956. Mesh.prototype.getVertexBuffer = function (kind) {
  19957. if (!this._geometry) {
  19958. return undefined;
  19959. }
  19960. return this._geometry.getVertexBuffer(kind);
  19961. };
  19962. /**
  19963. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19964. * Possible `kind` values :
  19965. * - BABYLON.VertexBuffer.PositionKind
  19966. * - BABYLON.VertexBuffer.UVKind
  19967. * - BABYLON.VertexBuffer.UV2Kind
  19968. * - BABYLON.VertexBuffer.UV3Kind
  19969. * - BABYLON.VertexBuffer.UV4Kind
  19970. * - BABYLON.VertexBuffer.UV5Kind
  19971. * - BABYLON.VertexBuffer.UV6Kind
  19972. * - BABYLON.VertexBuffer.ColorKind
  19973. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19974. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19975. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19976. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19977. */
  19978. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19979. if (!this._geometry) {
  19980. if (this._delayInfo) {
  19981. return this._delayInfo.indexOf(kind) !== -1;
  19982. }
  19983. return false;
  19984. }
  19985. return this._geometry.isVerticesDataPresent(kind);
  19986. };
  19987. /**
  19988. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19989. * Possible `kind` values :
  19990. * - BABYLON.VertexBuffer.PositionKind
  19991. * - BABYLON.VertexBuffer.UVKind
  19992. * - BABYLON.VertexBuffer.UV2Kind
  19993. * - BABYLON.VertexBuffer.UV3Kind
  19994. * - BABYLON.VertexBuffer.UV4Kind
  19995. * - BABYLON.VertexBuffer.UV5Kind
  19996. * - BABYLON.VertexBuffer.UV6Kind
  19997. * - BABYLON.VertexBuffer.ColorKind
  19998. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19999. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20000. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20001. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20002. */
  20003. Mesh.prototype.getVerticesDataKinds = function () {
  20004. if (!this._geometry) {
  20005. var result = [];
  20006. if (this._delayInfo) {
  20007. this._delayInfo.forEach(function (kind, index, array) {
  20008. result.push(kind);
  20009. });
  20010. }
  20011. return result;
  20012. }
  20013. return this._geometry.getVerticesDataKinds();
  20014. };
  20015. /**
  20016. * Returns a positive integer : the total number of indices in this mesh geometry.
  20017. * Returns zero if the mesh has no geometry.
  20018. */
  20019. Mesh.prototype.getTotalIndices = function () {
  20020. if (!this._geometry) {
  20021. return 0;
  20022. }
  20023. return this._geometry.getTotalIndices();
  20024. };
  20025. /**
  20026. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20027. * 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.
  20028. * Returns an empty array if the mesh has no geometry.
  20029. */
  20030. Mesh.prototype.getIndices = function (copyWhenShared) {
  20031. if (!this._geometry) {
  20032. return [];
  20033. }
  20034. return this._geometry.getIndices(copyWhenShared);
  20035. };
  20036. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20037. get: function () {
  20038. return this._masterMesh !== null && this._masterMesh !== undefined;
  20039. },
  20040. enumerable: true,
  20041. configurable: true
  20042. });
  20043. /**
  20044. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20045. */
  20046. Mesh.prototype.isReady = function () {
  20047. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20048. return false;
  20049. }
  20050. return _super.prototype.isReady.call(this);
  20051. };
  20052. /**
  20053. * Boolean : true if the mesh has been disposed.
  20054. */
  20055. Mesh.prototype.isDisposed = function () {
  20056. return this._isDisposed;
  20057. };
  20058. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20059. get: function () {
  20060. return this._sideOrientation;
  20061. },
  20062. /**
  20063. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20064. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20065. */
  20066. set: function (sideO) {
  20067. this._sideOrientation = sideO;
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20073. /**
  20074. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20075. * This property is pertinent only for updatable parametric shapes.
  20076. */
  20077. get: function () {
  20078. return this._areNormalsFrozen;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. /**
  20084. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20085. * It has no effect at all on other shapes.
  20086. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20087. * Returns the Mesh.
  20088. */
  20089. Mesh.prototype.freezeNormals = function () {
  20090. this._areNormalsFrozen = true;
  20091. return this;
  20092. };
  20093. /**
  20094. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20095. * It has no effect at all on other shapes.
  20096. * It reactivates the mesh normals computation if it was previously frozen.
  20097. * Returns the Mesh.
  20098. */
  20099. Mesh.prototype.unfreezeNormals = function () {
  20100. this._areNormalsFrozen = false;
  20101. return this;
  20102. };
  20103. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20104. /**
  20105. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20106. */
  20107. set: function (count) {
  20108. this._overridenInstanceCount = count;
  20109. },
  20110. enumerable: true,
  20111. configurable: true
  20112. });
  20113. // Methods
  20114. Mesh.prototype._preActivate = function () {
  20115. var sceneRenderId = this.getScene().getRenderId();
  20116. if (this._preActivateId === sceneRenderId) {
  20117. return this;
  20118. }
  20119. this._preActivateId = sceneRenderId;
  20120. this._visibleInstances = null;
  20121. return this;
  20122. };
  20123. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20124. if (this._visibleInstances) {
  20125. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20126. }
  20127. return this;
  20128. };
  20129. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20130. if (!this._visibleInstances) {
  20131. this._visibleInstances = {};
  20132. this._visibleInstances.defaultRenderId = renderId;
  20133. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20134. }
  20135. if (!this._visibleInstances[renderId]) {
  20136. this._visibleInstances[renderId] = new Array();
  20137. }
  20138. this._visibleInstances[renderId].push(instance);
  20139. return this;
  20140. };
  20141. /**
  20142. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20143. * This means the mesh underlying bounding box and sphere are recomputed.
  20144. * Returns the Mesh.
  20145. */
  20146. Mesh.prototype.refreshBoundingInfo = function () {
  20147. if (this._boundingInfo.isLocked) {
  20148. return;
  20149. }
  20150. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20151. if (data) {
  20152. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20153. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20154. }
  20155. if (this.subMeshes) {
  20156. for (var index = 0; index < this.subMeshes.length; index++) {
  20157. this.subMeshes[index].refreshBoundingInfo();
  20158. }
  20159. }
  20160. this._updateBoundingInfo();
  20161. return this;
  20162. };
  20163. Mesh.prototype._createGlobalSubMesh = function () {
  20164. var totalVertices = this.getTotalVertices();
  20165. if (!totalVertices || !this.getIndices()) {
  20166. return null;
  20167. }
  20168. // Check if we need to recreate the submeshes
  20169. if (this.subMeshes && this.subMeshes.length > 0) {
  20170. var totalIndices = this.getIndices().length;
  20171. var needToRecreate = false;
  20172. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20173. var submesh = _a[_i];
  20174. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  20175. needToRecreate = true;
  20176. break;
  20177. }
  20178. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  20179. needToRecreate = true;
  20180. break;
  20181. }
  20182. }
  20183. if (!needToRecreate) {
  20184. return;
  20185. }
  20186. }
  20187. this.releaseSubMeshes();
  20188. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20189. };
  20190. Mesh.prototype.subdivide = function (count) {
  20191. if (count < 1) {
  20192. return;
  20193. }
  20194. var totalIndices = this.getTotalIndices();
  20195. var subdivisionSize = (totalIndices / count) | 0;
  20196. var offset = 0;
  20197. // Ensure that subdivisionSize is a multiple of 3
  20198. while (subdivisionSize % 3 !== 0) {
  20199. subdivisionSize++;
  20200. }
  20201. this.releaseSubMeshes();
  20202. for (var index = 0; index < count; index++) {
  20203. if (offset >= totalIndices) {
  20204. break;
  20205. }
  20206. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20207. offset += subdivisionSize;
  20208. }
  20209. this.synchronizeInstances();
  20210. };
  20211. /**
  20212. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20213. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20214. * The `data` are either a numeric array either a Float32Array.
  20215. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20216. * 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).
  20217. * Note that a new underlying VertexBuffer object is created each call.
  20218. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20219. *
  20220. * Possible `kind` values :
  20221. * - BABYLON.VertexBuffer.PositionKind
  20222. * - BABYLON.VertexBuffer.UVKind
  20223. * - BABYLON.VertexBuffer.UV2Kind
  20224. * - BABYLON.VertexBuffer.UV3Kind
  20225. * - BABYLON.VertexBuffer.UV4Kind
  20226. * - BABYLON.VertexBuffer.UV5Kind
  20227. * - BABYLON.VertexBuffer.UV6Kind
  20228. * - BABYLON.VertexBuffer.ColorKind
  20229. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20230. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20231. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20232. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20233. *
  20234. * Returns the Mesh.
  20235. */
  20236. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20237. if (!this._geometry) {
  20238. var vertexData = new BABYLON.VertexData();
  20239. vertexData.set(data, kind);
  20240. var scene = this.getScene();
  20241. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20242. }
  20243. else {
  20244. this._geometry.setVerticesData(kind, data, updatable, stride);
  20245. }
  20246. return this;
  20247. };
  20248. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20249. if (updatable === void 0) { updatable = true; }
  20250. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20251. return;
  20252. }
  20253. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20254. };
  20255. /**
  20256. * Sets the mesh VertexBuffer.
  20257. * Returns the Mesh.
  20258. */
  20259. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20260. if (!this._geometry) {
  20261. var scene = this.getScene();
  20262. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20263. }
  20264. this._geometry.setVerticesBuffer(buffer);
  20265. return this;
  20266. };
  20267. /**
  20268. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20269. * If the mesh has no geometry, it is simply returned as it is.
  20270. * The `data` are either a numeric array either a Float32Array.
  20271. * No new underlying VertexBuffer object is created.
  20272. * 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.
  20273. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20274. *
  20275. * Possible `kind` values :
  20276. * - BABYLON.VertexBuffer.PositionKind
  20277. * - BABYLON.VertexBuffer.UVKind
  20278. * - BABYLON.VertexBuffer.UV2Kind
  20279. * - BABYLON.VertexBuffer.UV3Kind
  20280. * - BABYLON.VertexBuffer.UV4Kind
  20281. * - BABYLON.VertexBuffer.UV5Kind
  20282. * - BABYLON.VertexBuffer.UV6Kind
  20283. * - BABYLON.VertexBuffer.ColorKind
  20284. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20285. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20286. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20287. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20288. *
  20289. * Returns the Mesh.
  20290. */
  20291. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20292. if (!this._geometry) {
  20293. return;
  20294. }
  20295. if (!makeItUnique) {
  20296. this._geometry.updateVerticesData(kind, data, updateExtends);
  20297. }
  20298. else {
  20299. this.makeGeometryUnique();
  20300. this.updateVerticesData(kind, data, updateExtends, false);
  20301. }
  20302. return this;
  20303. };
  20304. /**
  20305. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20306. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20307. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20308. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20309. * Returns the Mesh.
  20310. */
  20311. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20312. if (computeNormals === void 0) { computeNormals = true; }
  20313. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20314. positionFunction(positions);
  20315. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20316. if (computeNormals) {
  20317. var indices = this.getIndices();
  20318. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20319. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20320. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20321. }
  20322. return this;
  20323. };
  20324. /**
  20325. * Creates a un-shared specific occurence of the geometry for the mesh.
  20326. * Returns the Mesh.
  20327. */
  20328. Mesh.prototype.makeGeometryUnique = function () {
  20329. if (!this._geometry) {
  20330. return;
  20331. }
  20332. var oldGeometry = this._geometry;
  20333. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20334. oldGeometry.releaseForMesh(this, true);
  20335. geometry.applyToMesh(this);
  20336. return this;
  20337. };
  20338. /**
  20339. * Sets the mesh indices.
  20340. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20341. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20342. * This method creates a new index buffer each call.
  20343. * Returns the Mesh.
  20344. */
  20345. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20346. if (!this._geometry) {
  20347. var vertexData = new BABYLON.VertexData();
  20348. vertexData.indices = indices;
  20349. var scene = this.getScene();
  20350. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20351. }
  20352. else {
  20353. this._geometry.setIndices(indices, totalVertices);
  20354. }
  20355. return this;
  20356. };
  20357. /**
  20358. * Invert the geometry to move from a right handed system to a left handed one.
  20359. * Returns the Mesh.
  20360. */
  20361. Mesh.prototype.toLeftHanded = function () {
  20362. if (!this._geometry) {
  20363. return;
  20364. }
  20365. this._geometry.toLeftHanded();
  20366. return this;
  20367. };
  20368. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20369. var engine = this.getScene().getEngine();
  20370. // Wireframe
  20371. var indexToBind;
  20372. if (this._unIndexed) {
  20373. indexToBind = null;
  20374. }
  20375. else {
  20376. switch (fillMode) {
  20377. case BABYLON.Material.PointFillMode:
  20378. indexToBind = null;
  20379. break;
  20380. case BABYLON.Material.WireFrameFillMode:
  20381. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20382. break;
  20383. default:
  20384. case BABYLON.Material.TriangleFillMode:
  20385. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20386. break;
  20387. }
  20388. }
  20389. // VBOs
  20390. this._geometry._bind(effect, indexToBind);
  20391. return this;
  20392. };
  20393. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20394. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20395. return this;
  20396. }
  20397. this.onBeforeDrawObservable.notifyObservers(this);
  20398. var engine = this.getScene().getEngine();
  20399. // Draw order
  20400. switch (fillMode) {
  20401. case BABYLON.Material.PointFillMode:
  20402. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20403. break;
  20404. case BABYLON.Material.WireFrameFillMode:
  20405. if (this._unIndexed) {
  20406. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20407. }
  20408. else {
  20409. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20410. }
  20411. break;
  20412. default:
  20413. if (this._unIndexed) {
  20414. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20415. }
  20416. else {
  20417. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20418. }
  20419. }
  20420. return this;
  20421. };
  20422. /**
  20423. * Registers for this mesh a javascript function called just before the rendering process.
  20424. * This function is passed the current mesh.
  20425. * Return the Mesh.
  20426. */
  20427. Mesh.prototype.registerBeforeRender = function (func) {
  20428. this.onBeforeRenderObservable.add(func);
  20429. return this;
  20430. };
  20431. /**
  20432. * Disposes a previously registered javascript function called before the rendering.
  20433. * This function is passed the current mesh.
  20434. * Returns the Mesh.
  20435. */
  20436. Mesh.prototype.unregisterBeforeRender = function (func) {
  20437. this.onBeforeRenderObservable.removeCallback(func);
  20438. return this;
  20439. };
  20440. /**
  20441. * Registers for this mesh a javascript function called just after the rendering is complete.
  20442. * This function is passed the current mesh.
  20443. * Returns the Mesh.
  20444. */
  20445. Mesh.prototype.registerAfterRender = function (func) {
  20446. this.onAfterRenderObservable.add(func);
  20447. return this;
  20448. };
  20449. /**
  20450. * Disposes a previously registered javascript function called after the rendering.
  20451. * This function is passed the current mesh.
  20452. * Return the Mesh.
  20453. */
  20454. Mesh.prototype.unregisterAfterRender = function (func) {
  20455. this.onAfterRenderObservable.removeCallback(func);
  20456. return this;
  20457. };
  20458. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20459. var scene = this.getScene();
  20460. this._batchCache.mustReturn = false;
  20461. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20462. this._batchCache.visibleInstances[subMeshId] = null;
  20463. if (this._visibleInstances) {
  20464. var currentRenderId = scene.getRenderId();
  20465. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20466. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20467. var selfRenderId = this._renderId;
  20468. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20469. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20470. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20471. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20472. }
  20473. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20474. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20475. this._batchCache.mustReturn = true;
  20476. return this._batchCache;
  20477. }
  20478. if (currentRenderId !== selfRenderId) {
  20479. this._batchCache.renderSelf[subMeshId] = false;
  20480. }
  20481. }
  20482. this._renderIdForInstances[subMeshId] = currentRenderId;
  20483. }
  20484. return this._batchCache;
  20485. };
  20486. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20487. var visibleInstances = batch.visibleInstances[subMesh._id];
  20488. var matricesCount = visibleInstances.length + 1;
  20489. var bufferSize = matricesCount * 16 * 4;
  20490. var currentInstancesBufferSize = this._instancesBufferSize;
  20491. var instancesBuffer = this._instancesBuffer;
  20492. while (this._instancesBufferSize < bufferSize) {
  20493. this._instancesBufferSize *= 2;
  20494. }
  20495. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20496. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20497. }
  20498. var offset = 0;
  20499. var instancesCount = 0;
  20500. var world = this.getWorldMatrix();
  20501. if (batch.renderSelf[subMesh._id]) {
  20502. world.copyToArray(this._instancesData, offset);
  20503. offset += 16;
  20504. instancesCount++;
  20505. }
  20506. if (visibleInstances) {
  20507. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20508. var instance = visibleInstances[instanceIndex];
  20509. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20510. offset += 16;
  20511. instancesCount++;
  20512. }
  20513. }
  20514. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20515. if (instancesBuffer) {
  20516. instancesBuffer.dispose();
  20517. }
  20518. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20519. this._instancesBuffer = instancesBuffer;
  20520. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20521. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20522. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20523. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20524. }
  20525. else {
  20526. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20527. }
  20528. this.geometry._bind(effect);
  20529. this._draw(subMesh, fillMode, instancesCount);
  20530. engine.unbindInstanceAttributes();
  20531. return this;
  20532. };
  20533. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20534. var scene = this.getScene();
  20535. var engine = scene.getEngine();
  20536. if (hardwareInstancedRendering) {
  20537. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20538. }
  20539. else {
  20540. if (batch.renderSelf[subMesh._id]) {
  20541. // Draw
  20542. if (onBeforeDraw) {
  20543. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20544. }
  20545. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20546. }
  20547. if (batch.visibleInstances[subMesh._id]) {
  20548. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20549. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20550. // World
  20551. var world = instance.getWorldMatrix();
  20552. if (onBeforeDraw) {
  20553. onBeforeDraw(true, world, effectiveMaterial);
  20554. }
  20555. // Draw
  20556. this._draw(subMesh, fillMode);
  20557. }
  20558. }
  20559. }
  20560. return this;
  20561. };
  20562. /**
  20563. * Triggers the draw call for the mesh.
  20564. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20565. * Returns the Mesh.
  20566. */
  20567. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20568. var scene = this.getScene();
  20569. // Managing instances
  20570. var batch = this._getInstancesRenderList(subMesh._id);
  20571. if (batch.mustReturn) {
  20572. return this;
  20573. }
  20574. // Checking geometry state
  20575. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20576. return this;
  20577. }
  20578. var callbackIndex;
  20579. this.onBeforeRenderObservable.notifyObservers(this);
  20580. var engine = scene.getEngine();
  20581. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20582. // Material
  20583. var effectiveMaterial = subMesh.getMaterial();
  20584. if (!effectiveMaterial) {
  20585. return this;
  20586. }
  20587. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20588. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20589. return this;
  20590. }
  20591. }
  20592. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20593. return this;
  20594. }
  20595. // Alpha mode
  20596. if (enableAlphaMode) {
  20597. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20598. }
  20599. // Outline - step 1
  20600. var savedDepthWrite = engine.getDepthWrite();
  20601. if (this.renderOutline) {
  20602. engine.setDepthWrite(false);
  20603. scene.getOutlineRenderer().render(subMesh, batch);
  20604. engine.setDepthWrite(savedDepthWrite);
  20605. }
  20606. var effect;
  20607. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20608. effect = subMesh.effect;
  20609. }
  20610. else {
  20611. effect = effectiveMaterial.getEffect();
  20612. }
  20613. effectiveMaterial._preBind(effect);
  20614. // Bind
  20615. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20616. this._bind(subMesh, effect, fillMode);
  20617. var world = this.getWorldMatrix();
  20618. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20619. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20620. }
  20621. else {
  20622. effectiveMaterial.bind(world, this);
  20623. }
  20624. // Draw
  20625. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20626. // Unbind
  20627. effectiveMaterial.unbind();
  20628. // Outline - step 2
  20629. if (this.renderOutline && savedDepthWrite) {
  20630. engine.setDepthWrite(true);
  20631. engine.setColorWrite(false);
  20632. scene.getOutlineRenderer().render(subMesh, batch);
  20633. engine.setColorWrite(true);
  20634. }
  20635. // Overlay
  20636. if (this.renderOverlay) {
  20637. var currentMode = engine.getAlphaMode();
  20638. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20639. scene.getOutlineRenderer().render(subMesh, batch, true);
  20640. engine.setAlphaMode(currentMode);
  20641. }
  20642. this.onAfterRenderObservable.notifyObservers(this);
  20643. return this;
  20644. };
  20645. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20646. if (isInstance) {
  20647. effectiveMaterial.bindOnlyWorldMatrix(world);
  20648. }
  20649. return this;
  20650. };
  20651. /**
  20652. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20653. */
  20654. Mesh.prototype.getEmittedParticleSystems = function () {
  20655. var results = new Array();
  20656. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20657. var particleSystem = this.getScene().particleSystems[index];
  20658. if (particleSystem.emitter === this) {
  20659. results.push(particleSystem);
  20660. }
  20661. }
  20662. return results;
  20663. };
  20664. /**
  20665. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20666. */
  20667. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20668. var results = new Array();
  20669. var descendants = this.getDescendants();
  20670. descendants.push(this);
  20671. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20672. var particleSystem = this.getScene().particleSystems[index];
  20673. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20674. results.push(particleSystem);
  20675. }
  20676. }
  20677. return results;
  20678. };
  20679. Mesh.prototype._checkDelayState = function () {
  20680. var scene = this.getScene();
  20681. if (this._geometry) {
  20682. this._geometry.load(scene);
  20683. }
  20684. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20685. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20686. this._queueLoad(this, scene);
  20687. }
  20688. return this;
  20689. };
  20690. Mesh.prototype._queueLoad = function (mesh, scene) {
  20691. var _this = this;
  20692. scene._addPendingData(mesh);
  20693. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20694. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20695. if (data instanceof ArrayBuffer) {
  20696. _this._delayLoadingFunction(data, _this);
  20697. }
  20698. else {
  20699. _this._delayLoadingFunction(JSON.parse(data), _this);
  20700. }
  20701. _this.instances.forEach(function (instance) {
  20702. instance._syncSubMeshes();
  20703. });
  20704. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20705. scene._removePendingData(_this);
  20706. }, function () { }, scene.database, getBinaryData);
  20707. return this;
  20708. };
  20709. /**
  20710. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20711. */
  20712. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20713. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20714. return false;
  20715. }
  20716. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20717. return false;
  20718. }
  20719. this._checkDelayState();
  20720. return true;
  20721. };
  20722. /**
  20723. * Sets the mesh material by the material or multiMaterial `id` property.
  20724. * The material `id` is a string identifying the material or the multiMaterial.
  20725. * This method returns the Mesh.
  20726. */
  20727. Mesh.prototype.setMaterialByID = function (id) {
  20728. var materials = this.getScene().materials;
  20729. var index;
  20730. for (index = materials.length - 1; index > -1; index--) {
  20731. if (materials[index].id === id) {
  20732. this.material = materials[index];
  20733. return this;
  20734. }
  20735. }
  20736. // Multi
  20737. var multiMaterials = this.getScene().multiMaterials;
  20738. for (index = multiMaterials.length - 1; index > -1; index--) {
  20739. if (multiMaterials[index].id === id) {
  20740. this.material = multiMaterials[index];
  20741. return this;
  20742. }
  20743. }
  20744. return this;
  20745. };
  20746. /**
  20747. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20748. */
  20749. Mesh.prototype.getAnimatables = function () {
  20750. var results = [];
  20751. if (this.material) {
  20752. results.push(this.material);
  20753. }
  20754. if (this.skeleton) {
  20755. results.push(this.skeleton);
  20756. }
  20757. return results;
  20758. };
  20759. /**
  20760. * Modifies the mesh geometry according to the passed transformation matrix.
  20761. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20762. * The mesh normals are modified accordingly the same transformation.
  20763. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20764. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20765. * Returns the Mesh.
  20766. */
  20767. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20768. // Position
  20769. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20770. return this;
  20771. }
  20772. var submeshes = this.subMeshes.splice(0);
  20773. this._resetPointsArrayCache();
  20774. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20775. var temp = [];
  20776. var index;
  20777. for (index = 0; index < data.length; index += 3) {
  20778. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20779. }
  20780. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20781. // Normals
  20782. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20783. return this;
  20784. }
  20785. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20786. temp = [];
  20787. for (index = 0; index < data.length; index += 3) {
  20788. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20789. }
  20790. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20791. // flip faces?
  20792. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20793. this.flipFaces();
  20794. }
  20795. // Restore submeshes
  20796. this.releaseSubMeshes();
  20797. this.subMeshes = submeshes;
  20798. return this;
  20799. };
  20800. /**
  20801. * Modifies the mesh geometry according to its own current World Matrix.
  20802. * The mesh World Matrix is then reset.
  20803. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20804. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20805. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20806. * Returns the Mesh.
  20807. */
  20808. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20809. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20810. this.scaling.copyFromFloats(1, 1, 1);
  20811. this.position.copyFromFloats(0, 0, 0);
  20812. this.rotation.copyFromFloats(0, 0, 0);
  20813. //only if quaternion is already set
  20814. if (this.rotationQuaternion) {
  20815. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20816. }
  20817. this._worldMatrix = BABYLON.Matrix.Identity();
  20818. return this;
  20819. };
  20820. Object.defineProperty(Mesh.prototype, "_positions", {
  20821. // Cache
  20822. get: function () {
  20823. if (this._geometry) {
  20824. return this._geometry._positions;
  20825. }
  20826. return null;
  20827. },
  20828. enumerable: true,
  20829. configurable: true
  20830. });
  20831. Mesh.prototype._resetPointsArrayCache = function () {
  20832. if (this._geometry) {
  20833. this._geometry._resetPointsArrayCache();
  20834. }
  20835. return this;
  20836. };
  20837. Mesh.prototype._generatePointsArray = function () {
  20838. if (this._geometry) {
  20839. return this._geometry._generatePointsArray();
  20840. }
  20841. return false;
  20842. };
  20843. /**
  20844. * Returns a new Mesh object generated from the current mesh properties.
  20845. * This method must not get confused with createInstance().
  20846. * The parameter `name` is a string, the name given to the new mesh.
  20847. * The optional parameter `newParent` can be any Node object (default `null`).
  20848. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20849. * 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.
  20850. */
  20851. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20852. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20853. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20854. };
  20855. /**
  20856. * Disposes the mesh.
  20857. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20858. */
  20859. Mesh.prototype.dispose = function (doNotRecurse) {
  20860. var _this = this;
  20861. this.morphTargetManager = undefined;
  20862. if (this._geometry) {
  20863. this._geometry.releaseForMesh(this, true);
  20864. }
  20865. // Sources
  20866. var meshes = this.getScene().meshes;
  20867. meshes.forEach(function (mesh) {
  20868. if (mesh._source && mesh._source === _this) {
  20869. mesh._source = null;
  20870. }
  20871. });
  20872. this._source = null;
  20873. // Instances
  20874. if (this._instancesBuffer) {
  20875. this._instancesBuffer.dispose();
  20876. this._instancesBuffer = null;
  20877. }
  20878. while (this.instances.length) {
  20879. this.instances[0].dispose();
  20880. }
  20881. // Highlight layers.
  20882. var highlightLayers = this.getScene().highlightLayers;
  20883. for (var i = 0; i < highlightLayers.length; i++) {
  20884. var highlightLayer = highlightLayers[i];
  20885. if (highlightLayer) {
  20886. highlightLayer.removeMesh(this);
  20887. highlightLayer.removeExcludedMesh(this);
  20888. }
  20889. }
  20890. _super.prototype.dispose.call(this, doNotRecurse);
  20891. };
  20892. /**
  20893. * Modifies the mesh geometry according to a displacement map.
  20894. * 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.
  20895. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20896. * This method returns nothing.
  20897. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20898. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20899. * 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.
  20900. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20901. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20902. *
  20903. * Returns the Mesh.
  20904. */
  20905. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20906. var _this = this;
  20907. var scene = this.getScene();
  20908. var onload = function (img) {
  20909. // Getting height map data
  20910. var canvas = document.createElement("canvas");
  20911. var context = canvas.getContext("2d");
  20912. var heightMapWidth = img.width;
  20913. var heightMapHeight = img.height;
  20914. canvas.width = heightMapWidth;
  20915. canvas.height = heightMapHeight;
  20916. context.drawImage(img, 0, 0);
  20917. // Create VertexData from map data
  20918. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20919. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20920. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20921. //execute success callback, if set
  20922. if (onSuccess) {
  20923. onSuccess(_this);
  20924. }
  20925. };
  20926. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20927. return this;
  20928. };
  20929. /**
  20930. * Modifies the mesh geometry according to a displacementMap buffer.
  20931. * 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.
  20932. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20933. * This method returns nothing.
  20934. * 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.
  20935. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20936. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20937. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20938. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20939. *
  20940. * Returns the Mesh.
  20941. */
  20942. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20943. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20944. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20945. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20946. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20947. return this;
  20948. }
  20949. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20950. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20951. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20952. var position = BABYLON.Vector3.Zero();
  20953. var normal = BABYLON.Vector3.Zero();
  20954. var uv = BABYLON.Vector2.Zero();
  20955. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20956. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20957. for (var index = 0; index < positions.length; index += 3) {
  20958. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20959. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20960. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20961. // Compute height
  20962. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20963. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20964. var pos = (u + v * heightMapWidth) * 4;
  20965. var r = buffer[pos] / 255.0;
  20966. var g = buffer[pos + 1] / 255.0;
  20967. var b = buffer[pos + 2] / 255.0;
  20968. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20969. normal.normalize();
  20970. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20971. position = position.add(normal);
  20972. position.toArray(positions, index);
  20973. }
  20974. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20975. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20976. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20977. return this;
  20978. };
  20979. /**
  20980. * Modify the mesh to get a flat shading rendering.
  20981. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20982. * This method returns the Mesh.
  20983. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20984. */
  20985. Mesh.prototype.convertToFlatShadedMesh = function () {
  20986. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20987. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20988. var kinds = this.getVerticesDataKinds();
  20989. var vbs = [];
  20990. var data = [];
  20991. var newdata = [];
  20992. var updatableNormals = false;
  20993. var kindIndex;
  20994. var kind;
  20995. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20996. kind = kinds[kindIndex];
  20997. var vertexBuffer = this.getVertexBuffer(kind);
  20998. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20999. updatableNormals = vertexBuffer.isUpdatable();
  21000. kinds.splice(kindIndex, 1);
  21001. kindIndex--;
  21002. continue;
  21003. }
  21004. vbs[kind] = vertexBuffer;
  21005. data[kind] = vbs[kind].getData();
  21006. newdata[kind] = [];
  21007. }
  21008. // Save previous submeshes
  21009. var previousSubmeshes = this.subMeshes.slice(0);
  21010. var indices = this.getIndices();
  21011. var totalIndices = this.getTotalIndices();
  21012. // Generating unique vertices per face
  21013. var index;
  21014. for (index = 0; index < totalIndices; index++) {
  21015. var vertexIndex = indices[index];
  21016. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21017. kind = kinds[kindIndex];
  21018. var stride = vbs[kind].getStrideSize();
  21019. for (var offset = 0; offset < stride; offset++) {
  21020. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21021. }
  21022. }
  21023. }
  21024. // Updating faces & normal
  21025. var normals = [];
  21026. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21027. for (index = 0; index < totalIndices; index += 3) {
  21028. indices[index] = index;
  21029. indices[index + 1] = index + 1;
  21030. indices[index + 2] = index + 2;
  21031. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21032. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21033. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21034. var p1p2 = p1.subtract(p2);
  21035. var p3p2 = p3.subtract(p2);
  21036. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21037. // Store same normals for every vertex
  21038. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21039. normals.push(normal.x);
  21040. normals.push(normal.y);
  21041. normals.push(normal.z);
  21042. }
  21043. }
  21044. this.setIndices(indices);
  21045. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21046. // Updating vertex buffers
  21047. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21048. kind = kinds[kindIndex];
  21049. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21050. }
  21051. // Updating submeshes
  21052. this.releaseSubMeshes();
  21053. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21054. var previousOne = previousSubmeshes[submeshIndex];
  21055. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21056. }
  21057. this.synchronizeInstances();
  21058. return this;
  21059. };
  21060. /**
  21061. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21062. * In other words, more vertices, no more indices and a single bigger VBO.
  21063. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21064. * Returns the Mesh.
  21065. */
  21066. Mesh.prototype.convertToUnIndexedMesh = function () {
  21067. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21068. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21069. var kinds = this.getVerticesDataKinds();
  21070. var vbs = [];
  21071. var data = [];
  21072. var newdata = [];
  21073. var updatableNormals = false;
  21074. var kindIndex;
  21075. var kind;
  21076. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21077. kind = kinds[kindIndex];
  21078. var vertexBuffer = this.getVertexBuffer(kind);
  21079. vbs[kind] = vertexBuffer;
  21080. data[kind] = vbs[kind].getData();
  21081. newdata[kind] = [];
  21082. }
  21083. // Save previous submeshes
  21084. var previousSubmeshes = this.subMeshes.slice(0);
  21085. var indices = this.getIndices();
  21086. var totalIndices = this.getTotalIndices();
  21087. // Generating unique vertices per face
  21088. var index;
  21089. for (index = 0; index < totalIndices; index++) {
  21090. var vertexIndex = indices[index];
  21091. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21092. kind = kinds[kindIndex];
  21093. var stride = vbs[kind].getStrideSize();
  21094. for (var offset = 0; offset < stride; offset++) {
  21095. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21096. }
  21097. }
  21098. }
  21099. // Updating indices
  21100. for (index = 0; index < totalIndices; index += 3) {
  21101. indices[index] = index;
  21102. indices[index + 1] = index + 1;
  21103. indices[index + 2] = index + 2;
  21104. }
  21105. this.setIndices(indices);
  21106. // Updating vertex buffers
  21107. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21108. kind = kinds[kindIndex];
  21109. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21110. }
  21111. // Updating submeshes
  21112. this.releaseSubMeshes();
  21113. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21114. var previousOne = previousSubmeshes[submeshIndex];
  21115. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21116. }
  21117. this._unIndexed = true;
  21118. this.synchronizeInstances();
  21119. return this;
  21120. };
  21121. /**
  21122. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21123. * This method returns the Mesh.
  21124. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21125. */
  21126. Mesh.prototype.flipFaces = function (flipNormals) {
  21127. if (flipNormals === void 0) { flipNormals = false; }
  21128. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21129. var i;
  21130. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21131. for (i = 0; i < vertex_data.normals.length; i++) {
  21132. vertex_data.normals[i] *= -1;
  21133. }
  21134. }
  21135. var temp;
  21136. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21137. // reassign indices
  21138. temp = vertex_data.indices[i + 1];
  21139. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21140. vertex_data.indices[i + 2] = temp;
  21141. }
  21142. vertex_data.applyToMesh(this);
  21143. return this;
  21144. };
  21145. // Instances
  21146. /**
  21147. * Creates a new InstancedMesh object from the mesh model.
  21148. * An instance shares the same properties and the same material than its model.
  21149. * Only these properties of each instance can then be set individually :
  21150. * - position
  21151. * - rotation
  21152. * - rotationQuaternion
  21153. * - setPivotMatrix
  21154. * - scaling
  21155. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21156. * Warning : this method is not supported for Line mesh and LineSystem
  21157. */
  21158. Mesh.prototype.createInstance = function (name) {
  21159. return new BABYLON.InstancedMesh(name, this);
  21160. };
  21161. /**
  21162. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21163. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21164. * This method returns the Mesh.
  21165. */
  21166. Mesh.prototype.synchronizeInstances = function () {
  21167. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21168. var instance = this.instances[instanceIndex];
  21169. instance._syncSubMeshes();
  21170. }
  21171. return this;
  21172. };
  21173. /**
  21174. * Simplify the mesh according to the given array of settings.
  21175. * Function will return immediately and will simplify async. It returns the Mesh.
  21176. * @param settings a collection of simplification settings.
  21177. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21178. * @param type the type of simplification to run.
  21179. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21180. */
  21181. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21182. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21183. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21184. this.getScene().simplificationQueue.addTask({
  21185. settings: settings,
  21186. parallelProcessing: parallelProcessing,
  21187. mesh: this,
  21188. simplificationType: simplificationType,
  21189. successCallback: successCallback
  21190. });
  21191. return this;
  21192. };
  21193. /**
  21194. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21195. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21196. * This should be used together with the simplification to avoid disappearing triangles.
  21197. * Returns the Mesh.
  21198. * @param successCallback an optional success callback to be called after the optimization finished.
  21199. */
  21200. Mesh.prototype.optimizeIndices = function (successCallback) {
  21201. var _this = this;
  21202. var indices = this.getIndices();
  21203. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21204. var vectorPositions = [];
  21205. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21206. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21207. }
  21208. var dupes = [];
  21209. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21210. var realPos = vectorPositions.length - 1 - iteration;
  21211. var testedPosition = vectorPositions[realPos];
  21212. for (var j = 0; j < realPos; ++j) {
  21213. var againstPosition = vectorPositions[j];
  21214. if (testedPosition.equals(againstPosition)) {
  21215. dupes[realPos] = j;
  21216. break;
  21217. }
  21218. }
  21219. }, function () {
  21220. for (var i = 0; i < indices.length; ++i) {
  21221. indices[i] = dupes[indices[i]] || indices[i];
  21222. }
  21223. //indices are now reordered
  21224. var originalSubMeshes = _this.subMeshes.slice(0);
  21225. _this.setIndices(indices);
  21226. _this.subMeshes = originalSubMeshes;
  21227. if (successCallback) {
  21228. successCallback(_this);
  21229. }
  21230. });
  21231. return this;
  21232. };
  21233. Mesh.prototype.serialize = function (serializationObject) {
  21234. serializationObject.name = this.name;
  21235. serializationObject.id = this.id;
  21236. serializationObject.type = this.getClassName();
  21237. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21238. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21239. }
  21240. serializationObject.position = this.position.asArray();
  21241. if (this.rotationQuaternion) {
  21242. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21243. }
  21244. else if (this.rotation) {
  21245. serializationObject.rotation = this.rotation.asArray();
  21246. }
  21247. serializationObject.scaling = this.scaling.asArray();
  21248. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21249. serializationObject.isEnabled = this.isEnabled();
  21250. serializationObject.isVisible = this.isVisible;
  21251. serializationObject.infiniteDistance = this.infiniteDistance;
  21252. serializationObject.pickable = this.isPickable;
  21253. serializationObject.receiveShadows = this.receiveShadows;
  21254. serializationObject.billboardMode = this.billboardMode;
  21255. serializationObject.visibility = this.visibility;
  21256. serializationObject.checkCollisions = this.checkCollisions;
  21257. serializationObject.isBlocker = this.isBlocker;
  21258. // Parent
  21259. if (this.parent) {
  21260. serializationObject.parentId = this.parent.id;
  21261. }
  21262. // Geometry
  21263. var geometry = this._geometry;
  21264. if (geometry) {
  21265. var geometryId = geometry.id;
  21266. serializationObject.geometryId = geometryId;
  21267. // SubMeshes
  21268. serializationObject.subMeshes = [];
  21269. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21270. var subMesh = this.subMeshes[subIndex];
  21271. serializationObject.subMeshes.push({
  21272. materialIndex: subMesh.materialIndex,
  21273. verticesStart: subMesh.verticesStart,
  21274. verticesCount: subMesh.verticesCount,
  21275. indexStart: subMesh.indexStart,
  21276. indexCount: subMesh.indexCount
  21277. });
  21278. }
  21279. }
  21280. // Material
  21281. if (this.material) {
  21282. serializationObject.materialId = this.material.id;
  21283. }
  21284. else {
  21285. this.material = null;
  21286. }
  21287. // Morph targets
  21288. if (this.morphTargetManager) {
  21289. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21290. }
  21291. // Skeleton
  21292. if (this.skeleton) {
  21293. serializationObject.skeletonId = this.skeleton.id;
  21294. }
  21295. // Physics
  21296. //TODO implement correct serialization for physics impostors.
  21297. if (this.getPhysicsImpostor()) {
  21298. var impostor = this.getPhysicsImpostor();
  21299. serializationObject.physicsMass = impostor.getParam("mass");
  21300. serializationObject.physicsFriction = impostor.getParam("friction");
  21301. serializationObject.physicsRestitution = impostor.getParam("mass");
  21302. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21303. }
  21304. // Metadata
  21305. if (this.metadata) {
  21306. serializationObject.metadata = this.metadata;
  21307. }
  21308. // Instances
  21309. serializationObject.instances = [];
  21310. for (var index = 0; index < this.instances.length; index++) {
  21311. var instance = this.instances[index];
  21312. var serializationInstance = {
  21313. name: instance.name,
  21314. position: instance.position.asArray(),
  21315. scaling: instance.scaling.asArray()
  21316. };
  21317. if (instance.rotationQuaternion) {
  21318. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21319. }
  21320. else if (instance.rotation) {
  21321. serializationInstance.rotation = instance.rotation.asArray();
  21322. }
  21323. serializationObject.instances.push(serializationInstance);
  21324. // Animations
  21325. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21326. serializationInstance.ranges = instance.serializeAnimationRanges();
  21327. }
  21328. //
  21329. // Animations
  21330. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21331. serializationObject.ranges = this.serializeAnimationRanges();
  21332. // Layer mask
  21333. serializationObject.layerMask = this.layerMask;
  21334. // Alpha
  21335. serializationObject.alphaIndex = this.alphaIndex;
  21336. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21337. // Overlay
  21338. serializationObject.overlayAlpha = this.overlayAlpha;
  21339. serializationObject.overlayColor = this.overlayColor.asArray();
  21340. serializationObject.renderOverlay = this.renderOverlay;
  21341. // Fog
  21342. serializationObject.applyFog = this.applyFog;
  21343. // Action Manager
  21344. if (this.actionManager) {
  21345. serializationObject.actions = this.actionManager.serialize(this.name);
  21346. }
  21347. };
  21348. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21349. if (!this.geometry) {
  21350. return;
  21351. }
  21352. this._markSubMeshesAsAttributesDirty();
  21353. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21354. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21355. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21356. this.morphTargetManager = undefined;
  21357. return;
  21358. }
  21359. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21360. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21361. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21362. if (morphTarget.hasNormals) {
  21363. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21364. }
  21365. if (morphTarget.hasTangents) {
  21366. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21367. }
  21368. }
  21369. }
  21370. else {
  21371. var index = 0;
  21372. // Positions
  21373. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21374. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21375. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21376. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21377. }
  21378. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21379. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21380. }
  21381. index++;
  21382. }
  21383. }
  21384. };
  21385. // Statics
  21386. /**
  21387. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21388. * The parameter `parsedMesh` is the mesh to be copied.
  21389. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21390. */
  21391. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21392. var mesh;
  21393. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21394. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21395. }
  21396. else {
  21397. mesh = new Mesh(parsedMesh.name, scene);
  21398. }
  21399. mesh.id = parsedMesh.id;
  21400. if (BABYLON.Tags) {
  21401. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21402. }
  21403. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21404. if (parsedMesh.metadata !== undefined) {
  21405. mesh.metadata = parsedMesh.metadata;
  21406. }
  21407. if (parsedMesh.rotationQuaternion) {
  21408. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21409. }
  21410. else if (parsedMesh.rotation) {
  21411. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21412. }
  21413. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21414. if (parsedMesh.localMatrix) {
  21415. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21416. }
  21417. else if (parsedMesh.pivotMatrix) {
  21418. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21419. }
  21420. mesh.setEnabled(parsedMesh.isEnabled);
  21421. mesh.isVisible = parsedMesh.isVisible;
  21422. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21423. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21424. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21425. if (parsedMesh.applyFog !== undefined) {
  21426. mesh.applyFog = parsedMesh.applyFog;
  21427. }
  21428. if (parsedMesh.pickable !== undefined) {
  21429. mesh.isPickable = parsedMesh.pickable;
  21430. }
  21431. if (parsedMesh.alphaIndex !== undefined) {
  21432. mesh.alphaIndex = parsedMesh.alphaIndex;
  21433. }
  21434. mesh.receiveShadows = parsedMesh.receiveShadows;
  21435. mesh.billboardMode = parsedMesh.billboardMode;
  21436. if (parsedMesh.visibility !== undefined) {
  21437. mesh.visibility = parsedMesh.visibility;
  21438. }
  21439. mesh.checkCollisions = parsedMesh.checkCollisions;
  21440. if (parsedMesh.isBlocker !== undefined) {
  21441. mesh.isBlocker = parsedMesh.isBlocker;
  21442. }
  21443. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21444. // freezeWorldMatrix
  21445. if (parsedMesh.freezeWorldMatrix) {
  21446. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21447. }
  21448. // Parent
  21449. if (parsedMesh.parentId) {
  21450. mesh._waitingParentId = parsedMesh.parentId;
  21451. }
  21452. // Actions
  21453. if (parsedMesh.actions !== undefined) {
  21454. mesh._waitingActions = parsedMesh.actions;
  21455. }
  21456. // Overlay
  21457. if (parsedMesh.overlayAlpha !== undefined) {
  21458. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21459. }
  21460. if (parsedMesh.overlayColor !== undefined) {
  21461. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21462. }
  21463. if (parsedMesh.renderOverlay !== undefined) {
  21464. mesh.renderOverlay = parsedMesh.renderOverlay;
  21465. }
  21466. // Geometry
  21467. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21468. if (parsedMesh.delayLoadingFile) {
  21469. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21470. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21471. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21472. if (parsedMesh._binaryInfo) {
  21473. mesh._binaryInfo = parsedMesh._binaryInfo;
  21474. }
  21475. mesh._delayInfo = [];
  21476. if (parsedMesh.hasUVs) {
  21477. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21478. }
  21479. if (parsedMesh.hasUVs2) {
  21480. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21481. }
  21482. if (parsedMesh.hasUVs3) {
  21483. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21484. }
  21485. if (parsedMesh.hasUVs4) {
  21486. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21487. }
  21488. if (parsedMesh.hasUVs5) {
  21489. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21490. }
  21491. if (parsedMesh.hasUVs6) {
  21492. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21493. }
  21494. if (parsedMesh.hasColors) {
  21495. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21496. }
  21497. if (parsedMesh.hasMatricesIndices) {
  21498. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21499. }
  21500. if (parsedMesh.hasMatricesWeights) {
  21501. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21502. }
  21503. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21504. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21505. mesh._checkDelayState();
  21506. }
  21507. }
  21508. else {
  21509. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21510. }
  21511. // Material
  21512. if (parsedMesh.materialId) {
  21513. mesh.setMaterialByID(parsedMesh.materialId);
  21514. }
  21515. else {
  21516. mesh.material = null;
  21517. }
  21518. // Morph targets
  21519. if (parsedMesh.morphTargetManagerId > -1) {
  21520. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21521. }
  21522. // Skeleton
  21523. if (parsedMesh.skeletonId > -1) {
  21524. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21525. if (parsedMesh.numBoneInfluencers) {
  21526. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21527. }
  21528. }
  21529. // Animations
  21530. if (parsedMesh.animations) {
  21531. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21532. var parsedAnimation = parsedMesh.animations[animationIndex];
  21533. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21534. }
  21535. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21536. }
  21537. if (parsedMesh.autoAnimate) {
  21538. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21539. }
  21540. // Layer Mask
  21541. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21542. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21543. }
  21544. else {
  21545. mesh.layerMask = 0x0FFFFFFF;
  21546. }
  21547. // Physics
  21548. if (parsedMesh.physicsImpostor) {
  21549. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21550. mass: parsedMesh.physicsMass,
  21551. friction: parsedMesh.physicsFriction,
  21552. restitution: parsedMesh.physicsRestitution
  21553. }, scene);
  21554. }
  21555. // Instances
  21556. if (parsedMesh.instances) {
  21557. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21558. var parsedInstance = parsedMesh.instances[index];
  21559. var instance = mesh.createInstance(parsedInstance.name);
  21560. if (BABYLON.Tags) {
  21561. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21562. }
  21563. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21564. if (parsedInstance.parentId) {
  21565. instance._waitingParentId = parsedInstance.parentId;
  21566. }
  21567. if (parsedInstance.rotationQuaternion) {
  21568. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21569. }
  21570. else if (parsedInstance.rotation) {
  21571. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21572. }
  21573. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21574. instance.checkCollisions = mesh.checkCollisions;
  21575. if (parsedMesh.animations) {
  21576. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21577. parsedAnimation = parsedMesh.animations[animationIndex];
  21578. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21579. }
  21580. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21581. }
  21582. }
  21583. }
  21584. return mesh;
  21585. };
  21586. /**
  21587. * Creates a ribbon mesh.
  21588. * Please consider using the same method from the MeshBuilder class instead.
  21589. * 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.
  21590. *
  21591. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21592. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21593. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21594. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21595. * 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.
  21596. * 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.
  21597. * 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
  21598. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21599. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21600. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21601. */
  21602. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21603. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21604. pathArray: pathArray,
  21605. closeArray: closeArray,
  21606. closePath: closePath,
  21607. offset: offset,
  21608. updatable: updatable,
  21609. sideOrientation: sideOrientation,
  21610. instance: instance
  21611. }, scene);
  21612. };
  21613. /**
  21614. * Creates a plane polygonal mesh. By default, this is a disc.
  21615. * Please consider using the same method from the MeshBuilder class instead.
  21616. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21617. * 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.
  21618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21619. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21621. */
  21622. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21623. var options = {
  21624. radius: radius,
  21625. tessellation: tessellation,
  21626. sideOrientation: sideOrientation,
  21627. updatable: updatable
  21628. };
  21629. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21630. };
  21631. /**
  21632. * Creates a box mesh.
  21633. * Please consider using the same method from the MeshBuilder class instead.
  21634. * The parameter `size` sets the size (float) of each box side (default 1).
  21635. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21636. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21638. */
  21639. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21640. var options = {
  21641. size: size,
  21642. sideOrientation: sideOrientation,
  21643. updatable: updatable
  21644. };
  21645. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21646. };
  21647. /**
  21648. * Creates a sphere mesh.
  21649. * Please consider using the same method from the MeshBuilder class instead.
  21650. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21651. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21652. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21653. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21654. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21655. */
  21656. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21657. var options = {
  21658. segments: segments,
  21659. diameterX: diameter,
  21660. diameterY: diameter,
  21661. diameterZ: diameter,
  21662. sideOrientation: sideOrientation,
  21663. updatable: updatable
  21664. };
  21665. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21666. };
  21667. /**
  21668. * Creates a cylinder or a cone mesh.
  21669. * Please consider using the same method from the MeshBuilder class instead.
  21670. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21671. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21672. * 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.
  21673. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21674. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21675. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21676. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21677. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21678. */
  21679. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21680. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21681. if (scene !== undefined) {
  21682. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21683. updatable = scene;
  21684. }
  21685. scene = subdivisions;
  21686. subdivisions = 1;
  21687. }
  21688. var options = {
  21689. height: height,
  21690. diameterTop: diameterTop,
  21691. diameterBottom: diameterBottom,
  21692. tessellation: tessellation,
  21693. subdivisions: subdivisions,
  21694. sideOrientation: sideOrientation,
  21695. updatable: updatable
  21696. };
  21697. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21698. };
  21699. // Torus (Code from SharpDX.org)
  21700. /**
  21701. * Creates a torus mesh.
  21702. * Please consider using the same method from the MeshBuilder class instead.
  21703. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21704. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21705. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21707. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21709. */
  21710. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21711. var options = {
  21712. diameter: diameter,
  21713. thickness: thickness,
  21714. tessellation: tessellation,
  21715. sideOrientation: sideOrientation,
  21716. updatable: updatable
  21717. };
  21718. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21719. };
  21720. /**
  21721. * Creates a torus knot mesh.
  21722. * Please consider using the same method from the MeshBuilder class instead.
  21723. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21724. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21725. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21726. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21728. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21730. */
  21731. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21732. var options = {
  21733. radius: radius,
  21734. tube: tube,
  21735. radialSegments: radialSegments,
  21736. tubularSegments: tubularSegments,
  21737. p: p,
  21738. q: q,
  21739. sideOrientation: sideOrientation,
  21740. updatable: updatable
  21741. };
  21742. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21743. };
  21744. /**
  21745. * Creates a line mesh.
  21746. * Please consider using the same method from the MeshBuilder class instead.
  21747. * 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.
  21748. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21749. * The parameter `points` is an array successive Vector3.
  21750. * 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
  21751. * When updating an instance, remember that only point positions can change, not the number of points.
  21752. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21753. */
  21754. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21755. var options = {
  21756. points: points,
  21757. updatable: updatable,
  21758. instance: instance
  21759. };
  21760. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21761. };
  21762. /**
  21763. * Creates a dashed line mesh.
  21764. * Please consider using the same method from the MeshBuilder class instead.
  21765. * 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.
  21766. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21767. * The parameter `points` is an array successive Vector3.
  21768. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21769. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21770. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21771. * 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
  21772. * When updating an instance, remember that only point positions can change, not the number of points.
  21773. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21774. */
  21775. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21776. var options = {
  21777. points: points,
  21778. dashSize: dashSize,
  21779. gapSize: gapSize,
  21780. dashNb: dashNb,
  21781. updatable: updatable,
  21782. instance: instance
  21783. };
  21784. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21785. };
  21786. /**
  21787. * Creates a polygon mesh.
  21788. * Please consider using the same method from the MeshBuilder class instead.
  21789. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21790. * 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.
  21791. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21792. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21793. * Remember you can only change the shape positions, not their number when updating a polygon.
  21794. */
  21795. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21796. var options = {
  21797. shape: shape,
  21798. holes: holes,
  21799. updatable: updatable,
  21800. sideOrientation: sideOrientation
  21801. };
  21802. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21803. };
  21804. /**
  21805. * Creates an extruded polygon mesh, with depth in the Y direction.
  21806. * Please consider using the same method from the MeshBuilder class instead.
  21807. */
  21808. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21809. var options = {
  21810. shape: shape,
  21811. holes: holes,
  21812. depth: depth,
  21813. updatable: updatable,
  21814. sideOrientation: sideOrientation
  21815. };
  21816. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21817. };
  21818. /**
  21819. * Creates an extruded shape mesh.
  21820. * 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.
  21821. * Please consider using the same method from the MeshBuilder class instead.
  21822. *
  21823. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21824. * 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
  21825. * extruded along the Z axis.
  21826. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21827. * 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.
  21828. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21829. * 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
  21830. * 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
  21831. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21832. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21833. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21835. */
  21836. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21837. var options = {
  21838. shape: shape,
  21839. path: path,
  21840. scale: scale,
  21841. rotation: rotation,
  21842. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21843. sideOrientation: sideOrientation,
  21844. instance: instance,
  21845. updatable: updatable
  21846. };
  21847. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21848. };
  21849. /**
  21850. * Creates an custom extruded shape mesh.
  21851. * 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.
  21852. * Please consider using the same method from the MeshBuilder class instead.
  21853. *
  21854. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21855. * 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
  21856. * extruded along the Z axis.
  21857. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21858. * 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
  21859. * and the distance of this point from the begining of the path :
  21860. * ```javascript
  21861. * var rotationFunction = function(i, distance) {
  21862. * // do things
  21863. * return rotationValue; }
  21864. * ```
  21865. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21866. * 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
  21867. * and the distance of this point from the begining of the path :
  21868. * ```javascript
  21869. * var scaleFunction = function(i, distance) {
  21870. * // do things
  21871. * return scaleValue;}
  21872. * ```
  21873. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21874. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21875. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21876. * 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
  21877. * 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
  21878. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21879. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21880. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21881. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21882. */
  21883. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21884. var options = {
  21885. shape: shape,
  21886. path: path,
  21887. scaleFunction: scaleFunction,
  21888. rotationFunction: rotationFunction,
  21889. ribbonCloseArray: ribbonCloseArray,
  21890. ribbonClosePath: ribbonClosePath,
  21891. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21892. sideOrientation: sideOrientation,
  21893. instance: instance,
  21894. updatable: updatable
  21895. };
  21896. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21897. };
  21898. /**
  21899. * Creates lathe mesh.
  21900. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21901. * Please consider using the same method from the MeshBuilder class instead.
  21902. * 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
  21903. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21904. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21905. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21907. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21908. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21909. */
  21910. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21911. var options = {
  21912. shape: shape,
  21913. radius: radius,
  21914. tessellation: tessellation,
  21915. sideOrientation: sideOrientation,
  21916. updatable: updatable
  21917. };
  21918. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21919. };
  21920. /**
  21921. * Creates a plane mesh.
  21922. * Please consider using the same method from the MeshBuilder class instead.
  21923. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21924. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21925. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21926. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21927. */
  21928. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21929. var options = {
  21930. size: size,
  21931. width: size,
  21932. height: size,
  21933. sideOrientation: sideOrientation,
  21934. updatable: updatable
  21935. };
  21936. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21937. };
  21938. /**
  21939. * Creates a ground mesh.
  21940. * Please consider using the same method from the MeshBuilder class instead.
  21941. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21942. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21944. */
  21945. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21946. var options = {
  21947. width: width,
  21948. height: height,
  21949. subdivisions: subdivisions,
  21950. updatable: updatable
  21951. };
  21952. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21953. };
  21954. /**
  21955. * Creates a tiled ground mesh.
  21956. * Please consider using the same method from the MeshBuilder class instead.
  21957. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21958. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21959. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21960. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21961. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21962. * numbers of subdivisions on the ground width and height of each tile.
  21963. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21964. */
  21965. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21966. var options = {
  21967. xmin: xmin,
  21968. zmin: zmin,
  21969. xmax: xmax,
  21970. zmax: zmax,
  21971. subdivisions: subdivisions,
  21972. precision: precision,
  21973. updatable: updatable
  21974. };
  21975. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21976. };
  21977. /**
  21978. * Creates a ground mesh from a height map.
  21979. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21980. * Please consider using the same method from the MeshBuilder class instead.
  21981. * The parameter `url` sets the URL of the height map image resource.
  21982. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21983. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21984. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21985. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21986. * 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).
  21987. * This function is passed the newly built mesh :
  21988. * ```javascript
  21989. * function(mesh) { // do things
  21990. * return; }
  21991. * ```
  21992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21993. */
  21994. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21995. var options = {
  21996. width: width,
  21997. height: height,
  21998. subdivisions: subdivisions,
  21999. minHeight: minHeight,
  22000. maxHeight: maxHeight,
  22001. updatable: updatable,
  22002. onReady: onReady
  22003. };
  22004. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22005. };
  22006. /**
  22007. * Creates a tube mesh.
  22008. * 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.
  22009. * Please consider using the same method from the MeshBuilder class instead.
  22010. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22011. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22012. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22013. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22014. * 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.
  22015. * It must return a radius value (positive float) :
  22016. * ```javascript
  22017. * var radiusFunction = function(i, distance) {
  22018. * // do things
  22019. * return radius; }
  22020. * ```
  22021. * 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
  22022. * 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
  22023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22024. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22025. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22026. */
  22027. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22028. var options = {
  22029. path: path,
  22030. radius: radius,
  22031. tessellation: tessellation,
  22032. radiusFunction: radiusFunction,
  22033. arc: 1,
  22034. cap: cap,
  22035. updatable: updatable,
  22036. sideOrientation: sideOrientation,
  22037. instance: instance
  22038. };
  22039. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22040. };
  22041. /**
  22042. * Creates a polyhedron mesh.
  22043. * Please consider using the same method from the MeshBuilder class instead.
  22044. * 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
  22045. * to choose the wanted type.
  22046. * The parameter `size` (positive float, default 1) sets the polygon size.
  22047. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22048. * 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`.
  22049. * 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
  22050. * 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)`).
  22051. * 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
  22052. * 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.
  22053. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22054. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22056. */
  22057. Mesh.CreatePolyhedron = function (name, options, scene) {
  22058. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22059. };
  22060. /**
  22061. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22062. * Please consider using the same method from the MeshBuilder class instead.
  22063. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22064. * 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`).
  22065. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22066. * 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.
  22067. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22068. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22070. */
  22071. Mesh.CreateIcoSphere = function (name, options, scene) {
  22072. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22073. };
  22074. /**
  22075. * Creates a decal mesh.
  22076. * Please consider using the same method from the MeshBuilder class instead.
  22077. * 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.
  22078. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22079. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22080. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22081. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22082. */
  22083. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22084. var options = {
  22085. position: position,
  22086. normal: normal,
  22087. size: size,
  22088. angle: angle
  22089. };
  22090. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22091. };
  22092. // Skeletons
  22093. /**
  22094. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22095. */
  22096. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22097. var source;
  22098. if (!this._sourcePositions) {
  22099. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22100. this._sourcePositions = new Float32Array(source);
  22101. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22102. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22103. }
  22104. }
  22105. return this._sourcePositions;
  22106. };
  22107. /**
  22108. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22109. */
  22110. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22111. var source;
  22112. if (!this._sourceNormals) {
  22113. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22114. this._sourceNormals = new Float32Array(source);
  22115. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22116. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22117. }
  22118. }
  22119. return this._sourceNormals;
  22120. };
  22121. /**
  22122. * Updates the vertex buffer by applying transformation from the bones.
  22123. * Returns the Mesh.
  22124. *
  22125. * @param {skeleton} skeleton to apply
  22126. */
  22127. Mesh.prototype.applySkeleton = function (skeleton) {
  22128. if (!this.geometry) {
  22129. return this;
  22130. }
  22131. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22132. return this;
  22133. }
  22134. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22135. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22136. return this;
  22137. }
  22138. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22139. return this;
  22140. }
  22141. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22142. return this;
  22143. }
  22144. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22145. return this;
  22146. }
  22147. if (!this._sourcePositions) {
  22148. var submeshes = this.subMeshes.slice();
  22149. this.setPositionsForCPUSkinning();
  22150. this.subMeshes = submeshes;
  22151. }
  22152. if (!this._sourceNormals) {
  22153. this.setNormalsForCPUSkinning();
  22154. }
  22155. // positionsData checks for not being Float32Array will only pass at most once
  22156. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22157. if (!(positionsData instanceof Float32Array)) {
  22158. positionsData = new Float32Array(positionsData);
  22159. }
  22160. // normalsData checks for not being Float32Array will only pass at most once
  22161. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22162. if (!(normalsData instanceof Float32Array)) {
  22163. normalsData = new Float32Array(normalsData);
  22164. }
  22165. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22166. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22167. var needExtras = this.numBoneInfluencers > 4;
  22168. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22169. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22170. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22171. var tempVector3 = BABYLON.Vector3.Zero();
  22172. var finalMatrix = new BABYLON.Matrix();
  22173. var tempMatrix = new BABYLON.Matrix();
  22174. var matWeightIdx = 0;
  22175. var inf;
  22176. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22177. var weight;
  22178. for (inf = 0; inf < 4; inf++) {
  22179. weight = matricesWeightsData[matWeightIdx + inf];
  22180. if (weight > 0) {
  22181. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22182. finalMatrix.addToSelf(tempMatrix);
  22183. }
  22184. else
  22185. break;
  22186. }
  22187. if (needExtras) {
  22188. for (inf = 0; inf < 4; inf++) {
  22189. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22190. if (weight > 0) {
  22191. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22192. finalMatrix.addToSelf(tempMatrix);
  22193. }
  22194. else
  22195. break;
  22196. }
  22197. }
  22198. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22199. tempVector3.toArray(positionsData, index);
  22200. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22201. tempVector3.toArray(normalsData, index);
  22202. finalMatrix.reset();
  22203. }
  22204. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22205. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22206. return this;
  22207. };
  22208. // Tools
  22209. /**
  22210. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22211. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22212. */
  22213. Mesh.MinMax = function (meshes) {
  22214. var minVector = null;
  22215. var maxVector = null;
  22216. meshes.forEach(function (mesh, index, array) {
  22217. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22218. if (!minVector) {
  22219. minVector = boundingBox.minimumWorld;
  22220. maxVector = boundingBox.maximumWorld;
  22221. }
  22222. else {
  22223. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22224. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22225. }
  22226. });
  22227. return {
  22228. min: minVector,
  22229. max: maxVector
  22230. };
  22231. };
  22232. /**
  22233. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22234. */
  22235. Mesh.Center = function (meshesOrMinMaxVector) {
  22236. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22237. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22238. };
  22239. /**
  22240. * Merge the array of meshes into a single mesh for performance reasons.
  22241. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22242. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22243. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22244. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22245. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22246. */
  22247. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22248. if (disposeSource === void 0) { disposeSource = true; }
  22249. var index;
  22250. if (!allow32BitsIndices) {
  22251. var totalVertices = 0;
  22252. // Counting vertices
  22253. for (index = 0; index < meshes.length; index++) {
  22254. if (meshes[index]) {
  22255. totalVertices += meshes[index].getTotalVertices();
  22256. if (totalVertices > 65536) {
  22257. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22258. return null;
  22259. }
  22260. }
  22261. }
  22262. }
  22263. // Merge
  22264. var vertexData;
  22265. var otherVertexData;
  22266. var indiceArray = new Array();
  22267. var source;
  22268. for (index = 0; index < meshes.length; index++) {
  22269. if (meshes[index]) {
  22270. meshes[index].computeWorldMatrix(true);
  22271. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22272. otherVertexData.transform(meshes[index].getWorldMatrix());
  22273. if (vertexData) {
  22274. vertexData.merge(otherVertexData);
  22275. }
  22276. else {
  22277. vertexData = otherVertexData;
  22278. source = meshes[index];
  22279. }
  22280. if (subdivideWithSubMeshes) {
  22281. indiceArray.push(meshes[index].getTotalIndices());
  22282. }
  22283. }
  22284. }
  22285. if (!meshSubclass) {
  22286. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22287. }
  22288. vertexData.applyToMesh(meshSubclass);
  22289. // Setting properties
  22290. meshSubclass.material = source.material;
  22291. meshSubclass.checkCollisions = source.checkCollisions;
  22292. // Cleaning
  22293. if (disposeSource) {
  22294. for (index = 0; index < meshes.length; index++) {
  22295. if (meshes[index]) {
  22296. meshes[index].dispose();
  22297. }
  22298. }
  22299. }
  22300. // Subdivide
  22301. if (subdivideWithSubMeshes) {
  22302. //-- Suppresions du submesh global
  22303. meshSubclass.releaseSubMeshes();
  22304. index = 0;
  22305. var offset = 0;
  22306. //-- aplique la subdivision en fonction du tableau d'indices
  22307. while (index < indiceArray.length) {
  22308. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22309. offset += indiceArray[index];
  22310. index++;
  22311. }
  22312. }
  22313. return meshSubclass;
  22314. };
  22315. return Mesh;
  22316. }(BABYLON.AbstractMesh));
  22317. // Consts
  22318. Mesh._FRONTSIDE = 0;
  22319. Mesh._BACKSIDE = 1;
  22320. Mesh._DOUBLESIDE = 2;
  22321. Mesh._DEFAULTSIDE = 0;
  22322. Mesh._NO_CAP = 0;
  22323. Mesh._CAP_START = 1;
  22324. Mesh._CAP_END = 2;
  22325. Mesh._CAP_ALL = 3;
  22326. BABYLON.Mesh = Mesh;
  22327. })(BABYLON || (BABYLON = {}));
  22328. //# sourceMappingURL=babylon.mesh.js.map
  22329. var BABYLON;
  22330. (function (BABYLON) {
  22331. var BaseSubMesh = (function () {
  22332. function BaseSubMesh() {
  22333. }
  22334. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  22335. get: function () {
  22336. return this._materialEffect;
  22337. },
  22338. enumerable: true,
  22339. configurable: true
  22340. });
  22341. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  22342. if (this._materialEffect === effect) {
  22343. return;
  22344. }
  22345. this._materialDefines = defines;
  22346. this._materialEffect = effect;
  22347. };
  22348. return BaseSubMesh;
  22349. }());
  22350. BABYLON.BaseSubMesh = BaseSubMesh;
  22351. var SubMesh = (function (_super) {
  22352. __extends(SubMesh, _super);
  22353. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22354. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22355. var _this = _super.call(this) || this;
  22356. _this.materialIndex = materialIndex;
  22357. _this.verticesStart = verticesStart;
  22358. _this.verticesCount = verticesCount;
  22359. _this.indexStart = indexStart;
  22360. _this.indexCount = indexCount;
  22361. _this._renderId = 0;
  22362. _this._mesh = mesh;
  22363. _this._renderingMesh = renderingMesh || mesh;
  22364. mesh.subMeshes.push(_this);
  22365. _this._trianglePlanes = [];
  22366. _this._id = mesh.subMeshes.length - 1;
  22367. if (createBoundingBox) {
  22368. _this.refreshBoundingInfo();
  22369. mesh.computeWorldMatrix(true);
  22370. }
  22371. return _this;
  22372. }
  22373. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22374. get: function () {
  22375. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22376. },
  22377. enumerable: true,
  22378. configurable: true
  22379. });
  22380. /**
  22381. * Returns the submesh BoudingInfo object.
  22382. */
  22383. SubMesh.prototype.getBoundingInfo = function () {
  22384. if (this.IsGlobal) {
  22385. return this._mesh.getBoundingInfo();
  22386. }
  22387. return this._boundingInfo;
  22388. };
  22389. /**
  22390. * Sets the submesh BoundingInfo.
  22391. * Return the SubMesh.
  22392. */
  22393. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22394. this._boundingInfo = boundingInfo;
  22395. return this;
  22396. };
  22397. /**
  22398. * Returns the mesh of the current submesh.
  22399. */
  22400. SubMesh.prototype.getMesh = function () {
  22401. return this._mesh;
  22402. };
  22403. /**
  22404. * Returns the rendering mesh of the submesh.
  22405. */
  22406. SubMesh.prototype.getRenderingMesh = function () {
  22407. return this._renderingMesh;
  22408. };
  22409. /**
  22410. * Returns the submesh material.
  22411. */
  22412. SubMesh.prototype.getMaterial = function () {
  22413. var rootMaterial = this._renderingMesh.material;
  22414. if (rootMaterial && rootMaterial.getSubMaterial) {
  22415. var multiMaterial = rootMaterial;
  22416. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22417. if (this._currentMaterial !== effectiveMaterial) {
  22418. this._currentMaterial = effectiveMaterial;
  22419. if (this._materialDefines) {
  22420. this._materialDefines.markAllAsDirty();
  22421. }
  22422. }
  22423. return effectiveMaterial;
  22424. }
  22425. if (!rootMaterial) {
  22426. return this._mesh.getScene().defaultMaterial;
  22427. }
  22428. return rootMaterial;
  22429. };
  22430. // Methods
  22431. /**
  22432. * Sets a new updated BoundingInfo object to the submesh.
  22433. * Returns the SubMesh.
  22434. */
  22435. SubMesh.prototype.refreshBoundingInfo = function () {
  22436. this._lastColliderWorldVertices = null;
  22437. if (this.IsGlobal) {
  22438. return;
  22439. }
  22440. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22441. if (!data) {
  22442. this._boundingInfo = this._mesh._boundingInfo;
  22443. return;
  22444. }
  22445. var indices = this._renderingMesh.getIndices();
  22446. var extend;
  22447. //is this the only submesh?
  22448. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22449. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22450. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22451. }
  22452. else {
  22453. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22454. }
  22455. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22456. return this;
  22457. };
  22458. SubMesh.prototype._checkCollision = function (collider) {
  22459. return this.getBoundingInfo()._checkCollision(collider);
  22460. };
  22461. /**
  22462. * Updates the submesh BoundingInfo.
  22463. * Returns the Submesh.
  22464. */
  22465. SubMesh.prototype.updateBoundingInfo = function (world) {
  22466. if (!this.getBoundingInfo()) {
  22467. this.refreshBoundingInfo();
  22468. }
  22469. this.getBoundingInfo().update(world);
  22470. return this;
  22471. };
  22472. /**
  22473. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22474. * Boolean returned.
  22475. */
  22476. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22477. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22478. };
  22479. /**
  22480. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22481. * Boolean returned.
  22482. */
  22483. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22484. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22485. };
  22486. /**
  22487. * Renders the submesh.
  22488. * Returns it.
  22489. */
  22490. SubMesh.prototype.render = function (enableAlphaMode) {
  22491. this._renderingMesh.render(this, enableAlphaMode);
  22492. return this;
  22493. };
  22494. /**
  22495. * Returns a new Index Buffer.
  22496. * Type returned : WebGLBuffer.
  22497. */
  22498. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22499. if (!this._linesIndexBuffer) {
  22500. var linesIndices = [];
  22501. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22502. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22503. }
  22504. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22505. this.linesIndexCount = linesIndices.length;
  22506. }
  22507. return this._linesIndexBuffer;
  22508. };
  22509. /**
  22510. * True is the passed Ray intersects the submesh bounding box.
  22511. * Boolean returned.
  22512. */
  22513. SubMesh.prototype.canIntersects = function (ray) {
  22514. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22515. };
  22516. /**
  22517. * Returns an object IntersectionInfo.
  22518. */
  22519. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22520. var intersectInfo = null;
  22521. // LineMesh first as it's also a Mesh...
  22522. if (this._mesh instanceof BABYLON.LinesMesh) {
  22523. var lineMesh = this._mesh;
  22524. // Line test
  22525. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22526. var p0 = positions[indices[index]];
  22527. var p1 = positions[indices[index + 1]];
  22528. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22529. if (length < 0) {
  22530. continue;
  22531. }
  22532. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22533. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22534. if (fastCheck) {
  22535. break;
  22536. }
  22537. }
  22538. }
  22539. }
  22540. else {
  22541. // Triangles test
  22542. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22543. var p0 = positions[indices[index]];
  22544. var p1 = positions[indices[index + 1]];
  22545. var p2 = positions[indices[index + 2]];
  22546. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22547. if (currentIntersectInfo) {
  22548. if (currentIntersectInfo.distance < 0) {
  22549. continue;
  22550. }
  22551. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22552. intersectInfo = currentIntersectInfo;
  22553. intersectInfo.faceId = index / 3;
  22554. if (fastCheck) {
  22555. break;
  22556. }
  22557. }
  22558. }
  22559. }
  22560. }
  22561. return intersectInfo;
  22562. };
  22563. // Clone
  22564. /**
  22565. * Creates a new Submesh from the passed Mesh.
  22566. */
  22567. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22568. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22569. if (!this.IsGlobal) {
  22570. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22571. }
  22572. return result;
  22573. };
  22574. // Dispose
  22575. /**
  22576. * Disposes the Submesh.
  22577. * Returns nothing.
  22578. */
  22579. SubMesh.prototype.dispose = function () {
  22580. if (this._linesIndexBuffer) {
  22581. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22582. this._linesIndexBuffer = null;
  22583. }
  22584. // Remove from mesh
  22585. var index = this._mesh.subMeshes.indexOf(this);
  22586. this._mesh.subMeshes.splice(index, 1);
  22587. };
  22588. // Statics
  22589. /**
  22590. * Creates a new Submesh from the passed parameters :
  22591. * - materialIndex (integer) : the index of the main mesh material.
  22592. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22593. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22594. * - mesh (Mesh) : the main mesh to create the submesh from.
  22595. * - renderingMesh (optional Mesh) : rendering mesh.
  22596. */
  22597. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22598. var minVertexIndex = Number.MAX_VALUE;
  22599. var maxVertexIndex = -Number.MAX_VALUE;
  22600. renderingMesh = renderingMesh || mesh;
  22601. var indices = renderingMesh.getIndices();
  22602. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22603. var vertexIndex = indices[index];
  22604. if (vertexIndex < minVertexIndex)
  22605. minVertexIndex = vertexIndex;
  22606. if (vertexIndex > maxVertexIndex)
  22607. maxVertexIndex = vertexIndex;
  22608. }
  22609. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22610. };
  22611. return SubMesh;
  22612. }(BaseSubMesh));
  22613. BABYLON.SubMesh = SubMesh;
  22614. })(BABYLON || (BABYLON = {}));
  22615. //# sourceMappingURL=babylon.subMesh.js.map
  22616. var BABYLON;
  22617. (function (BABYLON) {
  22618. var EffectFallbacks = (function () {
  22619. function EffectFallbacks() {
  22620. this._defines = {};
  22621. this._currentRank = 32;
  22622. this._maxRank = -1;
  22623. }
  22624. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22625. if (!this._defines[rank]) {
  22626. if (rank < this._currentRank) {
  22627. this._currentRank = rank;
  22628. }
  22629. if (rank > this._maxRank) {
  22630. this._maxRank = rank;
  22631. }
  22632. this._defines[rank] = new Array();
  22633. }
  22634. this._defines[rank].push(define);
  22635. };
  22636. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22637. this._meshRank = rank;
  22638. this._mesh = mesh;
  22639. if (rank < this._currentRank) {
  22640. this._currentRank = rank;
  22641. }
  22642. if (rank > this._maxRank) {
  22643. this._maxRank = rank;
  22644. }
  22645. };
  22646. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22647. get: function () {
  22648. return this._currentRank <= this._maxRank;
  22649. },
  22650. enumerable: true,
  22651. configurable: true
  22652. });
  22653. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22654. // First we try to switch to CPU skinning
  22655. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22656. this._mesh.computeBonesUsingShaders = false;
  22657. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22658. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22659. var scene = this._mesh.getScene();
  22660. for (var index = 0; index < scene.meshes.length; index++) {
  22661. var otherMesh = scene.meshes[index];
  22662. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22663. otherMesh.computeBonesUsingShaders = false;
  22664. }
  22665. }
  22666. }
  22667. else {
  22668. var currentFallbacks = this._defines[this._currentRank];
  22669. if (currentFallbacks) {
  22670. for (var index = 0; index < currentFallbacks.length; index++) {
  22671. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22672. }
  22673. }
  22674. this._currentRank++;
  22675. }
  22676. return currentDefines;
  22677. };
  22678. return EffectFallbacks;
  22679. }());
  22680. BABYLON.EffectFallbacks = EffectFallbacks;
  22681. var EffectCreationOptions = (function () {
  22682. function EffectCreationOptions() {
  22683. }
  22684. return EffectCreationOptions;
  22685. }());
  22686. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22687. var Effect = (function () {
  22688. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22689. var _this = this;
  22690. this.uniqueId = 0;
  22691. this.onCompileObservable = new BABYLON.Observable();
  22692. this.onErrorObservable = new BABYLON.Observable();
  22693. this.onBindObservable = new BABYLON.Observable();
  22694. this._uniformBuffersNames = {};
  22695. this._isReady = false;
  22696. this._compilationError = "";
  22697. this._valueCache = {};
  22698. this.name = baseName;
  22699. if (attributesNamesOrOptions.attributes) {
  22700. var options = attributesNamesOrOptions;
  22701. this._engine = uniformsNamesOrEngine;
  22702. this._attributesNames = options.attributes;
  22703. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22704. this._samplers = options.samplers;
  22705. this.defines = options.defines;
  22706. this.onError = options.onError;
  22707. this.onCompiled = options.onCompiled;
  22708. this._fallbacks = options.fallbacks;
  22709. this._indexParameters = options.indexParameters;
  22710. if (options.uniformBuffersNames) {
  22711. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22712. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22713. }
  22714. }
  22715. }
  22716. else {
  22717. this._engine = engine;
  22718. this.defines = defines;
  22719. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22720. this._samplers = samplers;
  22721. this._attributesNames = attributesNamesOrOptions;
  22722. this.onError = onError;
  22723. this.onCompiled = onCompiled;
  22724. this._indexParameters = indexParameters;
  22725. this._fallbacks = fallbacks;
  22726. }
  22727. this.uniqueId = Effect._uniqueIdSeed++;
  22728. var vertexSource;
  22729. var fragmentSource;
  22730. if (baseName.vertexElement) {
  22731. vertexSource = document.getElementById(baseName.vertexElement);
  22732. if (!vertexSource) {
  22733. vertexSource = baseName.vertexElement;
  22734. }
  22735. }
  22736. else {
  22737. vertexSource = baseName.vertex || baseName;
  22738. }
  22739. if (baseName.fragmentElement) {
  22740. fragmentSource = document.getElementById(baseName.fragmentElement);
  22741. if (!fragmentSource) {
  22742. fragmentSource = baseName.fragmentElement;
  22743. }
  22744. }
  22745. else {
  22746. fragmentSource = baseName.fragment || baseName;
  22747. }
  22748. this._loadVertexShader(vertexSource, function (vertexCode) {
  22749. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22750. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22751. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22752. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22753. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22754. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22755. });
  22756. });
  22757. });
  22758. });
  22759. });
  22760. });
  22761. }
  22762. Object.defineProperty(Effect.prototype, "key", {
  22763. get: function () {
  22764. return this._key;
  22765. },
  22766. enumerable: true,
  22767. configurable: true
  22768. });
  22769. // Properties
  22770. Effect.prototype.isReady = function () {
  22771. return this._isReady;
  22772. };
  22773. Effect.prototype.getEngine = function () {
  22774. return this._engine;
  22775. };
  22776. Effect.prototype.getProgram = function () {
  22777. return this._program;
  22778. };
  22779. Effect.prototype.getAttributesNames = function () {
  22780. return this._attributesNames;
  22781. };
  22782. Effect.prototype.getAttributeLocation = function (index) {
  22783. return this._attributes[index];
  22784. };
  22785. Effect.prototype.getAttributeLocationByName = function (name) {
  22786. var index = this._attributesNames.indexOf(name);
  22787. return this._attributes[index];
  22788. };
  22789. Effect.prototype.getAttributesCount = function () {
  22790. return this._attributes.length;
  22791. };
  22792. Effect.prototype.getUniformIndex = function (uniformName) {
  22793. return this._uniformsNames.indexOf(uniformName);
  22794. };
  22795. Effect.prototype.getUniform = function (uniformName) {
  22796. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22797. };
  22798. Effect.prototype.getSamplers = function () {
  22799. return this._samplers;
  22800. };
  22801. Effect.prototype.getCompilationError = function () {
  22802. return this._compilationError;
  22803. };
  22804. Effect.prototype.getVertexShaderSource = function () {
  22805. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22806. };
  22807. Effect.prototype.getFragmentShaderSource = function () {
  22808. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22809. };
  22810. // Methods
  22811. Effect.prototype.executeWhenCompiled = function (func) {
  22812. var _this = this;
  22813. if (this.isReady()) {
  22814. func(this);
  22815. return;
  22816. }
  22817. var observer = this.onCompileObservable.add(function (effect) {
  22818. _this.onCompileObservable.remove(observer);
  22819. func(effect);
  22820. });
  22821. };
  22822. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22823. // DOM element ?
  22824. if (vertex instanceof HTMLElement) {
  22825. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22826. callback(vertexCode);
  22827. return;
  22828. }
  22829. // Base64 encoded ?
  22830. if (vertex.substr(0, 7) === "base64:") {
  22831. var vertexBinary = window.atob(vertex.substr(7));
  22832. callback(vertexBinary);
  22833. return;
  22834. }
  22835. // Is in local store ?
  22836. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22837. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22838. return;
  22839. }
  22840. var vertexShaderUrl;
  22841. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22842. vertexShaderUrl = vertex;
  22843. }
  22844. else {
  22845. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22846. }
  22847. // Vertex shader
  22848. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22849. };
  22850. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22851. // DOM element ?
  22852. if (fragment instanceof HTMLElement) {
  22853. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22854. callback(fragmentCode);
  22855. return;
  22856. }
  22857. // Base64 encoded ?
  22858. if (fragment.substr(0, 7) === "base64:") {
  22859. var fragmentBinary = window.atob(fragment.substr(7));
  22860. callback(fragmentBinary);
  22861. return;
  22862. }
  22863. // Is in local store ?
  22864. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22865. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22866. return;
  22867. }
  22868. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22869. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22870. return;
  22871. }
  22872. var fragmentShaderUrl;
  22873. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22874. fragmentShaderUrl = fragment;
  22875. }
  22876. else {
  22877. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22878. }
  22879. // Fragment shader
  22880. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22881. };
  22882. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22883. // Rebuild shaders source code
  22884. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22885. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22886. vertexCode = prefix + vertexCode;
  22887. fragmentCode = prefix + fragmentCode;
  22888. // Number lines of shaders source code
  22889. var i = 2;
  22890. var regex = /\n/gm;
  22891. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22892. i = 2;
  22893. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22894. // Dump shaders name and formatted source code
  22895. if (this.name.vertexElement) {
  22896. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22897. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22898. }
  22899. else if (this.name.vertex) {
  22900. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22901. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22902. }
  22903. else {
  22904. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22905. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22906. }
  22907. };
  22908. ;
  22909. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22910. var preparedSourceCode = this._processPrecision(sourceCode);
  22911. if (this._engine.webGLVersion == 1) {
  22912. callback(preparedSourceCode);
  22913. return;
  22914. }
  22915. // Already converted
  22916. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22917. callback(preparedSourceCode.replace("#version 300 es", ""));
  22918. return;
  22919. }
  22920. // Remove extensions
  22921. // #extension GL_OES_standard_derivatives : enable
  22922. // #extension GL_EXT_shader_texture_lod : enable
  22923. // #extension GL_EXT_frag_depth : enable
  22924. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22925. var result = preparedSourceCode.replace(regex, "");
  22926. // Migrate to GLSL v300
  22927. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22928. result = result.replace(/attribute[ \t]/g, "in ");
  22929. result = result.replace(/[ \t]attribute/g, " in");
  22930. if (isFragment) {
  22931. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22932. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22933. result = result.replace(/texture2D\(/g, "texture(");
  22934. result = result.replace(/textureCube\(/g, "texture(");
  22935. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22936. result = result.replace(/gl_FragColor/g, "glFragColor");
  22937. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22938. }
  22939. callback(result);
  22940. };
  22941. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22942. var _this = this;
  22943. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22944. var match = regex.exec(sourceCode);
  22945. var returnValue = new String(sourceCode);
  22946. while (match != null) {
  22947. var includeFile = match[1];
  22948. // Uniform declaration
  22949. if (includeFile.indexOf("__decl__") !== -1) {
  22950. includeFile = includeFile.replace(/__decl__/, "");
  22951. if (this._engine.webGLVersion != 1) {
  22952. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22953. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22954. }
  22955. includeFile = includeFile + "Declaration";
  22956. }
  22957. if (Effect.IncludesShadersStore[includeFile]) {
  22958. // Substitution
  22959. var includeContent = Effect.IncludesShadersStore[includeFile];
  22960. if (match[2]) {
  22961. var splits = match[3].split(",");
  22962. for (var index = 0; index < splits.length; index += 2) {
  22963. var source = new RegExp(splits[index], "g");
  22964. var dest = splits[index + 1];
  22965. includeContent = includeContent.replace(source, dest);
  22966. }
  22967. }
  22968. if (match[4]) {
  22969. var indexString = match[5];
  22970. if (indexString.indexOf("..") !== -1) {
  22971. var indexSplits = indexString.split("..");
  22972. var minIndex = parseInt(indexSplits[0]);
  22973. var maxIndex = parseInt(indexSplits[1]);
  22974. var sourceIncludeContent = includeContent.slice(0);
  22975. includeContent = "";
  22976. if (isNaN(maxIndex)) {
  22977. maxIndex = this._indexParameters[indexSplits[1]];
  22978. }
  22979. for (var i = minIndex; i < maxIndex; i++) {
  22980. if (this._engine.webGLVersion === 1) {
  22981. // Ubo replacement
  22982. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22983. return p1 + "{X}";
  22984. });
  22985. }
  22986. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22987. }
  22988. }
  22989. else {
  22990. if (this._engine.webGLVersion === 1) {
  22991. // Ubo replacement
  22992. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22993. return p1 + "{X}";
  22994. });
  22995. }
  22996. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22997. }
  22998. }
  22999. // Replace
  23000. returnValue = returnValue.replace(match[0], includeContent);
  23001. }
  23002. else {
  23003. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23004. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23005. Effect.IncludesShadersStore[includeFile] = fileContent;
  23006. _this._processIncludes(returnValue, callback);
  23007. });
  23008. return;
  23009. }
  23010. match = regex.exec(sourceCode);
  23011. }
  23012. callback(returnValue);
  23013. };
  23014. Effect.prototype._processPrecision = function (source) {
  23015. if (source.indexOf("precision highp float") === -1) {
  23016. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23017. source = "precision mediump float;\n" + source;
  23018. }
  23019. else {
  23020. source = "precision highp float;\n" + source;
  23021. }
  23022. }
  23023. else {
  23024. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23025. source = source.replace("precision highp float", "precision mediump float");
  23026. }
  23027. }
  23028. return source;
  23029. };
  23030. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23031. try {
  23032. var engine = this._engine;
  23033. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23034. if (engine.webGLVersion > 1) {
  23035. for (var name in this._uniformBuffersNames) {
  23036. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  23037. }
  23038. }
  23039. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23040. this._attributes = engine.getAttributes(this._program, attributesNames);
  23041. var index;
  23042. for (index = 0; index < this._samplers.length; index++) {
  23043. var sampler = this.getUniform(this._samplers[index]);
  23044. if (sampler == null) {
  23045. this._samplers.splice(index, 1);
  23046. index--;
  23047. }
  23048. }
  23049. engine.bindSamplers(this);
  23050. this._compilationError = "";
  23051. this._isReady = true;
  23052. if (this.onCompiled) {
  23053. this.onCompiled(this);
  23054. }
  23055. this.onCompileObservable.notifyObservers(this);
  23056. }
  23057. catch (e) {
  23058. this._compilationError = e.message;
  23059. // Let's go through fallbacks then
  23060. BABYLON.Tools.Error("Unable to compile effect:");
  23061. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23062. return " " + uniform;
  23063. }));
  23064. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23065. return " " + attribute;
  23066. }));
  23067. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23068. BABYLON.Tools.Error("Error: " + this._compilationError);
  23069. if (fallbacks && fallbacks.isMoreFallbacks) {
  23070. BABYLON.Tools.Error("Trying next fallback.");
  23071. defines = fallbacks.reduce(defines);
  23072. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23073. }
  23074. else {
  23075. if (this.onError) {
  23076. this.onError(this, this._compilationError);
  23077. }
  23078. this.onErrorObservable.notifyObservers(this);
  23079. }
  23080. }
  23081. };
  23082. Object.defineProperty(Effect.prototype, "isSupported", {
  23083. get: function () {
  23084. return this._compilationError === "";
  23085. },
  23086. enumerable: true,
  23087. configurable: true
  23088. });
  23089. Effect.prototype._bindTexture = function (channel, texture) {
  23090. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23091. };
  23092. Effect.prototype.setTexture = function (channel, texture) {
  23093. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23094. };
  23095. Effect.prototype.setTextureArray = function (channel, textures) {
  23096. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23097. var initialPos = this._samplers.indexOf(channel);
  23098. for (var index = 1; index < textures.length; index++) {
  23099. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23100. }
  23101. }
  23102. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23103. };
  23104. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23105. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23106. };
  23107. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23108. var cache = this._valueCache[uniformName];
  23109. var flag = matrix.updateFlag;
  23110. if (cache !== undefined && cache === flag) {
  23111. return false;
  23112. }
  23113. this._valueCache[uniformName] = flag;
  23114. return true;
  23115. };
  23116. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23117. var cache = this._valueCache[uniformName];
  23118. if (!cache) {
  23119. cache = [x, y];
  23120. this._valueCache[uniformName] = cache;
  23121. return true;
  23122. }
  23123. var changed = false;
  23124. if (cache[0] !== x) {
  23125. cache[0] = x;
  23126. changed = true;
  23127. }
  23128. if (cache[1] !== y) {
  23129. cache[1] = y;
  23130. changed = true;
  23131. }
  23132. return changed;
  23133. };
  23134. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23135. var cache = this._valueCache[uniformName];
  23136. if (!cache) {
  23137. cache = [x, y, z];
  23138. this._valueCache[uniformName] = cache;
  23139. return true;
  23140. }
  23141. var changed = false;
  23142. if (cache[0] !== x) {
  23143. cache[0] = x;
  23144. changed = true;
  23145. }
  23146. if (cache[1] !== y) {
  23147. cache[1] = y;
  23148. changed = true;
  23149. }
  23150. if (cache[2] !== z) {
  23151. cache[2] = z;
  23152. changed = true;
  23153. }
  23154. return changed;
  23155. };
  23156. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23157. var cache = this._valueCache[uniformName];
  23158. if (!cache) {
  23159. cache = [x, y, z, w];
  23160. this._valueCache[uniformName] = cache;
  23161. return true;
  23162. }
  23163. var changed = false;
  23164. if (cache[0] !== x) {
  23165. cache[0] = x;
  23166. changed = true;
  23167. }
  23168. if (cache[1] !== y) {
  23169. cache[1] = y;
  23170. changed = true;
  23171. }
  23172. if (cache[2] !== z) {
  23173. cache[2] = z;
  23174. changed = true;
  23175. }
  23176. if (cache[3] !== w) {
  23177. cache[3] = w;
  23178. changed = true;
  23179. }
  23180. return changed;
  23181. };
  23182. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23183. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23184. return;
  23185. }
  23186. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23187. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23188. };
  23189. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23190. this._engine.bindUniformBlock(this._program, blockName, index);
  23191. };
  23192. Effect.prototype.setIntArray = function (uniformName, array) {
  23193. this._valueCache[uniformName] = null;
  23194. this._engine.setIntArray(this.getUniform(uniformName), array);
  23195. return this;
  23196. };
  23197. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23198. this._valueCache[uniformName] = null;
  23199. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23200. return this;
  23201. };
  23202. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23203. this._valueCache[uniformName] = null;
  23204. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23205. return this;
  23206. };
  23207. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23208. this._valueCache[uniformName] = null;
  23209. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23210. return this;
  23211. };
  23212. Effect.prototype.setFloatArray = function (uniformName, array) {
  23213. this._valueCache[uniformName] = null;
  23214. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23215. return this;
  23216. };
  23217. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23218. this._valueCache[uniformName] = null;
  23219. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23220. return this;
  23221. };
  23222. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23223. this._valueCache[uniformName] = null;
  23224. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23225. return this;
  23226. };
  23227. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23228. this._valueCache[uniformName] = null;
  23229. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23230. return this;
  23231. };
  23232. Effect.prototype.setArray = function (uniformName, array) {
  23233. this._valueCache[uniformName] = null;
  23234. this._engine.setArray(this.getUniform(uniformName), array);
  23235. return this;
  23236. };
  23237. Effect.prototype.setArray2 = function (uniformName, array) {
  23238. this._valueCache[uniformName] = null;
  23239. this._engine.setArray2(this.getUniform(uniformName), array);
  23240. return this;
  23241. };
  23242. Effect.prototype.setArray3 = function (uniformName, array) {
  23243. this._valueCache[uniformName] = null;
  23244. this._engine.setArray3(this.getUniform(uniformName), array);
  23245. return this;
  23246. };
  23247. Effect.prototype.setArray4 = function (uniformName, array) {
  23248. this._valueCache[uniformName] = null;
  23249. this._engine.setArray4(this.getUniform(uniformName), array);
  23250. return this;
  23251. };
  23252. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23253. if (!matrices) {
  23254. return;
  23255. }
  23256. this._valueCache[uniformName] = null;
  23257. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23258. return this;
  23259. };
  23260. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23261. if (this._cacheMatrix(uniformName, matrix)) {
  23262. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23263. }
  23264. return this;
  23265. };
  23266. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23267. this._valueCache[uniformName] = null;
  23268. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23269. return this;
  23270. };
  23271. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23272. this._valueCache[uniformName] = null;
  23273. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23274. return this;
  23275. };
  23276. Effect.prototype.setFloat = function (uniformName, value) {
  23277. var cache = this._valueCache[uniformName];
  23278. if (cache !== undefined && cache === value)
  23279. return this;
  23280. this._valueCache[uniformName] = value;
  23281. this._engine.setFloat(this.getUniform(uniformName), value);
  23282. return this;
  23283. };
  23284. Effect.prototype.setBool = function (uniformName, bool) {
  23285. var cache = this._valueCache[uniformName];
  23286. if (cache !== undefined && cache === bool)
  23287. return this;
  23288. this._valueCache[uniformName] = bool;
  23289. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23290. return this;
  23291. };
  23292. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23293. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23294. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23295. }
  23296. return this;
  23297. };
  23298. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23299. if (this._cacheFloat2(uniformName, x, y)) {
  23300. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23301. }
  23302. return this;
  23303. };
  23304. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23305. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23306. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23307. }
  23308. return this;
  23309. };
  23310. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23311. if (this._cacheFloat3(uniformName, x, y, z)) {
  23312. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23313. }
  23314. return this;
  23315. };
  23316. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23317. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23318. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23319. }
  23320. return this;
  23321. };
  23322. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23323. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23324. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23325. }
  23326. return this;
  23327. };
  23328. Effect.prototype.setColor3 = function (uniformName, color3) {
  23329. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23330. this._engine.setColor3(this.getUniform(uniformName), color3);
  23331. }
  23332. return this;
  23333. };
  23334. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23335. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23336. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23337. }
  23338. return this;
  23339. };
  23340. Effect.prototype._recombineShader = function (node) {
  23341. if (node.define) {
  23342. if (node.condition) {
  23343. var defineIndex = this.defines.indexOf("#define " + node.define);
  23344. if (defineIndex === -1) {
  23345. return null;
  23346. }
  23347. var nextComma = this.defines.indexOf("\n", defineIndex);
  23348. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23349. var condition = defineValue + node.condition;
  23350. if (!eval(condition)) {
  23351. return null;
  23352. }
  23353. }
  23354. else if (node.ndef) {
  23355. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23356. return null;
  23357. }
  23358. }
  23359. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23360. return null;
  23361. }
  23362. }
  23363. var result = "";
  23364. for (var index = 0; index < node.children.length; index++) {
  23365. var line = node.children[index];
  23366. if (line.children) {
  23367. var combined = this._recombineShader(line);
  23368. if (combined !== null) {
  23369. result += combined + "\r\n";
  23370. }
  23371. continue;
  23372. }
  23373. if (line.length > 0) {
  23374. result += line + "\r\n";
  23375. }
  23376. }
  23377. return result;
  23378. };
  23379. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23380. var root = {
  23381. children: []
  23382. };
  23383. var currentNode = root;
  23384. var lines = shaderString.split("\n");
  23385. for (var index = 0; index < lines.length; index++) {
  23386. var line = lines[index].trim();
  23387. // #ifdef
  23388. var pos = line.indexOf("#ifdef ");
  23389. if (pos !== -1) {
  23390. var define = line.substr(pos + 7);
  23391. var newNode = {
  23392. condition: null,
  23393. ndef: false,
  23394. define: define,
  23395. children: [],
  23396. parent: currentNode
  23397. };
  23398. currentNode.children.push(newNode);
  23399. currentNode = newNode;
  23400. continue;
  23401. }
  23402. // #ifndef
  23403. var pos = line.indexOf("#ifndef ");
  23404. if (pos !== -1) {
  23405. var define = line.substr(pos + 8);
  23406. newNode = {
  23407. condition: null,
  23408. define: define,
  23409. ndef: true,
  23410. children: [],
  23411. parent: currentNode
  23412. };
  23413. currentNode.children.push(newNode);
  23414. currentNode = newNode;
  23415. continue;
  23416. }
  23417. // #if
  23418. var pos = line.indexOf("#if ");
  23419. if (pos !== -1) {
  23420. var define = line.substr(pos + 4).trim();
  23421. var conditionPos = define.indexOf(" ");
  23422. newNode = {
  23423. condition: define.substr(conditionPos + 1),
  23424. define: define.substr(0, conditionPos),
  23425. ndef: false,
  23426. children: [],
  23427. parent: currentNode
  23428. };
  23429. currentNode.children.push(newNode);
  23430. currentNode = newNode;
  23431. continue;
  23432. }
  23433. // #endif
  23434. pos = line.indexOf("#endif");
  23435. if (pos !== -1) {
  23436. currentNode = currentNode.parent;
  23437. continue;
  23438. }
  23439. currentNode.children.push(line);
  23440. }
  23441. // Recombine
  23442. return this._recombineShader(root);
  23443. };
  23444. return Effect;
  23445. }());
  23446. Effect._uniqueIdSeed = 0;
  23447. Effect._baseCache = {};
  23448. // Statics
  23449. Effect.ShadersStore = {};
  23450. Effect.IncludesShadersStore = {};
  23451. BABYLON.Effect = Effect;
  23452. })(BABYLON || (BABYLON = {}));
  23453. //# sourceMappingURL=babylon.effect.js.map
  23454. var BABYLON;
  23455. (function (BABYLON) {
  23456. var MaterialHelper = (function () {
  23457. function MaterialHelper() {
  23458. }
  23459. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23460. if (defines._areMiscDirty) {
  23461. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23462. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23463. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23464. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23465. }
  23466. };
  23467. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23468. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23469. var changed = false;
  23470. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23471. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23472. changed = true;
  23473. }
  23474. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23475. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23476. changed = true;
  23477. }
  23478. if (defines["INSTANCES"] !== useInstances) {
  23479. defines["INSTANCES"] = useInstances;
  23480. changed = true;
  23481. }
  23482. if (changed) {
  23483. defines.markAsUnprocessed();
  23484. }
  23485. };
  23486. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23487. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23488. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23489. return false;
  23490. }
  23491. defines._normals = defines._needNormals;
  23492. defines._uvs = defines._needUVs;
  23493. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23494. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23495. defines["TANGENT"] = true;
  23496. }
  23497. if (defines._needUVs) {
  23498. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23499. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23500. }
  23501. else {
  23502. defines["UV1"] = false;
  23503. defines["UV2"] = false;
  23504. }
  23505. if (useVertexColor) {
  23506. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23507. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23508. }
  23509. if (useBones) {
  23510. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23511. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23512. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23513. }
  23514. else {
  23515. defines["NUM_BONE_INFLUENCERS"] = 0;
  23516. defines["BonesPerMesh"] = 0;
  23517. }
  23518. }
  23519. if (useMorphTargets) {
  23520. if (mesh.morphTargetManager) {
  23521. var manager = mesh.morphTargetManager;
  23522. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23523. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23524. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23525. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23526. }
  23527. else {
  23528. defines["MORPHTARGETS_TANGENT"] = false;
  23529. defines["MORPHTARGETS_NORMAL"] = false;
  23530. defines["MORPHTARGETS"] = false;
  23531. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23532. }
  23533. }
  23534. return true;
  23535. };
  23536. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23537. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23538. if (disableLighting === void 0) { disableLighting = false; }
  23539. if (!defines._areLightsDirty) {
  23540. return defines._needNormals;
  23541. }
  23542. var lightIndex = 0;
  23543. var needNormals = false;
  23544. var needRebuild = false;
  23545. var lightmapMode = false;
  23546. var shadowEnabled = false;
  23547. var specularEnabled = false;
  23548. if (scene.lightsEnabled && !disableLighting) {
  23549. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23550. var light = _a[_i];
  23551. needNormals = true;
  23552. if (defines["LIGHT" + lightIndex] === undefined) {
  23553. needRebuild = true;
  23554. }
  23555. defines["LIGHT" + lightIndex] = true;
  23556. defines["SPOTLIGHT" + lightIndex] = false;
  23557. defines["HEMILIGHT" + lightIndex] = false;
  23558. defines["POINTLIGHT" + lightIndex] = false;
  23559. defines["DIRLIGHT" + lightIndex] = false;
  23560. var type;
  23561. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23562. type = "SPOTLIGHT" + lightIndex;
  23563. }
  23564. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23565. type = "HEMILIGHT" + lightIndex;
  23566. }
  23567. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23568. type = "POINTLIGHT" + lightIndex;
  23569. }
  23570. else {
  23571. type = "DIRLIGHT" + lightIndex;
  23572. }
  23573. defines[type] = true;
  23574. // Specular
  23575. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23576. specularEnabled = true;
  23577. }
  23578. // Shadows
  23579. defines["SHADOW" + lightIndex] = false;
  23580. defines["SHADOWPCF" + lightIndex] = false;
  23581. defines["SHADOWESM" + lightIndex] = false;
  23582. defines["SHADOWCUBE" + lightIndex] = false;
  23583. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23584. var shadowGenerator = light.getShadowGenerator();
  23585. if (shadowGenerator) {
  23586. shadowEnabled = true;
  23587. shadowGenerator.prepareDefines(defines, lightIndex);
  23588. }
  23589. }
  23590. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23591. lightmapMode = true;
  23592. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23593. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23594. }
  23595. else {
  23596. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23597. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23598. }
  23599. lightIndex++;
  23600. if (lightIndex === maxSimultaneousLights)
  23601. break;
  23602. }
  23603. }
  23604. defines["SPECULARTERM"] = specularEnabled;
  23605. defines["SHADOWS"] = shadowEnabled;
  23606. // Resetting all other lights if any
  23607. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23608. if (defines["LIGHT" + index] !== undefined) {
  23609. defines["LIGHT" + index] = false;
  23610. defines["HEMILIGHT" + lightIndex] = false;
  23611. defines["POINTLIGHT" + lightIndex] = false;
  23612. defines["DIRLIGHT" + lightIndex] = false;
  23613. defines["SPOTLIGHT" + lightIndex] = false;
  23614. defines["SHADOW" + lightIndex] = false;
  23615. }
  23616. }
  23617. var caps = scene.getEngine().getCaps();
  23618. if (defines["SHADOWFLOAT"] === undefined) {
  23619. needRebuild = true;
  23620. }
  23621. defines["SHADOWFLOAT"] = shadowEnabled &&
  23622. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23623. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23624. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23625. if (needRebuild) {
  23626. defines.rebuild();
  23627. }
  23628. return needNormals;
  23629. };
  23630. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23631. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23632. var uniformsList, uniformBuffersList, samplersList, defines;
  23633. if (uniformsListOrOptions.uniformsNames) {
  23634. var options = uniformsListOrOptions;
  23635. uniformsList = options.uniformsNames;
  23636. uniformBuffersList = options.uniformBuffersNames;
  23637. samplersList = options.samplers;
  23638. defines = options.defines;
  23639. maxSimultaneousLights = options.maxSimultaneousLights;
  23640. }
  23641. else {
  23642. uniformsList = uniformsListOrOptions;
  23643. }
  23644. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23645. if (!defines["LIGHT" + lightIndex]) {
  23646. break;
  23647. }
  23648. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  23649. if (uniformBuffersList) {
  23650. uniformBuffersList.push("Light" + lightIndex);
  23651. }
  23652. samplersList.push("shadowSampler" + lightIndex);
  23653. }
  23654. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23655. uniformsList.push("morphTargetInfluences");
  23656. }
  23657. };
  23658. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23659. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23660. if (!defines["SHADOWS"]) {
  23661. return;
  23662. }
  23663. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23664. if (!defines["LIGHT" + lightIndex]) {
  23665. break;
  23666. }
  23667. if (lightIndex > 0) {
  23668. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23669. }
  23670. if (defines["SHADOW" + lightIndex]) {
  23671. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23672. }
  23673. if (defines["SHADOWPCF" + lightIndex]) {
  23674. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23675. }
  23676. if (defines["SHADOWESM" + lightIndex]) {
  23677. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23678. }
  23679. }
  23680. };
  23681. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23682. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23683. if (influencers > 0) {
  23684. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23685. var manager = mesh.morphTargetManager;
  23686. var normal = manager.supportsNormals && defines["NORMAL"];
  23687. var tangent = manager.supportsTangents && defines["TANGENT"];
  23688. for (var index = 0; index < influencers; index++) {
  23689. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23690. if (normal) {
  23691. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23692. }
  23693. if (tangent) {
  23694. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23695. }
  23696. if (attribs.length > maxAttributesCount) {
  23697. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23698. }
  23699. }
  23700. }
  23701. };
  23702. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23703. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23704. fallbacks.addCPUSkinningFallback(0, mesh);
  23705. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23706. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23707. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23708. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23709. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23710. }
  23711. }
  23712. };
  23713. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23714. if (defines["INSTANCES"]) {
  23715. attribs.push("world0");
  23716. attribs.push("world1");
  23717. attribs.push("world2");
  23718. attribs.push("world3");
  23719. }
  23720. };
  23721. // Bindings
  23722. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  23723. if (light.shadowEnabled && mesh.receiveShadows) {
  23724. var shadowGenerator = light.getShadowGenerator();
  23725. if (shadowGenerator) {
  23726. shadowGenerator.bindShadowLight(lightIndex, effect);
  23727. }
  23728. }
  23729. };
  23730. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23731. light.transferToEffect(effect, lightIndex + "");
  23732. };
  23733. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  23734. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23735. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  23736. var lightIndex = 0;
  23737. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23738. var light = _a[_i];
  23739. var scaledIntensity = light.getScaledIntensity();
  23740. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23741. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23742. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  23743. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  23744. if (defines["SPECULARTERM"]) {
  23745. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  23746. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23747. }
  23748. // Shadows
  23749. if (scene.shadowsEnabled) {
  23750. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  23751. }
  23752. light._uniformBuffer.update();
  23753. lightIndex++;
  23754. if (lightIndex === maxSimultaneousLights)
  23755. break;
  23756. }
  23757. };
  23758. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23759. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23760. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23761. effect.setColor3("vFogColor", scene.fogColor);
  23762. }
  23763. };
  23764. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23765. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23766. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23767. if (matrices) {
  23768. effect.setMatrices("mBones", matrices);
  23769. }
  23770. }
  23771. };
  23772. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23773. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23774. return;
  23775. }
  23776. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23777. };
  23778. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23779. if (defines["LOGARITHMICDEPTH"]) {
  23780. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23781. }
  23782. };
  23783. MaterialHelper.BindClipPlane = function (effect, scene) {
  23784. if (scene.clipPlane) {
  23785. var clipPlane = scene.clipPlane;
  23786. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23787. }
  23788. };
  23789. return MaterialHelper;
  23790. }());
  23791. BABYLON.MaterialHelper = MaterialHelper;
  23792. })(BABYLON || (BABYLON = {}));
  23793. //# sourceMappingURL=babylon.materialHelper.js.map
  23794. var BABYLON;
  23795. (function (BABYLON) {
  23796. var MaterialDefines = (function () {
  23797. function MaterialDefines() {
  23798. this._isDirty = true;
  23799. this._areLightsDirty = true;
  23800. this._areAttributesDirty = true;
  23801. this._areTexturesDirty = true;
  23802. this._areFresnelDirty = true;
  23803. this._areMiscDirty = true;
  23804. this._areImageProcessingDirty = true;
  23805. this._normals = false;
  23806. this._uvs = false;
  23807. this._needNormals = false;
  23808. this._needUVs = false;
  23809. }
  23810. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23811. get: function () {
  23812. return this._isDirty;
  23813. },
  23814. enumerable: true,
  23815. configurable: true
  23816. });
  23817. MaterialDefines.prototype.markAsProcessed = function () {
  23818. this._isDirty = false;
  23819. this._areAttributesDirty = false;
  23820. this._areTexturesDirty = false;
  23821. this._areFresnelDirty = false;
  23822. this._areLightsDirty = false;
  23823. this._areMiscDirty = false;
  23824. this._areImageProcessingDirty = false;
  23825. };
  23826. MaterialDefines.prototype.markAsUnprocessed = function () {
  23827. this._isDirty = true;
  23828. };
  23829. MaterialDefines.prototype.markAllAsDirty = function () {
  23830. this._areTexturesDirty = true;
  23831. this._areAttributesDirty = true;
  23832. this._areLightsDirty = true;
  23833. this._areFresnelDirty = true;
  23834. this._areMiscDirty = true;
  23835. this._areImageProcessingDirty = true;
  23836. this._isDirty = true;
  23837. };
  23838. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  23839. this._areImageProcessingDirty = true;
  23840. this._isDirty = true;
  23841. };
  23842. MaterialDefines.prototype.markAsLightDirty = function () {
  23843. this._areLightsDirty = true;
  23844. this._isDirty = true;
  23845. };
  23846. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23847. this._areAttributesDirty = true;
  23848. this._isDirty = true;
  23849. };
  23850. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23851. this._areTexturesDirty = true;
  23852. this._isDirty = true;
  23853. };
  23854. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23855. this._areFresnelDirty = true;
  23856. this._isDirty = true;
  23857. };
  23858. MaterialDefines.prototype.markAsMiscDirty = function () {
  23859. this._areMiscDirty = true;
  23860. this._isDirty = true;
  23861. };
  23862. MaterialDefines.prototype.rebuild = function () {
  23863. if (this._keys) {
  23864. delete this._keys;
  23865. }
  23866. this._keys = [];
  23867. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23868. var key = _a[_i];
  23869. if (key[0] === "_") {
  23870. continue;
  23871. }
  23872. this._keys.push(key);
  23873. }
  23874. };
  23875. MaterialDefines.prototype.isEqual = function (other) {
  23876. if (this._keys.length !== other._keys.length) {
  23877. return false;
  23878. }
  23879. for (var index = 0; index < this._keys.length; index++) {
  23880. var prop = this._keys[index];
  23881. if (this[prop] !== other[prop]) {
  23882. return false;
  23883. }
  23884. }
  23885. return true;
  23886. };
  23887. MaterialDefines.prototype.cloneTo = function (other) {
  23888. if (this._keys.length !== other._keys.length) {
  23889. other._keys = this._keys.slice(0);
  23890. }
  23891. for (var index = 0; index < this._keys.length; index++) {
  23892. var prop = this._keys[index];
  23893. other[prop] = this[prop];
  23894. }
  23895. };
  23896. MaterialDefines.prototype.reset = function () {
  23897. for (var index = 0; index < this._keys.length; index++) {
  23898. var prop = this._keys[index];
  23899. if (typeof (this[prop]) === "number") {
  23900. this[prop] = 0;
  23901. }
  23902. else {
  23903. this[prop] = false;
  23904. }
  23905. }
  23906. };
  23907. MaterialDefines.prototype.toString = function () {
  23908. var result = "";
  23909. for (var index = 0; index < this._keys.length; index++) {
  23910. var prop = this._keys[index];
  23911. var value = this[prop];
  23912. if (typeof (value) === "number") {
  23913. result += "#define " + prop + " " + this[prop] + "\n";
  23914. }
  23915. else if (value) {
  23916. result += "#define " + prop + "\n";
  23917. }
  23918. }
  23919. return result;
  23920. };
  23921. return MaterialDefines;
  23922. }());
  23923. BABYLON.MaterialDefines = MaterialDefines;
  23924. var Material = (function () {
  23925. function Material(name, scene, doNotAdd) {
  23926. this.checkReadyOnEveryCall = false;
  23927. this.checkReadyOnlyOnce = false;
  23928. this.state = "";
  23929. this.alpha = 1.0;
  23930. this._backFaceCulling = true;
  23931. this.doNotSerialize = false;
  23932. this.storeEffectOnSubMeshes = false;
  23933. /**
  23934. * An event triggered when the material is disposed.
  23935. * @type {BABYLON.Observable}
  23936. */
  23937. this.onDisposeObservable = new BABYLON.Observable();
  23938. /**
  23939. * An event triggered when the material is bound.
  23940. * @type {BABYLON.Observable}
  23941. */
  23942. this.onBindObservable = new BABYLON.Observable();
  23943. /**
  23944. * An event triggered when the material is unbound.
  23945. * @type {BABYLON.Observable}
  23946. */
  23947. this.onUnBindObservable = new BABYLON.Observable();
  23948. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23949. this.disableDepthWrite = false;
  23950. this._fogEnabled = true;
  23951. this.pointSize = 1.0;
  23952. this.zOffset = 0;
  23953. this._wasPreviouslyReady = false;
  23954. this._fillMode = Material.TriangleFillMode;
  23955. this.name = name;
  23956. this.id = name;
  23957. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23958. if (this._scene.useRightHandedSystem) {
  23959. this.sideOrientation = Material.ClockWiseSideOrientation;
  23960. }
  23961. else {
  23962. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23963. }
  23964. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23965. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23966. if (!doNotAdd) {
  23967. this._scene.materials.push(this);
  23968. }
  23969. }
  23970. Object.defineProperty(Material, "TriangleFillMode", {
  23971. get: function () {
  23972. return Material._TriangleFillMode;
  23973. },
  23974. enumerable: true,
  23975. configurable: true
  23976. });
  23977. Object.defineProperty(Material, "WireFrameFillMode", {
  23978. get: function () {
  23979. return Material._WireFrameFillMode;
  23980. },
  23981. enumerable: true,
  23982. configurable: true
  23983. });
  23984. Object.defineProperty(Material, "PointFillMode", {
  23985. get: function () {
  23986. return Material._PointFillMode;
  23987. },
  23988. enumerable: true,
  23989. configurable: true
  23990. });
  23991. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23992. get: function () {
  23993. return Material._ClockWiseSideOrientation;
  23994. },
  23995. enumerable: true,
  23996. configurable: true
  23997. });
  23998. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23999. get: function () {
  24000. return Material._CounterClockWiseSideOrientation;
  24001. },
  24002. enumerable: true,
  24003. configurable: true
  24004. });
  24005. Object.defineProperty(Material, "TextureDirtyFlag", {
  24006. get: function () {
  24007. return Material._TextureDirtyFlag;
  24008. },
  24009. enumerable: true,
  24010. configurable: true
  24011. });
  24012. Object.defineProperty(Material, "LightDirtyFlag", {
  24013. get: function () {
  24014. return Material._LightDirtyFlag;
  24015. },
  24016. enumerable: true,
  24017. configurable: true
  24018. });
  24019. Object.defineProperty(Material, "FresnelDirtyFlag", {
  24020. get: function () {
  24021. return Material._FresnelDirtyFlag;
  24022. },
  24023. enumerable: true,
  24024. configurable: true
  24025. });
  24026. Object.defineProperty(Material, "AttributesDirtyFlag", {
  24027. get: function () {
  24028. return Material._AttributesDirtyFlag;
  24029. },
  24030. enumerable: true,
  24031. configurable: true
  24032. });
  24033. Object.defineProperty(Material, "MiscDirtyFlag", {
  24034. get: function () {
  24035. return Material._MiscDirtyFlag;
  24036. },
  24037. enumerable: true,
  24038. configurable: true
  24039. });
  24040. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24041. get: function () {
  24042. return this._backFaceCulling;
  24043. },
  24044. set: function (value) {
  24045. if (this._backFaceCulling === value) {
  24046. return;
  24047. }
  24048. this._backFaceCulling = value;
  24049. this.markAsDirty(Material.TextureDirtyFlag);
  24050. },
  24051. enumerable: true,
  24052. configurable: true
  24053. });
  24054. Object.defineProperty(Material.prototype, "onDispose", {
  24055. set: function (callback) {
  24056. if (this._onDisposeObserver) {
  24057. this.onDisposeObservable.remove(this._onDisposeObserver);
  24058. }
  24059. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24060. },
  24061. enumerable: true,
  24062. configurable: true
  24063. });
  24064. Object.defineProperty(Material.prototype, "onBind", {
  24065. set: function (callback) {
  24066. if (this._onBindObserver) {
  24067. this.onBindObservable.remove(this._onBindObserver);
  24068. }
  24069. this._onBindObserver = this.onBindObservable.add(callback);
  24070. },
  24071. enumerable: true,
  24072. configurable: true
  24073. });
  24074. Object.defineProperty(Material.prototype, "fogEnabled", {
  24075. get: function () {
  24076. return this._fogEnabled;
  24077. },
  24078. set: function (value) {
  24079. if (this._fogEnabled === value) {
  24080. return;
  24081. }
  24082. this._fogEnabled = value;
  24083. this.markAsDirty(Material.MiscDirtyFlag);
  24084. },
  24085. enumerable: true,
  24086. configurable: true
  24087. });
  24088. Object.defineProperty(Material.prototype, "wireframe", {
  24089. get: function () {
  24090. return this._fillMode === Material.WireFrameFillMode;
  24091. },
  24092. set: function (value) {
  24093. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24094. },
  24095. enumerable: true,
  24096. configurable: true
  24097. });
  24098. Object.defineProperty(Material.prototype, "pointsCloud", {
  24099. get: function () {
  24100. return this._fillMode === Material.PointFillMode;
  24101. },
  24102. set: function (value) {
  24103. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24104. },
  24105. enumerable: true,
  24106. configurable: true
  24107. });
  24108. Object.defineProperty(Material.prototype, "fillMode", {
  24109. get: function () {
  24110. return this._fillMode;
  24111. },
  24112. set: function (value) {
  24113. if (this._fillMode === value) {
  24114. return;
  24115. }
  24116. this._fillMode = value;
  24117. this.markAsDirty(Material.MiscDirtyFlag);
  24118. },
  24119. enumerable: true,
  24120. configurable: true
  24121. });
  24122. /**
  24123. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24124. * subclasses should override adding information pertainent to themselves
  24125. */
  24126. Material.prototype.toString = function (fullDetails) {
  24127. var ret = "Name: " + this.name;
  24128. if (fullDetails) {
  24129. }
  24130. return ret;
  24131. };
  24132. /**
  24133. * Child classes can use it to update shaders
  24134. */
  24135. Material.prototype.getClassName = function () {
  24136. return "Material";
  24137. };
  24138. Object.defineProperty(Material.prototype, "isFrozen", {
  24139. get: function () {
  24140. return this.checkReadyOnlyOnce;
  24141. },
  24142. enumerable: true,
  24143. configurable: true
  24144. });
  24145. Material.prototype.freeze = function () {
  24146. this.checkReadyOnlyOnce = true;
  24147. };
  24148. Material.prototype.unfreeze = function () {
  24149. this.checkReadyOnlyOnce = false;
  24150. };
  24151. Material.prototype.isReady = function (mesh, useInstances) {
  24152. return true;
  24153. };
  24154. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24155. return false;
  24156. };
  24157. Material.prototype.getEffect = function () {
  24158. return this._effect;
  24159. };
  24160. Material.prototype.getScene = function () {
  24161. return this._scene;
  24162. };
  24163. Material.prototype.needAlphaBlending = function () {
  24164. return (this.alpha < 1.0);
  24165. };
  24166. Material.prototype.needAlphaTesting = function () {
  24167. return false;
  24168. };
  24169. Material.prototype.getAlphaTestTexture = function () {
  24170. return null;
  24171. };
  24172. Material.prototype.markDirty = function () {
  24173. this._wasPreviouslyReady = false;
  24174. };
  24175. Material.prototype._preBind = function (effect) {
  24176. var engine = this._scene.getEngine();
  24177. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24178. engine.enableEffect(effect ? effect : this._effect);
  24179. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24180. };
  24181. Material.prototype.bind = function (world, mesh) {
  24182. };
  24183. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  24184. };
  24185. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24186. };
  24187. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  24188. sceneUbo.bindToEffect(effect, "Scene");
  24189. };
  24190. Material.prototype.bindView = function (effect) {
  24191. if (!this._useUBO) {
  24192. effect.setMatrix("view", this.getScene().getViewMatrix());
  24193. }
  24194. else {
  24195. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24196. }
  24197. };
  24198. Material.prototype.bindViewProjection = function (effect) {
  24199. if (!this._useUBO) {
  24200. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24201. }
  24202. else {
  24203. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24204. }
  24205. };
  24206. Material.prototype._afterBind = function (mesh) {
  24207. this._scene._cachedMaterial = this;
  24208. this.onBindObservable.notifyObservers(mesh);
  24209. if (this.disableDepthWrite) {
  24210. var engine = this._scene.getEngine();
  24211. this._cachedDepthWriteState = engine.getDepthWrite();
  24212. engine.setDepthWrite(false);
  24213. }
  24214. };
  24215. Material.prototype.unbind = function () {
  24216. this.onUnBindObservable.notifyObservers(this);
  24217. if (this.disableDepthWrite) {
  24218. var engine = this._scene.getEngine();
  24219. engine.setDepthWrite(this._cachedDepthWriteState);
  24220. }
  24221. };
  24222. Material.prototype.getActiveTextures = function () {
  24223. return [];
  24224. };
  24225. Material.prototype.clone = function (name) {
  24226. return null;
  24227. };
  24228. Material.prototype.getBindedMeshes = function () {
  24229. var result = new Array();
  24230. for (var index = 0; index < this._scene.meshes.length; index++) {
  24231. var mesh = this._scene.meshes[index];
  24232. if (mesh.material === this) {
  24233. result.push(mesh);
  24234. }
  24235. }
  24236. return result;
  24237. };
  24238. // Force shader compilation including textures ready check
  24239. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  24240. var _this = this;
  24241. var subMesh = new BABYLON.BaseSubMesh();
  24242. var scene = this.getScene();
  24243. var engine = scene.getEngine();
  24244. var beforeRenderCallback = function () {
  24245. if (subMesh._materialDefines) {
  24246. subMesh._materialDefines._renderId = -1;
  24247. }
  24248. var alphaTestState = engine.getAlphaTesting();
  24249. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  24250. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  24251. scene.unregisterBeforeRender(beforeRenderCallback);
  24252. if (onCompiled) {
  24253. onCompiled(_this);
  24254. }
  24255. }
  24256. engine.setAlphaTesting(alphaTestState);
  24257. };
  24258. scene.registerBeforeRender(beforeRenderCallback);
  24259. };
  24260. Material.prototype.markAsDirty = function (flag) {
  24261. if (flag & Material.TextureDirtyFlag) {
  24262. this._markAllSubMeshesAsTexturesDirty();
  24263. }
  24264. if (flag & Material.LightDirtyFlag) {
  24265. this._markAllSubMeshesAsLightsDirty();
  24266. }
  24267. if (flag & Material.FresnelDirtyFlag) {
  24268. this._markAllSubMeshesAsFresnelDirty();
  24269. }
  24270. if (flag & Material.AttributesDirtyFlag) {
  24271. this._markAllSubMeshesAsAttributesDirty();
  24272. }
  24273. if (flag & Material.MiscDirtyFlag) {
  24274. this._markAllSubMeshesAsMiscDirty();
  24275. }
  24276. this.getScene().resetCachedMaterial();
  24277. };
  24278. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  24279. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24280. var mesh = _a[_i];
  24281. if (!mesh.subMeshes) {
  24282. continue;
  24283. }
  24284. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24285. var subMesh = _c[_b];
  24286. if (subMesh.getMaterial() !== this) {
  24287. continue;
  24288. }
  24289. if (!subMesh._materialDefines) {
  24290. return;
  24291. }
  24292. func(subMesh._materialDefines);
  24293. }
  24294. }
  24295. };
  24296. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  24297. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  24298. };
  24299. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24300. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24301. };
  24302. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24303. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24304. };
  24305. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  24306. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24307. };
  24308. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24309. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24310. };
  24311. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  24312. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24313. };
  24314. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24315. // Animations
  24316. this.getScene().stopAnimation(this);
  24317. // Remove from scene
  24318. var index = this._scene.materials.indexOf(this);
  24319. if (index >= 0) {
  24320. this._scene.materials.splice(index, 1);
  24321. }
  24322. // Remove from meshes
  24323. for (index = 0; index < this._scene.meshes.length; index++) {
  24324. var mesh = this._scene.meshes[index];
  24325. if (mesh.material === this) {
  24326. mesh.material = null;
  24327. if (mesh.geometry) {
  24328. var geometry = mesh.geometry;
  24329. if (this.storeEffectOnSubMeshes) {
  24330. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24331. var subMesh = _a[_i];
  24332. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24333. }
  24334. }
  24335. else {
  24336. geometry._releaseVertexArrayObject(this._effect);
  24337. }
  24338. }
  24339. }
  24340. }
  24341. this._uniformBuffer.dispose();
  24342. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24343. if (forceDisposeEffect && this._effect) {
  24344. if (this.storeEffectOnSubMeshes) {
  24345. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24346. var subMesh = _c[_b];
  24347. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24348. }
  24349. }
  24350. else {
  24351. this._scene.getEngine()._releaseEffect(this._effect);
  24352. }
  24353. this._effect = null;
  24354. }
  24355. // Callback
  24356. this.onDisposeObservable.notifyObservers(this);
  24357. this.onDisposeObservable.clear();
  24358. this.onBindObservable.clear();
  24359. this.onUnBindObservable.clear();
  24360. };
  24361. Material.prototype.serialize = function () {
  24362. return BABYLON.SerializationHelper.Serialize(this);
  24363. };
  24364. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24365. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24366. multiMaterial.id = parsedMultiMaterial.id;
  24367. if (BABYLON.Tags) {
  24368. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24369. }
  24370. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24371. var subMatId = parsedMultiMaterial.materials[matIndex];
  24372. if (subMatId) {
  24373. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24374. }
  24375. else {
  24376. multiMaterial.subMaterials.push(null);
  24377. }
  24378. }
  24379. return multiMaterial;
  24380. };
  24381. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24382. if (!parsedMaterial.customType) {
  24383. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24384. }
  24385. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  24386. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24387. if (!BABYLON.LegacyPBRMaterial) {
  24388. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24389. return;
  24390. }
  24391. }
  24392. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24393. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24394. ;
  24395. };
  24396. return Material;
  24397. }());
  24398. Material._TriangleFillMode = 0;
  24399. Material._WireFrameFillMode = 1;
  24400. Material._PointFillMode = 2;
  24401. Material._ClockWiseSideOrientation = 0;
  24402. Material._CounterClockWiseSideOrientation = 1;
  24403. Material._TextureDirtyFlag = 1;
  24404. Material._LightDirtyFlag = 2;
  24405. Material._FresnelDirtyFlag = 4;
  24406. Material._AttributesDirtyFlag = 8;
  24407. Material._MiscDirtyFlag = 16;
  24408. __decorate([
  24409. BABYLON.serialize()
  24410. ], Material.prototype, "id", void 0);
  24411. __decorate([
  24412. BABYLON.serialize()
  24413. ], Material.prototype, "name", void 0);
  24414. __decorate([
  24415. BABYLON.serialize()
  24416. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24417. __decorate([
  24418. BABYLON.serialize()
  24419. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24420. __decorate([
  24421. BABYLON.serialize()
  24422. ], Material.prototype, "state", void 0);
  24423. __decorate([
  24424. BABYLON.serialize()
  24425. ], Material.prototype, "alpha", void 0);
  24426. __decorate([
  24427. BABYLON.serialize("backFaceCulling")
  24428. ], Material.prototype, "_backFaceCulling", void 0);
  24429. __decorate([
  24430. BABYLON.serialize()
  24431. ], Material.prototype, "sideOrientation", void 0);
  24432. __decorate([
  24433. BABYLON.serialize()
  24434. ], Material.prototype, "alphaMode", void 0);
  24435. __decorate([
  24436. BABYLON.serialize()
  24437. ], Material.prototype, "disableDepthWrite", void 0);
  24438. __decorate([
  24439. BABYLON.serialize("fogEnabled")
  24440. ], Material.prototype, "_fogEnabled", void 0);
  24441. __decorate([
  24442. BABYLON.serialize()
  24443. ], Material.prototype, "pointSize", void 0);
  24444. __decorate([
  24445. BABYLON.serialize()
  24446. ], Material.prototype, "zOffset", void 0);
  24447. __decorate([
  24448. BABYLON.serialize()
  24449. ], Material.prototype, "wireframe", null);
  24450. __decorate([
  24451. BABYLON.serialize()
  24452. ], Material.prototype, "pointsCloud", null);
  24453. __decorate([
  24454. BABYLON.serialize()
  24455. ], Material.prototype, "fillMode", null);
  24456. BABYLON.Material = Material;
  24457. })(BABYLON || (BABYLON = {}));
  24458. //# sourceMappingURL=babylon.material.js.map
  24459. var BABYLON;
  24460. (function (BABYLON) {
  24461. var UniformBuffer = (function () {
  24462. /**
  24463. * Uniform buffer objects.
  24464. *
  24465. * Handles blocks of uniform on the GPU.
  24466. *
  24467. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24468. *
  24469. * For more information, please refer to :
  24470. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24471. */
  24472. function UniformBuffer(engine, data, dynamic) {
  24473. this._engine = engine;
  24474. this._noUBO = engine.webGLVersion === 1;
  24475. this._dynamic = dynamic;
  24476. this._data = data || [];
  24477. this._uniformLocations = {};
  24478. this._uniformSizes = {};
  24479. this._uniformLocationPointer = 0;
  24480. this._needSync = false;
  24481. if (this._noUBO) {
  24482. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24483. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24484. this.updateFloat = this._updateFloatForEffect;
  24485. this.updateFloat2 = this._updateFloat2ForEffect;
  24486. this.updateFloat3 = this._updateFloat3ForEffect;
  24487. this.updateFloat4 = this._updateFloat4ForEffect;
  24488. this.updateMatrix = this._updateMatrixForEffect;
  24489. this.updateVector3 = this._updateVector3ForEffect;
  24490. this.updateVector4 = this._updateVector4ForEffect;
  24491. this.updateColor3 = this._updateColor3ForEffect;
  24492. this.updateColor4 = this._updateColor4ForEffect;
  24493. }
  24494. else {
  24495. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24496. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24497. this.updateFloat = this._updateFloatForUniform;
  24498. this.updateFloat2 = this._updateFloat2ForUniform;
  24499. this.updateFloat3 = this._updateFloat3ForUniform;
  24500. this.updateFloat4 = this._updateFloat4ForUniform;
  24501. this.updateMatrix = this._updateMatrixForUniform;
  24502. this.updateVector3 = this._updateVector3ForUniform;
  24503. this.updateVector4 = this._updateVector4ForUniform;
  24504. this.updateColor3 = this._updateColor3ForUniform;
  24505. this.updateColor4 = this._updateColor4ForUniform;
  24506. }
  24507. }
  24508. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24509. // Properties
  24510. /**
  24511. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24512. * or just falling back on setUniformXXX calls.
  24513. */
  24514. get: function () {
  24515. return !this._noUBO;
  24516. },
  24517. enumerable: true,
  24518. configurable: true
  24519. });
  24520. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24521. /**
  24522. * Indicates if the WebGL underlying uniform buffer is in sync
  24523. * with the javascript cache data.
  24524. */
  24525. get: function () {
  24526. return !this._needSync;
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. /**
  24532. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24533. * Also, a dynamic UniformBuffer will disable cache verification and always
  24534. * update the underlying WebGL uniform buffer to the GPU.
  24535. */
  24536. UniformBuffer.prototype.isDynamic = function () {
  24537. return this._dynamic;
  24538. };
  24539. /**
  24540. * The data cache on JS side.
  24541. */
  24542. UniformBuffer.prototype.getData = function () {
  24543. return this._bufferData;
  24544. };
  24545. /**
  24546. * The underlying WebGL Uniform buffer.
  24547. */
  24548. UniformBuffer.prototype.getBuffer = function () {
  24549. return this._buffer;
  24550. };
  24551. /**
  24552. * std140 layout specifies how to align data within an UBO structure.
  24553. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24554. * for specs.
  24555. */
  24556. UniformBuffer.prototype._fillAlignment = function (size) {
  24557. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24558. // and 4x4 matrices
  24559. // TODO : change if other types are used
  24560. var alignment;
  24561. if (size <= 2) {
  24562. alignment = size;
  24563. }
  24564. else {
  24565. alignment = 4;
  24566. }
  24567. if ((this._uniformLocationPointer % alignment) !== 0) {
  24568. var oldPointer = this._uniformLocationPointer;
  24569. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24570. var diff = this._uniformLocationPointer - oldPointer;
  24571. for (var i = 0; i < diff; i++) {
  24572. this._data.push(0);
  24573. }
  24574. }
  24575. };
  24576. /**
  24577. * Adds an uniform in the buffer.
  24578. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24579. * for the layout to be correct !
  24580. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24581. * @param {number|number[]} size Data size, or data directly.
  24582. */
  24583. UniformBuffer.prototype.addUniform = function (name, size) {
  24584. if (this._noUBO) {
  24585. return;
  24586. }
  24587. if (this._uniformLocations[name] !== undefined) {
  24588. // Already existing uniform
  24589. return;
  24590. }
  24591. // This function must be called in the order of the shader layout !
  24592. // size can be the size of the uniform, or data directly
  24593. var data;
  24594. if (size instanceof Array) {
  24595. data = size;
  24596. size = data.length;
  24597. }
  24598. else {
  24599. size = size;
  24600. data = [];
  24601. // Fill with zeros
  24602. for (var i = 0; i < size; i++) {
  24603. data.push(0);
  24604. }
  24605. }
  24606. this._fillAlignment(size);
  24607. this._uniformSizes[name] = size;
  24608. this._uniformLocations[name] = this._uniformLocationPointer;
  24609. this._uniformLocationPointer += size;
  24610. for (var i = 0; i < size; i++) {
  24611. this._data.push(data[i]);
  24612. }
  24613. this._needSync = true;
  24614. };
  24615. /**
  24616. * Wrapper for addUniform.
  24617. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24618. * @param {Matrix} mat A 4x4 matrix.
  24619. */
  24620. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24621. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24622. };
  24623. /**
  24624. * Wrapper for addUniform.
  24625. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24626. * @param {number} x
  24627. * @param {number} y
  24628. */
  24629. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24630. var temp = [x, y];
  24631. this.addUniform(name, temp);
  24632. };
  24633. /**
  24634. * Wrapper for addUniform.
  24635. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24636. * @param {number} x
  24637. * @param {number} y
  24638. * @param {number} z
  24639. */
  24640. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24641. var temp = [x, y, z];
  24642. this.addUniform(name, temp);
  24643. };
  24644. /**
  24645. * Wrapper for addUniform.
  24646. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24647. * @param {Color3} color
  24648. */
  24649. UniformBuffer.prototype.addColor3 = function (name, color) {
  24650. var temp = [];
  24651. color.toArray(temp);
  24652. this.addUniform(name, temp);
  24653. };
  24654. /**
  24655. * Wrapper for addUniform.
  24656. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24657. * @param {Color3} color
  24658. * @param {number} alpha
  24659. */
  24660. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24661. var temp = [];
  24662. color.toArray(temp);
  24663. temp.push(alpha);
  24664. this.addUniform(name, temp);
  24665. };
  24666. /**
  24667. * Wrapper for addUniform.
  24668. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24669. * @param {Vector3} vector
  24670. */
  24671. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24672. var temp = [];
  24673. vector.toArray(temp);
  24674. this.addUniform(name, temp);
  24675. };
  24676. /**
  24677. * Wrapper for addUniform.
  24678. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24679. */
  24680. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24681. this.addUniform(name, 12);
  24682. };
  24683. /**
  24684. * Wrapper for addUniform.
  24685. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24686. */
  24687. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24688. this.addUniform(name, 8);
  24689. };
  24690. /**
  24691. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24692. */
  24693. UniformBuffer.prototype.create = function () {
  24694. if (this._noUBO) {
  24695. return;
  24696. }
  24697. if (this._buffer) {
  24698. return; // nothing to do
  24699. }
  24700. // See spec, alignment must be filled as a vec4
  24701. this._fillAlignment(4);
  24702. this._bufferData = new Float32Array(this._data);
  24703. if (this._dynamic) {
  24704. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24705. }
  24706. else {
  24707. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24708. }
  24709. this._needSync = true;
  24710. };
  24711. /**
  24712. * Updates the WebGL Uniform Buffer on the GPU.
  24713. * If the `dynamic` flag is set to true, no cache comparison is done.
  24714. * Otherwise, the buffer will be updated only if the cache differs.
  24715. */
  24716. UniformBuffer.prototype.update = function () {
  24717. if (!this._buffer) {
  24718. this.create();
  24719. return;
  24720. }
  24721. if (!this._dynamic && !this._needSync) {
  24722. return;
  24723. }
  24724. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24725. this._needSync = false;
  24726. };
  24727. /**
  24728. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24729. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24730. * @param {number[]|Float32Array} data Flattened data
  24731. * @param {number} size Size of the data.
  24732. */
  24733. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24734. var location = this._uniformLocations[uniformName];
  24735. if (location === undefined) {
  24736. if (this._buffer) {
  24737. // Cannot add an uniform if the buffer is already created
  24738. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24739. return;
  24740. }
  24741. this.addUniform(uniformName, size);
  24742. location = this._uniformLocations[uniformName];
  24743. }
  24744. if (!this._buffer) {
  24745. this.create();
  24746. }
  24747. if (!this._dynamic) {
  24748. // Cache for static uniform buffers
  24749. var changed = false;
  24750. for (var i = 0; i < size; i++) {
  24751. if (this._bufferData[location + i] !== data[i]) {
  24752. changed = true;
  24753. this._bufferData[location + i] = data[i];
  24754. }
  24755. }
  24756. this._needSync = this._needSync || changed;
  24757. }
  24758. else {
  24759. // No cache for dynamic
  24760. for (var i = 0; i < size; i++) {
  24761. this._bufferData[location + i] = data[i];
  24762. }
  24763. }
  24764. };
  24765. // Update methods
  24766. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24767. // To match std140, matrix must be realigned
  24768. for (var i = 0; i < 3; i++) {
  24769. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24770. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24771. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24772. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24773. }
  24774. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24775. };
  24776. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24777. this._currentEffect.setMatrix3x3(name, matrix);
  24778. };
  24779. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24780. this._currentEffect.setMatrix2x2(name, matrix);
  24781. };
  24782. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24783. // To match std140, matrix must be realigned
  24784. for (var i = 0; i < 2; i++) {
  24785. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24786. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24787. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24788. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24789. }
  24790. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24791. };
  24792. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24793. this._currentEffect.setFloat(name, x);
  24794. };
  24795. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24796. UniformBuffer._tempBuffer[0] = x;
  24797. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24798. };
  24799. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  24800. if (suffix === void 0) { suffix = ""; }
  24801. this._currentEffect.setFloat2(name + suffix, x, y);
  24802. };
  24803. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  24804. if (suffix === void 0) { suffix = ""; }
  24805. UniformBuffer._tempBuffer[0] = x;
  24806. UniformBuffer._tempBuffer[1] = y;
  24807. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24808. };
  24809. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24810. if (suffix === void 0) { suffix = ""; }
  24811. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24812. };
  24813. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24814. if (suffix === void 0) { suffix = ""; }
  24815. UniformBuffer._tempBuffer[0] = x;
  24816. UniformBuffer._tempBuffer[1] = y;
  24817. UniformBuffer._tempBuffer[2] = z;
  24818. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24819. };
  24820. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24821. if (suffix === void 0) { suffix = ""; }
  24822. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24823. };
  24824. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24825. if (suffix === void 0) { suffix = ""; }
  24826. UniformBuffer._tempBuffer[0] = x;
  24827. UniformBuffer._tempBuffer[1] = y;
  24828. UniformBuffer._tempBuffer[2] = z;
  24829. UniformBuffer._tempBuffer[3] = w;
  24830. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24831. };
  24832. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24833. this._currentEffect.setMatrix(name, mat);
  24834. };
  24835. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24836. this.updateUniform(name, mat.toArray(), 16);
  24837. };
  24838. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24839. this._currentEffect.setVector3(name, vector);
  24840. };
  24841. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24842. vector.toArray(UniformBuffer._tempBuffer);
  24843. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24844. };
  24845. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24846. this._currentEffect.setVector4(name, vector);
  24847. };
  24848. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24849. vector.toArray(UniformBuffer._tempBuffer);
  24850. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24851. };
  24852. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24853. if (suffix === void 0) { suffix = ""; }
  24854. this._currentEffect.setColor3(name + suffix, color);
  24855. };
  24856. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24857. if (suffix === void 0) { suffix = ""; }
  24858. color.toArray(UniformBuffer._tempBuffer);
  24859. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24860. };
  24861. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24862. if (suffix === void 0) { suffix = ""; }
  24863. this._currentEffect.setColor4(name + suffix, color, alpha);
  24864. };
  24865. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24866. if (suffix === void 0) { suffix = ""; }
  24867. color.toArray(UniformBuffer._tempBuffer);
  24868. UniformBuffer._tempBuffer[3] = alpha;
  24869. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24870. };
  24871. /**
  24872. * Sets a sampler uniform on the effect.
  24873. * @param {string} name Name of the sampler.
  24874. * @param {Texture} texture
  24875. */
  24876. UniformBuffer.prototype.setTexture = function (name, texture) {
  24877. this._currentEffect.setTexture(name, texture);
  24878. };
  24879. /**
  24880. * Directly updates the value of the uniform in the cache AND on the GPU.
  24881. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24882. * @param {number[]|Float32Array} data Flattened data
  24883. */
  24884. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24885. this.updateUniform(uniformName, data, data.length);
  24886. this.update();
  24887. };
  24888. /**
  24889. * Binds this uniform buffer to an effect.
  24890. * @param {Effect} effect
  24891. * @param {string} name Name of the uniform block in the shader.
  24892. */
  24893. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24894. this._currentEffect = effect;
  24895. if (this._noUBO) {
  24896. return;
  24897. }
  24898. effect.bindUniformBuffer(this._buffer, name);
  24899. };
  24900. /**
  24901. * Disposes the uniform buffer.
  24902. */
  24903. UniformBuffer.prototype.dispose = function () {
  24904. if (!this._buffer) {
  24905. return;
  24906. }
  24907. if (this._engine._releaseBuffer(this._buffer)) {
  24908. this._buffer = null;
  24909. }
  24910. };
  24911. return UniformBuffer;
  24912. }());
  24913. // Pool for avoiding memory leaks
  24914. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24915. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24916. BABYLON.UniformBuffer = UniformBuffer;
  24917. })(BABYLON || (BABYLON = {}));
  24918. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24919. var BABYLON;
  24920. (function (BABYLON) {
  24921. var PushMaterial = (function (_super) {
  24922. __extends(PushMaterial, _super);
  24923. function PushMaterial(name, scene) {
  24924. var _this = _super.call(this, name, scene) || this;
  24925. _this.storeEffectOnSubMeshes = true;
  24926. return _this;
  24927. }
  24928. PushMaterial.prototype.getEffect = function () {
  24929. return this._activeEffect;
  24930. };
  24931. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24932. if (!mesh) {
  24933. return false;
  24934. }
  24935. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24936. return true;
  24937. }
  24938. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24939. };
  24940. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24941. this._activeEffect.setMatrix("world", world);
  24942. };
  24943. PushMaterial.prototype.bind = function (world, mesh) {
  24944. if (!mesh) {
  24945. return;
  24946. }
  24947. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24948. };
  24949. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24950. _super.prototype._afterBind.call(this, mesh);
  24951. this.getScene()._cachedEffect = effect;
  24952. };
  24953. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24954. if (visibility === void 0) { visibility = 0; }
  24955. return scene.isCachedMaterialValid(this, effect, visibility);
  24956. };
  24957. return PushMaterial;
  24958. }(BABYLON.Material));
  24959. BABYLON.PushMaterial = PushMaterial;
  24960. })(BABYLON || (BABYLON = {}));
  24961. //# sourceMappingURL=babylon.pushMaterial.js.map
  24962. var BABYLON;
  24963. (function (BABYLON) {
  24964. var VertexData = (function () {
  24965. function VertexData() {
  24966. }
  24967. VertexData.prototype.set = function (data, kind) {
  24968. switch (kind) {
  24969. case BABYLON.VertexBuffer.PositionKind:
  24970. this.positions = data;
  24971. break;
  24972. case BABYLON.VertexBuffer.NormalKind:
  24973. this.normals = data;
  24974. break;
  24975. case BABYLON.VertexBuffer.TangentKind:
  24976. this.tangents = data;
  24977. break;
  24978. case BABYLON.VertexBuffer.UVKind:
  24979. this.uvs = data;
  24980. break;
  24981. case BABYLON.VertexBuffer.UV2Kind:
  24982. this.uvs2 = data;
  24983. break;
  24984. case BABYLON.VertexBuffer.UV3Kind:
  24985. this.uvs3 = data;
  24986. break;
  24987. case BABYLON.VertexBuffer.UV4Kind:
  24988. this.uvs4 = data;
  24989. break;
  24990. case BABYLON.VertexBuffer.UV5Kind:
  24991. this.uvs5 = data;
  24992. break;
  24993. case BABYLON.VertexBuffer.UV6Kind:
  24994. this.uvs6 = data;
  24995. break;
  24996. case BABYLON.VertexBuffer.ColorKind:
  24997. this.colors = data;
  24998. break;
  24999. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25000. this.matricesIndices = data;
  25001. break;
  25002. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25003. this.matricesWeights = data;
  25004. break;
  25005. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  25006. this.matricesIndicesExtra = data;
  25007. break;
  25008. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  25009. this.matricesWeightsExtra = data;
  25010. break;
  25011. }
  25012. };
  25013. /**
  25014. * Associates the vertexData to the passed Mesh.
  25015. * Sets it as updatable or not (default `false`).
  25016. * Returns the VertexData.
  25017. */
  25018. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25019. this._applyTo(mesh, updatable);
  25020. return this;
  25021. };
  25022. /**
  25023. * Associates the vertexData to the passed Geometry.
  25024. * Sets it as updatable or not (default `false`).
  25025. * Returns the VertexData.
  25026. */
  25027. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25028. this._applyTo(geometry, updatable);
  25029. return this;
  25030. };
  25031. /**
  25032. * Updates the associated mesh.
  25033. * Returns the VertexData.
  25034. */
  25035. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25036. this._update(mesh);
  25037. return this;
  25038. };
  25039. /**
  25040. * Updates the associated geometry.
  25041. * Returns the VertexData.
  25042. */
  25043. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25044. this._update(geometry);
  25045. return this;
  25046. };
  25047. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25048. if (this.positions) {
  25049. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25050. }
  25051. if (this.normals) {
  25052. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25053. }
  25054. if (this.tangents) {
  25055. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25056. }
  25057. if (this.uvs) {
  25058. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25059. }
  25060. if (this.uvs2) {
  25061. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25062. }
  25063. if (this.uvs3) {
  25064. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25065. }
  25066. if (this.uvs4) {
  25067. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25068. }
  25069. if (this.uvs5) {
  25070. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25071. }
  25072. if (this.uvs6) {
  25073. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25074. }
  25075. if (this.colors) {
  25076. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25077. }
  25078. if (this.matricesIndices) {
  25079. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25080. }
  25081. if (this.matricesWeights) {
  25082. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25083. }
  25084. if (this.matricesIndicesExtra) {
  25085. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25086. }
  25087. if (this.matricesWeightsExtra) {
  25088. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25089. }
  25090. if (this.indices) {
  25091. meshOrGeometry.setIndices(this.indices);
  25092. }
  25093. return this;
  25094. };
  25095. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25096. if (this.positions) {
  25097. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25098. }
  25099. if (this.normals) {
  25100. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25101. }
  25102. if (this.tangents) {
  25103. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25104. }
  25105. if (this.uvs) {
  25106. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25107. }
  25108. if (this.uvs2) {
  25109. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25110. }
  25111. if (this.uvs3) {
  25112. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25113. }
  25114. if (this.uvs4) {
  25115. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25116. }
  25117. if (this.uvs5) {
  25118. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25119. }
  25120. if (this.uvs6) {
  25121. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25122. }
  25123. if (this.colors) {
  25124. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25125. }
  25126. if (this.matricesIndices) {
  25127. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25128. }
  25129. if (this.matricesWeights) {
  25130. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25131. }
  25132. if (this.matricesIndicesExtra) {
  25133. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25134. }
  25135. if (this.matricesWeightsExtra) {
  25136. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25137. }
  25138. if (this.indices) {
  25139. meshOrGeometry.setIndices(this.indices);
  25140. }
  25141. return this;
  25142. };
  25143. /**
  25144. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  25145. * Returns the VertexData.
  25146. */
  25147. VertexData.prototype.transform = function (matrix) {
  25148. var transformed = BABYLON.Vector3.Zero();
  25149. var index;
  25150. if (this.positions) {
  25151. var position = BABYLON.Vector3.Zero();
  25152. for (index = 0; index < this.positions.length; index += 3) {
  25153. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25154. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25155. this.positions[index] = transformed.x;
  25156. this.positions[index + 1] = transformed.y;
  25157. this.positions[index + 2] = transformed.z;
  25158. }
  25159. }
  25160. if (this.normals) {
  25161. var normal = BABYLON.Vector3.Zero();
  25162. for (index = 0; index < this.normals.length; index += 3) {
  25163. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25164. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25165. this.normals[index] = transformed.x;
  25166. this.normals[index + 1] = transformed.y;
  25167. this.normals[index + 2] = transformed.z;
  25168. }
  25169. }
  25170. if (this.tangents) {
  25171. var tangent = BABYLON.Vector4.Zero();
  25172. var tangentTransformed = BABYLON.Vector4.Zero();
  25173. for (index = 0; index < this.tangents.length; index += 4) {
  25174. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  25175. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  25176. this.tangents[index] = tangentTransformed.x;
  25177. this.tangents[index + 1] = tangentTransformed.y;
  25178. this.tangents[index + 2] = tangentTransformed.z;
  25179. this.tangents[index + 3] = tangentTransformed.w;
  25180. }
  25181. }
  25182. return this;
  25183. };
  25184. /**
  25185. * Merges the passed VertexData into the current one.
  25186. * Returns the modified VertexData.
  25187. */
  25188. VertexData.prototype.merge = function (other) {
  25189. if (other.indices) {
  25190. if (!this.indices) {
  25191. this.indices = [];
  25192. }
  25193. var offset = this.positions ? this.positions.length / 3 : 0;
  25194. for (var index = 0; index < other.indices.length; index++) {
  25195. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  25196. this.indices.push(other.indices[index] + offset);
  25197. }
  25198. }
  25199. this.positions = this._mergeElement(this.positions, other.positions);
  25200. this.normals = this._mergeElement(this.normals, other.normals);
  25201. this.tangents = this._mergeElement(this.tangents, other.tangents);
  25202. this.uvs = this._mergeElement(this.uvs, other.uvs);
  25203. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  25204. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  25205. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  25206. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  25207. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  25208. this.colors = this._mergeElement(this.colors, other.colors);
  25209. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  25210. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  25211. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  25212. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  25213. return this;
  25214. };
  25215. VertexData.prototype._mergeElement = function (source, other) {
  25216. if (!other)
  25217. return source;
  25218. if (!source)
  25219. return other;
  25220. var len = other.length + source.length;
  25221. var isSrcTypedArray = source instanceof Float32Array;
  25222. var isOthTypedArray = other instanceof Float32Array;
  25223. // use non-loop method when the source is Float32Array
  25224. if (isSrcTypedArray) {
  25225. var ret32 = new Float32Array(len);
  25226. ret32.set(source);
  25227. ret32.set(other, source.length);
  25228. return ret32;
  25229. // source is number[], when other is also use concat
  25230. }
  25231. else if (!isOthTypedArray) {
  25232. return source.concat(other);
  25233. // source is a number[], but other is a Float32Array, loop required
  25234. }
  25235. else {
  25236. var ret = source.slice(0); // copy source to a separate array
  25237. for (var i = 0, len = other.length; i < len; i++) {
  25238. ret.push(other[i]);
  25239. }
  25240. return ret;
  25241. }
  25242. };
  25243. /**
  25244. * Serializes the VertexData.
  25245. * Returns a serialized object.
  25246. */
  25247. VertexData.prototype.serialize = function () {
  25248. var serializationObject = this.serialize();
  25249. if (this.positions) {
  25250. serializationObject.positions = this.positions;
  25251. }
  25252. if (this.normals) {
  25253. serializationObject.normals = this.normals;
  25254. }
  25255. if (this.tangents) {
  25256. serializationObject.tangents = this.tangents;
  25257. }
  25258. if (this.uvs) {
  25259. serializationObject.uvs = this.uvs;
  25260. }
  25261. if (this.uvs2) {
  25262. serializationObject.uvs2 = this.uvs2;
  25263. }
  25264. if (this.uvs3) {
  25265. serializationObject.uvs3 = this.uvs3;
  25266. }
  25267. if (this.uvs4) {
  25268. serializationObject.uvs4 = this.uvs4;
  25269. }
  25270. if (this.uvs5) {
  25271. serializationObject.uvs5 = this.uvs5;
  25272. }
  25273. if (this.uvs6) {
  25274. serializationObject.uvs6 = this.uvs6;
  25275. }
  25276. if (this.colors) {
  25277. serializationObject.colors = this.colors;
  25278. }
  25279. if (this.matricesIndices) {
  25280. serializationObject.matricesIndices = this.matricesIndices;
  25281. serializationObject.matricesIndices._isExpanded = true;
  25282. }
  25283. if (this.matricesWeights) {
  25284. serializationObject.matricesWeights = this.matricesWeights;
  25285. }
  25286. if (this.matricesIndicesExtra) {
  25287. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25288. serializationObject.matricesIndicesExtra._isExpanded = true;
  25289. }
  25290. if (this.matricesWeightsExtra) {
  25291. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25292. }
  25293. serializationObject.indices = this.indices;
  25294. return serializationObject;
  25295. };
  25296. // Statics
  25297. /**
  25298. * Returns the object VertexData associated to the passed mesh.
  25299. */
  25300. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25301. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25302. };
  25303. /**
  25304. * Returns the object VertexData associated to the passed geometry.
  25305. */
  25306. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25307. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25308. };
  25309. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25310. var result = new VertexData();
  25311. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25312. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25313. }
  25314. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25315. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25316. }
  25317. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25318. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25319. }
  25320. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25321. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25322. }
  25323. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25324. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25325. }
  25326. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25327. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25328. }
  25329. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25330. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25331. }
  25332. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25333. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25334. }
  25335. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25336. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25337. }
  25338. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25339. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25340. }
  25341. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25342. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25343. }
  25344. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25345. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25346. }
  25347. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25348. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25349. }
  25350. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25351. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25352. }
  25353. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25354. return result;
  25355. };
  25356. /**
  25357. * Creates the vertexData of the Ribbon.
  25358. */
  25359. VertexData.CreateRibbon = function (options) {
  25360. var pathArray = options.pathArray;
  25361. var closeArray = options.closeArray || false;
  25362. var closePath = options.closePath || false;
  25363. var invertUV = options.invertUV || false;
  25364. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25365. var offset = options.offset || defaultOffset;
  25366. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25367. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25368. var customUV = options.uvs;
  25369. var customColors = options.colors;
  25370. var positions = [];
  25371. var indices = [];
  25372. var normals = [];
  25373. var uvs = [];
  25374. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25375. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25376. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25377. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25378. var minlg; // minimal length among all paths from pathArray
  25379. var lg = []; // array of path lengths : nb of vertex per path
  25380. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25381. var p; // path iterator
  25382. var i; // point iterator
  25383. var j; // point iterator
  25384. // if single path in pathArray
  25385. if (pathArray.length < 2) {
  25386. var ar1 = [];
  25387. var ar2 = [];
  25388. for (i = 0; i < pathArray[0].length - offset; i++) {
  25389. ar1.push(pathArray[0][i]);
  25390. ar2.push(pathArray[0][i + offset]);
  25391. }
  25392. pathArray = [ar1, ar2];
  25393. }
  25394. // positions and horizontal distances (u)
  25395. var idc = 0;
  25396. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25397. var path;
  25398. var l;
  25399. minlg = pathArray[0].length;
  25400. var vectlg;
  25401. var dist;
  25402. for (p = 0; p < pathArray.length; p++) {
  25403. uTotalDistance[p] = 0;
  25404. us[p] = [0];
  25405. path = pathArray[p];
  25406. l = path.length;
  25407. minlg = (minlg < l) ? minlg : l;
  25408. j = 0;
  25409. while (j < l) {
  25410. positions.push(path[j].x, path[j].y, path[j].z);
  25411. if (j > 0) {
  25412. vectlg = path[j].subtract(path[j - 1]).length();
  25413. dist = vectlg + uTotalDistance[p];
  25414. us[p].push(dist);
  25415. uTotalDistance[p] = dist;
  25416. }
  25417. j++;
  25418. }
  25419. if (closePath) {
  25420. j--;
  25421. positions.push(path[0].x, path[0].y, path[0].z);
  25422. vectlg = path[j].subtract(path[0]).length();
  25423. dist = vectlg + uTotalDistance[p];
  25424. us[p].push(dist);
  25425. uTotalDistance[p] = dist;
  25426. }
  25427. lg[p] = l + closePathCorr;
  25428. idx[p] = idc;
  25429. idc += (l + closePathCorr);
  25430. }
  25431. // vertical distances (v)
  25432. var path1;
  25433. var path2;
  25434. var vertex1;
  25435. var vertex2;
  25436. for (i = 0; i < minlg + closePathCorr; i++) {
  25437. vTotalDistance[i] = 0;
  25438. vs[i] = [0];
  25439. for (p = 0; p < pathArray.length - 1; p++) {
  25440. path1 = pathArray[p];
  25441. path2 = pathArray[p + 1];
  25442. if (i === minlg) {
  25443. vertex1 = path1[0];
  25444. vertex2 = path2[0];
  25445. }
  25446. else {
  25447. vertex1 = path1[i];
  25448. vertex2 = path2[i];
  25449. }
  25450. vectlg = vertex2.subtract(vertex1).length();
  25451. dist = vectlg + vTotalDistance[i];
  25452. vs[i].push(dist);
  25453. vTotalDistance[i] = dist;
  25454. }
  25455. if (closeArray) {
  25456. path1 = pathArray[p];
  25457. path2 = pathArray[0];
  25458. if (i === minlg) {
  25459. vertex2 = path2[0];
  25460. }
  25461. vectlg = vertex2.subtract(vertex1).length();
  25462. dist = vectlg + vTotalDistance[i];
  25463. vTotalDistance[i] = dist;
  25464. }
  25465. }
  25466. // uvs
  25467. var u;
  25468. var v;
  25469. if (customUV) {
  25470. for (p = 0; p < customUV.length; p++) {
  25471. uvs.push(customUV[p].x, customUV[p].y);
  25472. }
  25473. }
  25474. else {
  25475. for (p = 0; p < pathArray.length; p++) {
  25476. for (i = 0; i < minlg + closePathCorr; i++) {
  25477. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25478. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25479. if (invertUV) {
  25480. uvs.push(v, u);
  25481. }
  25482. else {
  25483. uvs.push(u, v);
  25484. }
  25485. }
  25486. }
  25487. }
  25488. // indices
  25489. p = 0; // path index
  25490. var pi = 0; // positions array index
  25491. var l1 = lg[p] - 1; // path1 length
  25492. var l2 = lg[p + 1] - 1; // path2 length
  25493. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25494. var shft = idx[1] - idx[0]; // shift
  25495. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25496. while (pi <= min && p < path1nb) {
  25497. // 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
  25498. indices.push(pi, pi + shft, pi + 1);
  25499. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25500. pi += 1;
  25501. if (pi === min) {
  25502. p++;
  25503. if (p === lg.length - 1) {
  25504. shft = idx[0] - idx[p];
  25505. l1 = lg[p] - 1;
  25506. l2 = lg[0] - 1;
  25507. }
  25508. else {
  25509. shft = idx[p + 1] - idx[p];
  25510. l1 = lg[p] - 1;
  25511. l2 = lg[p + 1] - 1;
  25512. }
  25513. pi = idx[p];
  25514. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25515. }
  25516. }
  25517. // normals
  25518. VertexData.ComputeNormals(positions, indices, normals);
  25519. if (closePath) {
  25520. var indexFirst = 0;
  25521. var indexLast = 0;
  25522. for (p = 0; p < pathArray.length; p++) {
  25523. indexFirst = idx[p] * 3;
  25524. if (p + 1 < pathArray.length) {
  25525. indexLast = (idx[p + 1] - 1) * 3;
  25526. }
  25527. else {
  25528. indexLast = normals.length - 3;
  25529. }
  25530. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25531. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25532. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25533. normals[indexLast] = normals[indexFirst];
  25534. normals[indexLast + 1] = normals[indexFirst + 1];
  25535. normals[indexLast + 2] = normals[indexFirst + 2];
  25536. }
  25537. }
  25538. // sides
  25539. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25540. // Colors
  25541. if (customColors) {
  25542. var colors = new Float32Array(customColors.length * 4);
  25543. for (var c = 0; c < customColors.length; c++) {
  25544. colors[c * 4] = customColors[c].r;
  25545. colors[c * 4 + 1] = customColors[c].g;
  25546. colors[c * 4 + 2] = customColors[c].b;
  25547. colors[c * 4 + 3] = customColors[c].a;
  25548. }
  25549. }
  25550. // Result
  25551. var vertexData = new VertexData();
  25552. var positions32 = new Float32Array(positions);
  25553. var normals32 = new Float32Array(normals);
  25554. var uvs32 = new Float32Array(uvs);
  25555. vertexData.indices = indices;
  25556. vertexData.positions = positions32;
  25557. vertexData.normals = normals32;
  25558. vertexData.uvs = uvs32;
  25559. if (customColors) {
  25560. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25561. }
  25562. if (closePath) {
  25563. vertexData._idx = idx;
  25564. }
  25565. return vertexData;
  25566. };
  25567. /**
  25568. * Creates the VertexData of the Box.
  25569. */
  25570. VertexData.CreateBox = function (options) {
  25571. var normalsSource = [
  25572. new BABYLON.Vector3(0, 0, 1),
  25573. new BABYLON.Vector3(0, 0, -1),
  25574. new BABYLON.Vector3(1, 0, 0),
  25575. new BABYLON.Vector3(-1, 0, 0),
  25576. new BABYLON.Vector3(0, 1, 0),
  25577. new BABYLON.Vector3(0, -1, 0)
  25578. ];
  25579. var indices = [];
  25580. var positions = [];
  25581. var normals = [];
  25582. var uvs = [];
  25583. var width = options.width || options.size || 1;
  25584. var height = options.height || options.size || 1;
  25585. var depth = options.depth || options.size || 1;
  25586. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25587. var faceUV = options.faceUV || new Array(6);
  25588. var faceColors = options.faceColors;
  25589. var colors = [];
  25590. // default face colors and UV if undefined
  25591. for (var f = 0; f < 6; f++) {
  25592. if (faceUV[f] === undefined) {
  25593. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25594. }
  25595. if (faceColors && faceColors[f] === undefined) {
  25596. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25597. }
  25598. }
  25599. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25600. // Create each face in turn.
  25601. for (var index = 0; index < normalsSource.length; index++) {
  25602. var normal = normalsSource[index];
  25603. // Get two vectors perpendicular to the face normal and to each other.
  25604. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25605. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25606. // Six indices (two triangles) per face.
  25607. var verticesLength = positions.length / 3;
  25608. indices.push(verticesLength);
  25609. indices.push(verticesLength + 1);
  25610. indices.push(verticesLength + 2);
  25611. indices.push(verticesLength);
  25612. indices.push(verticesLength + 2);
  25613. indices.push(verticesLength + 3);
  25614. // Four vertices per face.
  25615. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25616. positions.push(vertex.x, vertex.y, vertex.z);
  25617. normals.push(normal.x, normal.y, normal.z);
  25618. uvs.push(faceUV[index].z, faceUV[index].w);
  25619. if (faceColors) {
  25620. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25621. }
  25622. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25623. positions.push(vertex.x, vertex.y, vertex.z);
  25624. normals.push(normal.x, normal.y, normal.z);
  25625. uvs.push(faceUV[index].x, faceUV[index].w);
  25626. if (faceColors) {
  25627. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25628. }
  25629. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25630. positions.push(vertex.x, vertex.y, vertex.z);
  25631. normals.push(normal.x, normal.y, normal.z);
  25632. uvs.push(faceUV[index].x, faceUV[index].y);
  25633. if (faceColors) {
  25634. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25635. }
  25636. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25637. positions.push(vertex.x, vertex.y, vertex.z);
  25638. normals.push(normal.x, normal.y, normal.z);
  25639. uvs.push(faceUV[index].z, faceUV[index].y);
  25640. if (faceColors) {
  25641. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25642. }
  25643. }
  25644. // sides
  25645. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25646. // Result
  25647. var vertexData = new VertexData();
  25648. vertexData.indices = indices;
  25649. vertexData.positions = positions;
  25650. vertexData.normals = normals;
  25651. vertexData.uvs = uvs;
  25652. if (faceColors) {
  25653. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25654. vertexData.colors = totalColors;
  25655. }
  25656. return vertexData;
  25657. };
  25658. /**
  25659. * Creates the VertexData of the Sphere.
  25660. */
  25661. VertexData.CreateSphere = function (options) {
  25662. var segments = options.segments || 32;
  25663. var diameterX = options.diameterX || options.diameter || 1;
  25664. var diameterY = options.diameterY || options.diameter || 1;
  25665. var diameterZ = options.diameterZ || options.diameter || 1;
  25666. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25667. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25668. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25669. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25670. var totalZRotationSteps = 2 + segments;
  25671. var totalYRotationSteps = 2 * totalZRotationSteps;
  25672. var indices = [];
  25673. var positions = [];
  25674. var normals = [];
  25675. var uvs = [];
  25676. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25677. var normalizedZ = zRotationStep / totalZRotationSteps;
  25678. var angleZ = normalizedZ * Math.PI * slice;
  25679. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25680. var normalizedY = yRotationStep / totalYRotationSteps;
  25681. var angleY = normalizedY * Math.PI * 2 * arc;
  25682. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25683. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25684. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25685. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25686. var vertex = complete.multiply(radius);
  25687. var normal = complete.divide(radius).normalize();
  25688. positions.push(vertex.x, vertex.y, vertex.z);
  25689. normals.push(normal.x, normal.y, normal.z);
  25690. uvs.push(normalizedY, normalizedZ);
  25691. }
  25692. if (zRotationStep > 0) {
  25693. var verticesCount = positions.length / 3;
  25694. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25695. indices.push((firstIndex));
  25696. indices.push((firstIndex + 1));
  25697. indices.push(firstIndex + totalYRotationSteps + 1);
  25698. indices.push((firstIndex + totalYRotationSteps + 1));
  25699. indices.push((firstIndex + 1));
  25700. indices.push((firstIndex + totalYRotationSteps + 2));
  25701. }
  25702. }
  25703. }
  25704. // Sides
  25705. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25706. // Result
  25707. var vertexData = new VertexData();
  25708. vertexData.indices = indices;
  25709. vertexData.positions = positions;
  25710. vertexData.normals = normals;
  25711. vertexData.uvs = uvs;
  25712. return vertexData;
  25713. };
  25714. /**
  25715. * Creates the VertexData of the Cylinder or Cone.
  25716. */
  25717. VertexData.CreateCylinder = function (options) {
  25718. var height = options.height || 2;
  25719. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25720. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25721. var tessellation = options.tessellation || 24;
  25722. var subdivisions = options.subdivisions || 1;
  25723. var hasRings = options.hasRings;
  25724. var enclose = options.enclose;
  25725. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25726. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25727. var faceUV = options.faceUV || new Array(3);
  25728. var faceColors = options.faceColors;
  25729. // default face colors and UV if undefined
  25730. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25731. var ringNb = (hasRings) ? subdivisions : 1;
  25732. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25733. var f;
  25734. for (f = 0; f < surfaceNb; f++) {
  25735. if (faceColors && faceColors[f] === undefined) {
  25736. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25737. }
  25738. }
  25739. for (f = 0; f < surfaceNb; f++) {
  25740. if (faceUV && faceUV[f] === undefined) {
  25741. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25742. }
  25743. }
  25744. var indices = [];
  25745. var positions = [];
  25746. var normals = [];
  25747. var uvs = [];
  25748. var colors = [];
  25749. var angle_step = Math.PI * 2 * arc / tessellation;
  25750. var angle;
  25751. var h;
  25752. var radius;
  25753. var tan = (diameterBottom - diameterTop) / 2 / height;
  25754. var ringVertex = BABYLON.Vector3.Zero();
  25755. var ringNormal = BABYLON.Vector3.Zero();
  25756. var ringFirstVertex = BABYLON.Vector3.Zero();
  25757. var ringFirstNormal = BABYLON.Vector3.Zero();
  25758. var quadNormal = BABYLON.Vector3.Zero();
  25759. var Y = BABYLON.Axis.Y;
  25760. // positions, normals, uvs
  25761. var i;
  25762. var j;
  25763. var r;
  25764. var ringIdx = 1;
  25765. var s = 1; // surface index
  25766. var cs = 0;
  25767. var v = 0;
  25768. for (i = 0; i <= subdivisions; i++) {
  25769. h = i / subdivisions;
  25770. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25771. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25772. for (r = 0; r < ringIdx; r++) {
  25773. if (hasRings) {
  25774. s += r;
  25775. }
  25776. if (enclose) {
  25777. s += 2 * r;
  25778. }
  25779. for (j = 0; j <= tessellation; j++) {
  25780. angle = j * angle_step;
  25781. // position
  25782. ringVertex.x = Math.cos(-angle) * radius;
  25783. ringVertex.y = -height / 2 + h * height;
  25784. ringVertex.z = Math.sin(-angle) * radius;
  25785. // normal
  25786. if (diameterTop === 0 && i === subdivisions) {
  25787. // if no top cap, reuse former normals
  25788. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25789. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25790. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25791. }
  25792. else {
  25793. ringNormal.x = ringVertex.x;
  25794. ringNormal.z = ringVertex.z;
  25795. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25796. ringNormal.normalize();
  25797. }
  25798. // keep first ring vertex values for enclose
  25799. if (j === 0) {
  25800. ringFirstVertex.copyFrom(ringVertex);
  25801. ringFirstNormal.copyFrom(ringNormal);
  25802. }
  25803. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25804. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25805. if (hasRings) {
  25806. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25807. }
  25808. else {
  25809. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25810. }
  25811. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25812. if (faceColors) {
  25813. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25814. }
  25815. }
  25816. // if enclose, add four vertices and their dedicated normals
  25817. if (arc !== 1 && enclose) {
  25818. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25819. positions.push(0, ringVertex.y, 0);
  25820. positions.push(0, ringVertex.y, 0);
  25821. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25822. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25823. quadNormal.normalize();
  25824. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25825. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25826. quadNormal.normalize();
  25827. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25828. if (hasRings) {
  25829. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25830. }
  25831. else {
  25832. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25833. }
  25834. uvs.push(faceUV[s + 1].x, v);
  25835. uvs.push(faceUV[s + 1].z, v);
  25836. if (hasRings) {
  25837. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25838. }
  25839. else {
  25840. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25841. }
  25842. uvs.push(faceUV[s + 2].x, v);
  25843. uvs.push(faceUV[s + 2].z, v);
  25844. if (faceColors) {
  25845. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25846. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25847. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25848. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25849. }
  25850. }
  25851. if (cs !== s) {
  25852. cs = s;
  25853. }
  25854. }
  25855. }
  25856. // indices
  25857. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25858. var s;
  25859. i = 0;
  25860. for (s = 0; s < subdivisions; s++) {
  25861. for (j = 0; j < tessellation; j++) {
  25862. var i0 = i * (e + 1) + j;
  25863. var i1 = (i + 1) * (e + 1) + j;
  25864. var i2 = i * (e + 1) + (j + 1);
  25865. var i3 = (i + 1) * (e + 1) + (j + 1);
  25866. indices.push(i0, i1, i2);
  25867. indices.push(i3, i2, i1);
  25868. }
  25869. if (arc !== 1 && enclose) {
  25870. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25871. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25872. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25873. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25874. }
  25875. i = (hasRings) ? (i + 2) : (i + 1);
  25876. }
  25877. // Caps
  25878. var createCylinderCap = function (isTop) {
  25879. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25880. if (radius === 0) {
  25881. return;
  25882. }
  25883. // Cap positions, normals & uvs
  25884. var angle;
  25885. var circleVector;
  25886. var i;
  25887. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25888. var c;
  25889. if (faceColors) {
  25890. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25891. }
  25892. // cap center
  25893. var vbase = positions.length / 3;
  25894. var offset = isTop ? height / 2 : -height / 2;
  25895. var center = new BABYLON.Vector3(0, offset, 0);
  25896. positions.push(center.x, center.y, center.z);
  25897. normals.push(0, isTop ? 1 : -1, 0);
  25898. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25899. if (faceColors) {
  25900. colors.push(c.r, c.g, c.b, c.a);
  25901. }
  25902. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25903. for (i = 0; i <= tessellation; i++) {
  25904. angle = Math.PI * 2 * i * arc / tessellation;
  25905. var cos = Math.cos(-angle);
  25906. var sin = Math.sin(-angle);
  25907. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25908. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25909. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25910. normals.push(0, isTop ? 1 : -1, 0);
  25911. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25912. if (faceColors) {
  25913. colors.push(c.r, c.g, c.b, c.a);
  25914. }
  25915. }
  25916. // Cap indices
  25917. for (i = 0; i < tessellation; i++) {
  25918. if (!isTop) {
  25919. indices.push(vbase);
  25920. indices.push(vbase + (i + 1));
  25921. indices.push(vbase + (i + 2));
  25922. }
  25923. else {
  25924. indices.push(vbase);
  25925. indices.push(vbase + (i + 2));
  25926. indices.push(vbase + (i + 1));
  25927. }
  25928. }
  25929. };
  25930. // add caps to geometry
  25931. createCylinderCap(false);
  25932. createCylinderCap(true);
  25933. // Sides
  25934. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25935. var vertexData = new VertexData();
  25936. vertexData.indices = indices;
  25937. vertexData.positions = positions;
  25938. vertexData.normals = normals;
  25939. vertexData.uvs = uvs;
  25940. if (faceColors) {
  25941. vertexData.colors = colors;
  25942. }
  25943. return vertexData;
  25944. };
  25945. /**
  25946. * Creates the VertexData of the Torus.
  25947. */
  25948. VertexData.CreateTorus = function (options) {
  25949. var indices = [];
  25950. var positions = [];
  25951. var normals = [];
  25952. var uvs = [];
  25953. var diameter = options.diameter || 1;
  25954. var thickness = options.thickness || 0.5;
  25955. var tessellation = options.tessellation || 16;
  25956. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25957. var stride = tessellation + 1;
  25958. for (var i = 0; i <= tessellation; i++) {
  25959. var u = i / tessellation;
  25960. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25961. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25962. for (var j = 0; j <= tessellation; j++) {
  25963. var v = 1 - j / tessellation;
  25964. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25965. var dx = Math.cos(innerAngle);
  25966. var dy = Math.sin(innerAngle);
  25967. // Create a vertex.
  25968. var normal = new BABYLON.Vector3(dx, dy, 0);
  25969. var position = normal.scale(thickness / 2);
  25970. var textureCoordinate = new BABYLON.Vector2(u, v);
  25971. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25972. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25973. positions.push(position.x, position.y, position.z);
  25974. normals.push(normal.x, normal.y, normal.z);
  25975. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25976. // And create indices for two triangles.
  25977. var nextI = (i + 1) % stride;
  25978. var nextJ = (j + 1) % stride;
  25979. indices.push(i * stride + j);
  25980. indices.push(i * stride + nextJ);
  25981. indices.push(nextI * stride + j);
  25982. indices.push(i * stride + nextJ);
  25983. indices.push(nextI * stride + nextJ);
  25984. indices.push(nextI * stride + j);
  25985. }
  25986. }
  25987. // Sides
  25988. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25989. // Result
  25990. var vertexData = new VertexData();
  25991. vertexData.indices = indices;
  25992. vertexData.positions = positions;
  25993. vertexData.normals = normals;
  25994. vertexData.uvs = uvs;
  25995. return vertexData;
  25996. };
  25997. /**
  25998. * Creates the VertexData of the LineSystem.
  25999. */
  26000. VertexData.CreateLineSystem = function (options) {
  26001. var indices = [];
  26002. var positions = [];
  26003. var lines = options.lines;
  26004. var idx = 0;
  26005. for (var l = 0; l < lines.length; l++) {
  26006. var points = lines[l];
  26007. for (var index = 0; index < points.length; index++) {
  26008. positions.push(points[index].x, points[index].y, points[index].z);
  26009. if (index > 0) {
  26010. indices.push(idx - 1);
  26011. indices.push(idx);
  26012. }
  26013. idx++;
  26014. }
  26015. }
  26016. var vertexData = new VertexData();
  26017. vertexData.indices = indices;
  26018. vertexData.positions = positions;
  26019. return vertexData;
  26020. };
  26021. /**
  26022. * Create the VertexData of the DashedLines.
  26023. */
  26024. VertexData.CreateDashedLines = function (options) {
  26025. var dashSize = options.dashSize || 3;
  26026. var gapSize = options.gapSize || 1;
  26027. var dashNb = options.dashNb || 200;
  26028. var points = options.points;
  26029. var positions = new Array();
  26030. var indices = new Array();
  26031. var curvect = BABYLON.Vector3.Zero();
  26032. var lg = 0;
  26033. var nb = 0;
  26034. var shft = 0;
  26035. var dashshft = 0;
  26036. var curshft = 0;
  26037. var idx = 0;
  26038. var i = 0;
  26039. for (i = 0; i < points.length - 1; i++) {
  26040. points[i + 1].subtractToRef(points[i], curvect);
  26041. lg += curvect.length();
  26042. }
  26043. shft = lg / dashNb;
  26044. dashshft = dashSize * shft / (dashSize + gapSize);
  26045. for (i = 0; i < points.length - 1; i++) {
  26046. points[i + 1].subtractToRef(points[i], curvect);
  26047. nb = Math.floor(curvect.length() / shft);
  26048. curvect.normalize();
  26049. for (var j = 0; j < nb; j++) {
  26050. curshft = shft * j;
  26051. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26052. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26053. indices.push(idx, idx + 1);
  26054. idx += 2;
  26055. }
  26056. }
  26057. // Result
  26058. var vertexData = new VertexData();
  26059. vertexData.positions = positions;
  26060. vertexData.indices = indices;
  26061. return vertexData;
  26062. };
  26063. /**
  26064. * Creates the VertexData of the Ground.
  26065. */
  26066. VertexData.CreateGround = function (options) {
  26067. var indices = [];
  26068. var positions = [];
  26069. var normals = [];
  26070. var uvs = [];
  26071. var row, col;
  26072. var width = options.width || 1;
  26073. var height = options.height || 1;
  26074. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26075. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26076. for (row = 0; row <= subdivisionsY; row++) {
  26077. for (col = 0; col <= subdivisionsX; col++) {
  26078. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26079. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26080. positions.push(position.x, position.y, position.z);
  26081. normals.push(normal.x, normal.y, normal.z);
  26082. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26083. }
  26084. }
  26085. for (row = 0; row < subdivisionsY; row++) {
  26086. for (col = 0; col < subdivisionsX; col++) {
  26087. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26088. indices.push(col + 1 + row * (subdivisionsX + 1));
  26089. indices.push(col + row * (subdivisionsX + 1));
  26090. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26091. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26092. indices.push(col + row * (subdivisionsX + 1));
  26093. }
  26094. }
  26095. // Result
  26096. var vertexData = new VertexData();
  26097. vertexData.indices = indices;
  26098. vertexData.positions = positions;
  26099. vertexData.normals = normals;
  26100. vertexData.uvs = uvs;
  26101. return vertexData;
  26102. };
  26103. /**
  26104. * Creates the VertexData of the TiledGround.
  26105. */
  26106. VertexData.CreateTiledGround = function (options) {
  26107. var xmin = options.xmin || -1.0;
  26108. var zmin = options.zmin || -1.0;
  26109. var xmax = options.xmax || 1.0;
  26110. var zmax = options.zmax || 1.0;
  26111. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26112. var precision = options.precision || { w: 1, h: 1 };
  26113. var indices = [];
  26114. var positions = [];
  26115. var normals = [];
  26116. var uvs = [];
  26117. var row, col, tileRow, tileCol;
  26118. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26119. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26120. precision.w = (precision.w < 1) ? 1 : precision.w;
  26121. precision.h = (precision.h < 1) ? 1 : precision.h;
  26122. var tileSize = {
  26123. 'w': (xmax - xmin) / subdivisions.w,
  26124. 'h': (zmax - zmin) / subdivisions.h
  26125. };
  26126. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26127. // Indices
  26128. var base = positions.length / 3;
  26129. var rowLength = precision.w + 1;
  26130. for (row = 0; row < precision.h; row++) {
  26131. for (col = 0; col < precision.w; col++) {
  26132. var square = [
  26133. base + col + row * rowLength,
  26134. base + (col + 1) + row * rowLength,
  26135. base + (col + 1) + (row + 1) * rowLength,
  26136. base + col + (row + 1) * rowLength
  26137. ];
  26138. indices.push(square[1]);
  26139. indices.push(square[2]);
  26140. indices.push(square[3]);
  26141. indices.push(square[0]);
  26142. indices.push(square[1]);
  26143. indices.push(square[3]);
  26144. }
  26145. }
  26146. // Position, normals and uvs
  26147. var position = BABYLON.Vector3.Zero();
  26148. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26149. for (row = 0; row <= precision.h; row++) {
  26150. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26151. for (col = 0; col <= precision.w; col++) {
  26152. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26153. position.y = 0;
  26154. positions.push(position.x, position.y, position.z);
  26155. normals.push(normal.x, normal.y, normal.z);
  26156. uvs.push(col / precision.w, row / precision.h);
  26157. }
  26158. }
  26159. }
  26160. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26161. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26162. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26163. }
  26164. }
  26165. // Result
  26166. var vertexData = new VertexData();
  26167. vertexData.indices = indices;
  26168. vertexData.positions = positions;
  26169. vertexData.normals = normals;
  26170. vertexData.uvs = uvs;
  26171. return vertexData;
  26172. };
  26173. /**
  26174. * Creates the VertexData of the Ground designed from a heightmap.
  26175. */
  26176. VertexData.CreateGroundFromHeightMap = function (options) {
  26177. var indices = [];
  26178. var positions = [];
  26179. var normals = [];
  26180. var uvs = [];
  26181. var row, col;
  26182. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26183. // Vertices
  26184. for (row = 0; row <= options.subdivisions; row++) {
  26185. for (col = 0; col <= options.subdivisions; col++) {
  26186. 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));
  26187. // Compute height
  26188. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26189. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26190. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26191. var r = options.buffer[pos] / 255.0;
  26192. var g = options.buffer[pos + 1] / 255.0;
  26193. var b = options.buffer[pos + 2] / 255.0;
  26194. var gradient = r * filter.r + g * filter.g + b * filter.b;
  26195. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26196. // Add vertex
  26197. positions.push(position.x, position.y, position.z);
  26198. normals.push(0, 0, 0);
  26199. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26200. }
  26201. }
  26202. // Indices
  26203. for (row = 0; row < options.subdivisions; row++) {
  26204. for (col = 0; col < options.subdivisions; col++) {
  26205. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26206. indices.push(col + 1 + row * (options.subdivisions + 1));
  26207. indices.push(col + row * (options.subdivisions + 1));
  26208. indices.push(col + (row + 1) * (options.subdivisions + 1));
  26209. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26210. indices.push(col + row * (options.subdivisions + 1));
  26211. }
  26212. }
  26213. // Normals
  26214. VertexData.ComputeNormals(positions, indices, normals);
  26215. // Result
  26216. var vertexData = new VertexData();
  26217. vertexData.indices = indices;
  26218. vertexData.positions = positions;
  26219. vertexData.normals = normals;
  26220. vertexData.uvs = uvs;
  26221. return vertexData;
  26222. };
  26223. /**
  26224. * Creates the VertexData of the Plane.
  26225. */
  26226. VertexData.CreatePlane = function (options) {
  26227. var indices = [];
  26228. var positions = [];
  26229. var normals = [];
  26230. var uvs = [];
  26231. var width = options.width || options.size || 1;
  26232. var height = options.height || options.size || 1;
  26233. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26234. // Vertices
  26235. var halfWidth = width / 2.0;
  26236. var halfHeight = height / 2.0;
  26237. positions.push(-halfWidth, -halfHeight, 0);
  26238. normals.push(0, 0, -1.0);
  26239. uvs.push(0.0, 0.0);
  26240. positions.push(halfWidth, -halfHeight, 0);
  26241. normals.push(0, 0, -1.0);
  26242. uvs.push(1.0, 0.0);
  26243. positions.push(halfWidth, halfHeight, 0);
  26244. normals.push(0, 0, -1.0);
  26245. uvs.push(1.0, 1.0);
  26246. positions.push(-halfWidth, halfHeight, 0);
  26247. normals.push(0, 0, -1.0);
  26248. uvs.push(0.0, 1.0);
  26249. // Indices
  26250. indices.push(0);
  26251. indices.push(1);
  26252. indices.push(2);
  26253. indices.push(0);
  26254. indices.push(2);
  26255. indices.push(3);
  26256. // Sides
  26257. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26258. // Result
  26259. var vertexData = new VertexData();
  26260. vertexData.indices = indices;
  26261. vertexData.positions = positions;
  26262. vertexData.normals = normals;
  26263. vertexData.uvs = uvs;
  26264. return vertexData;
  26265. };
  26266. /**
  26267. * Creates the VertexData of the Disc or regular Polygon.
  26268. */
  26269. VertexData.CreateDisc = function (options) {
  26270. var positions = [];
  26271. var indices = [];
  26272. var normals = [];
  26273. var uvs = [];
  26274. var radius = options.radius || 0.5;
  26275. var tessellation = options.tessellation || 64;
  26276. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26277. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26278. // positions and uvs
  26279. positions.push(0, 0, 0); // disc center first
  26280. uvs.push(0.5, 0.5);
  26281. var theta = Math.PI * 2 * arc;
  26282. var step = theta / tessellation;
  26283. for (var a = 0; a < theta; a += step) {
  26284. var x = Math.cos(a);
  26285. var y = Math.sin(a);
  26286. var u = (x + 1) / 2;
  26287. var v = (1 - y) / 2;
  26288. positions.push(radius * x, radius * y, 0);
  26289. uvs.push(u, v);
  26290. }
  26291. if (arc === 1) {
  26292. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26293. uvs.push(uvs[2], uvs[3]);
  26294. }
  26295. //indices
  26296. var vertexNb = positions.length / 3;
  26297. for (var i = 1; i < vertexNb - 1; i++) {
  26298. indices.push(i + 1, 0, i);
  26299. }
  26300. // result
  26301. VertexData.ComputeNormals(positions, indices, normals);
  26302. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26303. var vertexData = new VertexData();
  26304. vertexData.indices = indices;
  26305. vertexData.positions = positions;
  26306. vertexData.normals = normals;
  26307. vertexData.uvs = uvs;
  26308. return vertexData;
  26309. };
  26310. /**
  26311. * Re-creates the VertexData of the Polygon for sideOrientation.
  26312. */
  26313. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26314. var faceUV = fUV || new Array(3);
  26315. var faceColors = fColors;
  26316. var colors = [];
  26317. // default face colors and UV if undefined
  26318. for (var f = 0; f < 3; f++) {
  26319. if (faceUV[f] === undefined) {
  26320. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26321. }
  26322. if (faceColors && faceColors[f] === undefined) {
  26323. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26324. }
  26325. }
  26326. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26327. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26328. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26329. var indices = polygon.getIndices();
  26330. // set face colours and textures
  26331. var idx = 0;
  26332. var face = 0;
  26333. for (var index = 0; index < normals.length; index += 3) {
  26334. //Edge Face no. 1
  26335. if (Math.abs(normals[index + 1]) == 0) {
  26336. face = 1;
  26337. }
  26338. //Top Face no. 0
  26339. if (normals[index + 1] == 1) {
  26340. face = 0;
  26341. }
  26342. //Bottom Face no. 2
  26343. if (normals[index + 1] == -1) {
  26344. face = 2;
  26345. }
  26346. idx = index / 3;
  26347. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26348. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26349. if (faceColors) {
  26350. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26351. }
  26352. }
  26353. // sides
  26354. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26355. // Result
  26356. var vertexData = new VertexData();
  26357. vertexData.indices = indices;
  26358. vertexData.positions = positions;
  26359. vertexData.normals = normals;
  26360. vertexData.uvs = uvs;
  26361. if (faceColors) {
  26362. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26363. vertexData.colors = totalColors;
  26364. }
  26365. return vertexData;
  26366. };
  26367. /**
  26368. * Creates the VertexData of the IcoSphere.
  26369. */
  26370. VertexData.CreateIcoSphere = function (options) {
  26371. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26372. var radius = options.radius || 1;
  26373. var flat = (options.flat === undefined) ? true : options.flat;
  26374. var subdivisions = options.subdivisions || 4;
  26375. var radiusX = options.radiusX || radius;
  26376. var radiusY = options.radiusY || radius;
  26377. var radiusZ = options.radiusZ || radius;
  26378. var t = (1 + Math.sqrt(5)) / 2;
  26379. // 12 vertex x,y,z
  26380. var ico_vertices = [
  26381. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26382. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26383. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26384. ];
  26385. // index of 3 vertex makes a face of icopshere
  26386. var ico_indices = [
  26387. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26388. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26389. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26390. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26391. ];
  26392. // vertex for uv have aliased position, not for UV
  26393. var vertices_unalias_id = [
  26394. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26395. // vertex alias
  26396. 0,
  26397. 2,
  26398. 3,
  26399. 3,
  26400. 3,
  26401. 4,
  26402. 7,
  26403. 8,
  26404. 9,
  26405. 9,
  26406. 10,
  26407. 11 // 23: B + 12
  26408. ];
  26409. // uv as integer step (not pixels !)
  26410. var ico_vertexuv = [
  26411. 5, 1, 3, 1, 6, 4, 0, 0,
  26412. 5, 3, 4, 2, 2, 2, 4, 0,
  26413. 2, 0, 1, 1, 6, 0, 6, 2,
  26414. // vertex alias (for same vertex on different faces)
  26415. 0, 4,
  26416. 3, 3,
  26417. 4, 4,
  26418. 3, 1,
  26419. 4, 2,
  26420. 4, 4,
  26421. 0, 2,
  26422. 1, 1,
  26423. 2, 2,
  26424. 3, 3,
  26425. 1, 3,
  26426. 2, 4 // 23: B + 12
  26427. ];
  26428. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26429. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26430. // First island of uv mapping
  26431. // v = 4h 3+ 2
  26432. // v = 3h 9+ 4
  26433. // v = 2h 9+ 5 B
  26434. // v = 1h 9 1 0
  26435. // v = 0h 3 8 7 A
  26436. // u = 0 1 2 3 4 5 6 *a
  26437. // Second island of uv mapping
  26438. // v = 4h 0+ B+ 4+
  26439. // v = 3h A+ 2+
  26440. // v = 2h 7+ 6 3+
  26441. // v = 1h 8+ 3+
  26442. // v = 0h
  26443. // u = 0 1 2 3 4 5 6 *a
  26444. // Face layout on texture UV mapping
  26445. // ============
  26446. // \ 4 /\ 16 / ======
  26447. // \ / \ / /\ 11 /
  26448. // \/ 7 \/ / \ /
  26449. // ======= / 10 \/
  26450. // /\ 17 /\ =======
  26451. // / \ / \ \ 15 /\
  26452. // / 8 \/ 12 \ \ / \
  26453. // ============ \/ 6 \
  26454. // \ 18 /\ ============
  26455. // \ / \ \ 5 /\ 0 /
  26456. // \/ 13 \ \ / \ /
  26457. // ======= \/ 1 \/
  26458. // =============
  26459. // /\ 19 /\ 2 /\
  26460. // / \ / \ / \
  26461. // / 14 \/ 9 \/ 3 \
  26462. // ===================
  26463. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26464. var ustep = 138 / 1024;
  26465. var vstep = 239 / 1024;
  26466. var uoffset = 60 / 1024;
  26467. var voffset = 26 / 1024;
  26468. // Second island should have margin, not to touch the first island
  26469. // avoid any borderline artefact in pixel rounding
  26470. var island_u_offset = -40 / 1024;
  26471. var island_v_offset = +20 / 1024;
  26472. // face is either island 0 or 1 :
  26473. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26474. var island = [
  26475. 0, 0, 0, 0, 1,
  26476. 0, 0, 1, 1, 0,
  26477. 0, 0, 1, 1, 0,
  26478. 0, 1, 1, 1, 0 // 15 - 19
  26479. ];
  26480. var indices = [];
  26481. var positions = [];
  26482. var normals = [];
  26483. var uvs = [];
  26484. var current_indice = 0;
  26485. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26486. var face_vertex_pos = new Array(3);
  26487. var face_vertex_uv = new Array(3);
  26488. var v012;
  26489. for (v012 = 0; v012 < 3; v012++) {
  26490. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26491. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26492. }
  26493. // create all with normals
  26494. for (var face = 0; face < 20; face++) {
  26495. // 3 vertex per face
  26496. for (v012 = 0; v012 < 3; v012++) {
  26497. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26498. var v_id = ico_indices[3 * face + v012];
  26499. // vertex have 3D position (x,y,z)
  26500. 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]);
  26501. // Normalize to get normal, then scale to radius
  26502. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26503. // uv Coordinates from vertex ID
  26504. 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);
  26505. }
  26506. // Subdivide the face (interpolate pos, norm, uv)
  26507. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26508. // - norm is linear interpolation of vertex corner normal
  26509. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26510. // - uv is linear interpolation
  26511. //
  26512. // Topology is as below for sub-divide by 2
  26513. // vertex shown as v0,v1,v2
  26514. // interp index is i1 to progress in range [v0,v1[
  26515. // interp index is i2 to progress in range [v0,v2[
  26516. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26517. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26518. //
  26519. //
  26520. // i2 v2
  26521. // ^ ^
  26522. // / / \
  26523. // / / \
  26524. // / / \
  26525. // / / (0,1) \
  26526. // / #---------\
  26527. // / / \ (0,0)'/ \
  26528. // / / \ / \
  26529. // / / \ / \
  26530. // / / (0,0) \ / (1,0) \
  26531. // / #---------#---------\
  26532. // v0 v1
  26533. //
  26534. // --------------------> i1
  26535. //
  26536. // interp of (i1,i2):
  26537. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26538. // along i1 : lerp(x0,x1, i1/(S-i2))
  26539. //
  26540. // centroid of triangle is needed to get help normal computation
  26541. // (c1,c2) are used for centroid location
  26542. var interp_vertex = function (i1, i2, c1, c2) {
  26543. // vertex is interpolated from
  26544. // - face_vertex_pos[0..2]
  26545. // - face_vertex_uv[0..2]
  26546. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26547. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26548. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26549. pos_interp.normalize();
  26550. var vertex_normal;
  26551. if (flat) {
  26552. // in flat mode, recalculate normal as face centroid normal
  26553. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26554. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26555. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26556. }
  26557. else {
  26558. // in smooth mode, recalculate normal from each single vertex position
  26559. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26560. }
  26561. // Vertex normal need correction due to X,Y,Z radius scaling
  26562. vertex_normal.x /= radiusX;
  26563. vertex_normal.y /= radiusY;
  26564. vertex_normal.z /= radiusZ;
  26565. vertex_normal.normalize();
  26566. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26567. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26568. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26569. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26570. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26571. uvs.push(uv_interp.x, uv_interp.y);
  26572. // push each vertex has member of a face
  26573. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26574. indices.push(current_indice);
  26575. current_indice++;
  26576. };
  26577. for (var i2 = 0; i2 < subdivisions; i2++) {
  26578. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26579. // face : (i1,i2) for /\ :
  26580. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26581. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26582. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26583. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26584. if (i1 + i2 + 1 < subdivisions) {
  26585. // face : (i1,i2)' for \/ :
  26586. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26587. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26588. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26589. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26590. }
  26591. }
  26592. }
  26593. }
  26594. // Sides
  26595. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26596. // Result
  26597. var vertexData = new VertexData();
  26598. vertexData.indices = indices;
  26599. vertexData.positions = positions;
  26600. vertexData.normals = normals;
  26601. vertexData.uvs = uvs;
  26602. return vertexData;
  26603. };
  26604. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26605. /**
  26606. * Creates the VertexData of the Polyhedron.
  26607. */
  26608. VertexData.CreatePolyhedron = function (options) {
  26609. // provided polyhedron types :
  26610. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26611. // 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)
  26612. var polyhedra = [];
  26613. 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]] };
  26614. 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]] };
  26615. polyhedra[2] = {
  26616. 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]],
  26617. 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]]
  26618. };
  26619. polyhedra[3] = {
  26620. 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]],
  26621. 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]]
  26622. };
  26623. polyhedra[4] = {
  26624. 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]],
  26625. 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]]
  26626. };
  26627. 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]] };
  26628. 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]] };
  26629. 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]] };
  26630. 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]] };
  26631. 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]] };
  26632. 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]] };
  26633. 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]] };
  26634. 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]] };
  26635. 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]] };
  26636. polyhedra[14] = {
  26637. 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]],
  26638. 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]]
  26639. };
  26640. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26641. var size = options.size;
  26642. var sizeX = options.sizeX || size || 1;
  26643. var sizeY = options.sizeY || size || 1;
  26644. var sizeZ = options.sizeZ || size || 1;
  26645. var data = options.custom || polyhedra[type];
  26646. var nbfaces = data.face.length;
  26647. var faceUV = options.faceUV || new Array(nbfaces);
  26648. var faceColors = options.faceColors;
  26649. var flat = (options.flat === undefined) ? true : options.flat;
  26650. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26651. var positions = [];
  26652. var indices = [];
  26653. var normals = [];
  26654. var uvs = [];
  26655. var colors = [];
  26656. var index = 0;
  26657. var faceIdx = 0; // face cursor in the array "indexes"
  26658. var indexes = [];
  26659. var i = 0;
  26660. var f = 0;
  26661. var u, v, ang, x, y, tmp;
  26662. // default face colors and UV if undefined
  26663. if (flat) {
  26664. for (f = 0; f < nbfaces; f++) {
  26665. if (faceColors && faceColors[f] === undefined) {
  26666. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26667. }
  26668. if (faceUV && faceUV[f] === undefined) {
  26669. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26670. }
  26671. }
  26672. }
  26673. if (!flat) {
  26674. for (i = 0; i < data.vertex.length; i++) {
  26675. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26676. uvs.push(0, 0);
  26677. }
  26678. for (f = 0; f < nbfaces; f++) {
  26679. for (i = 0; i < data.face[f].length - 2; i++) {
  26680. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26681. }
  26682. }
  26683. }
  26684. else {
  26685. for (f = 0; f < nbfaces; f++) {
  26686. var fl = data.face[f].length; // number of vertices of the current face
  26687. ang = 2 * Math.PI / fl;
  26688. x = 0.5 * Math.tan(ang / 2);
  26689. y = 0.5;
  26690. // positions, uvs, colors
  26691. for (i = 0; i < fl; i++) {
  26692. // positions
  26693. 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);
  26694. indexes.push(index);
  26695. index++;
  26696. // uvs
  26697. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26698. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26699. uvs.push(u, v);
  26700. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26701. y = x * Math.sin(ang) + y * Math.cos(ang);
  26702. x = tmp;
  26703. // colors
  26704. if (faceColors) {
  26705. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26706. }
  26707. }
  26708. // indices from indexes
  26709. for (i = 0; i < fl - 2; i++) {
  26710. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26711. }
  26712. faceIdx += fl;
  26713. }
  26714. }
  26715. VertexData.ComputeNormals(positions, indices, normals);
  26716. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26717. var vertexData = new VertexData();
  26718. vertexData.positions = positions;
  26719. vertexData.indices = indices;
  26720. vertexData.normals = normals;
  26721. vertexData.uvs = uvs;
  26722. if (faceColors && flat) {
  26723. vertexData.colors = colors;
  26724. }
  26725. return vertexData;
  26726. };
  26727. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26728. /**
  26729. * Creates the VertexData of the Torus Knot.
  26730. */
  26731. VertexData.CreateTorusKnot = function (options) {
  26732. var indices = [];
  26733. var positions = [];
  26734. var normals = [];
  26735. var uvs = [];
  26736. var radius = options.radius || 2;
  26737. var tube = options.tube || 0.5;
  26738. var radialSegments = options.radialSegments || 32;
  26739. var tubularSegments = options.tubularSegments || 32;
  26740. var p = options.p || 2;
  26741. var q = options.q || 3;
  26742. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26743. // Helper
  26744. var getPos = function (angle) {
  26745. var cu = Math.cos(angle);
  26746. var su = Math.sin(angle);
  26747. var quOverP = q / p * angle;
  26748. var cs = Math.cos(quOverP);
  26749. var tx = radius * (2 + cs) * 0.5 * cu;
  26750. var ty = radius * (2 + cs) * su * 0.5;
  26751. var tz = radius * Math.sin(quOverP) * 0.5;
  26752. return new BABYLON.Vector3(tx, ty, tz);
  26753. };
  26754. // Vertices
  26755. var i;
  26756. var j;
  26757. for (i = 0; i <= radialSegments; i++) {
  26758. var modI = i % radialSegments;
  26759. var u = modI / radialSegments * 2 * p * Math.PI;
  26760. var p1 = getPos(u);
  26761. var p2 = getPos(u + 0.01);
  26762. var tang = p2.subtract(p1);
  26763. var n = p2.add(p1);
  26764. var bitan = BABYLON.Vector3.Cross(tang, n);
  26765. n = BABYLON.Vector3.Cross(bitan, tang);
  26766. bitan.normalize();
  26767. n.normalize();
  26768. for (j = 0; j < tubularSegments; j++) {
  26769. var modJ = j % tubularSegments;
  26770. var v = modJ / tubularSegments * 2 * Math.PI;
  26771. var cx = -tube * Math.cos(v);
  26772. var cy = tube * Math.sin(v);
  26773. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26774. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26775. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26776. uvs.push(i / radialSegments);
  26777. uvs.push(j / tubularSegments);
  26778. }
  26779. }
  26780. for (i = 0; i < radialSegments; i++) {
  26781. for (j = 0; j < tubularSegments; j++) {
  26782. var jNext = (j + 1) % tubularSegments;
  26783. var a = i * tubularSegments + j;
  26784. var b = (i + 1) * tubularSegments + j;
  26785. var c = (i + 1) * tubularSegments + jNext;
  26786. var d = i * tubularSegments + jNext;
  26787. indices.push(d);
  26788. indices.push(b);
  26789. indices.push(a);
  26790. indices.push(d);
  26791. indices.push(c);
  26792. indices.push(b);
  26793. }
  26794. }
  26795. // Normals
  26796. VertexData.ComputeNormals(positions, indices, normals);
  26797. // Sides
  26798. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26799. // Result
  26800. var vertexData = new VertexData();
  26801. vertexData.indices = indices;
  26802. vertexData.positions = positions;
  26803. vertexData.normals = normals;
  26804. vertexData.uvs = uvs;
  26805. return vertexData;
  26806. };
  26807. // Tools
  26808. /**
  26809. * @param {any} - positions (number[] or Float32Array)
  26810. * @param {any} - indices (number[] or Uint16Array)
  26811. * @param {any} - normals (number[] or Float32Array)
  26812. * options (optional) :
  26813. * facetPositions : optional array of facet positions (vector3)
  26814. * facetNormals : optional array of facet normals (vector3)
  26815. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26816. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26817. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26818. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26819. * bInfo : optional bounding info, required for facetPartitioning computation
  26820. */
  26821. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26822. // temporary scalar variables
  26823. var index = 0; // facet index
  26824. var p1p2x = 0.0; // p1p2 vector x coordinate
  26825. var p1p2y = 0.0; // p1p2 vector y coordinate
  26826. var p1p2z = 0.0; // p1p2 vector z coordinate
  26827. var p3p2x = 0.0; // p3p2 vector x coordinate
  26828. var p3p2y = 0.0; // p3p2 vector y coordinate
  26829. var p3p2z = 0.0; // p3p2 vector z coordinate
  26830. var faceNormalx = 0.0; // facet normal x coordinate
  26831. var faceNormaly = 0.0; // facet normal y coordinate
  26832. var faceNormalz = 0.0; // facet normal z coordinate
  26833. var length = 0.0; // facet normal length before normalization
  26834. var v1x = 0; // vector1 x index in the positions array
  26835. var v1y = 0; // vector1 y index in the positions array
  26836. var v1z = 0; // vector1 z index in the positions array
  26837. var v2x = 0; // vector2 x index in the positions array
  26838. var v2y = 0; // vector2 y index in the positions array
  26839. var v2z = 0; // vector2 z index in the positions array
  26840. var v3x = 0; // vector3 x index in the positions array
  26841. var v3y = 0; // vector3 y index in the positions array
  26842. var v3z = 0; // vector3 z index in the positions array
  26843. var computeFacetNormals = false;
  26844. var computeFacetPositions = false;
  26845. var computeFacetPartitioning = false;
  26846. var faceNormalSign = 1;
  26847. if (options) {
  26848. computeFacetNormals = (options.facetNormals) ? true : false;
  26849. computeFacetPositions = (options.facetPositions) ? true : false;
  26850. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26851. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26852. }
  26853. // facetPartitioning reinit if needed
  26854. if (computeFacetPartitioning) {
  26855. var ox = 0; // X partitioning index for facet position
  26856. var oy = 0; // Y partinioning index for facet position
  26857. var oz = 0; // Z partinioning index for facet position
  26858. var b1x = 0; // X partitioning index for facet v1 vertex
  26859. var b1y = 0; // Y partitioning index for facet v1 vertex
  26860. var b1z = 0; // z partitioning index for facet v1 vertex
  26861. var b2x = 0; // X partitioning index for facet v2 vertex
  26862. var b2y = 0; // Y partitioning index for facet v2 vertex
  26863. var b2z = 0; // Z partitioning index for facet v2 vertex
  26864. var b3x = 0; // X partitioning index for facet v3 vertex
  26865. var b3y = 0; // Y partitioning index for facet v3 vertex
  26866. var b3z = 0; // Z partitioning index for facet v3 vertex
  26867. var block_idx_o = 0; // facet barycenter block index
  26868. var block_idx_v1 = 0; // v1 vertex block index
  26869. var block_idx_v2 = 0; // v2 vertex block index
  26870. var block_idx_v3 = 0; // v3 vertex block index
  26871. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26872. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26873. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26874. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26875. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26876. var subSq = options.subDiv.max * options.subDiv.max;
  26877. options.facetPartitioning.length = 0;
  26878. }
  26879. // reset the normals
  26880. for (index = 0; index < positions.length; index++) {
  26881. normals[index] = 0.0;
  26882. }
  26883. // Loop : 1 indice triplet = 1 facet
  26884. var nbFaces = indices.length / 3;
  26885. for (index = 0; index < nbFaces; index++) {
  26886. // get the indexes of the coordinates of each vertex of the facet
  26887. v1x = indices[index * 3] * 3;
  26888. v1y = v1x + 1;
  26889. v1z = v1x + 2;
  26890. v2x = indices[index * 3 + 1] * 3;
  26891. v2y = v2x + 1;
  26892. v2z = v2x + 2;
  26893. v3x = indices[index * 3 + 2] * 3;
  26894. v3y = v3x + 1;
  26895. v3z = v3x + 2;
  26896. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26897. p1p2y = positions[v1y] - positions[v2y];
  26898. p1p2z = positions[v1z] - positions[v2z];
  26899. p3p2x = positions[v3x] - positions[v2x];
  26900. p3p2y = positions[v3y] - positions[v2y];
  26901. p3p2z = positions[v3z] - positions[v2z];
  26902. // compute the face normal with the cross product
  26903. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26904. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26905. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26906. // normalize this normal and store it in the array facetData
  26907. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26908. length = (length === 0) ? 1.0 : length;
  26909. faceNormalx /= length;
  26910. faceNormaly /= length;
  26911. faceNormalz /= length;
  26912. if (computeFacetNormals) {
  26913. options.facetNormals[index].x = faceNormalx;
  26914. options.facetNormals[index].y = faceNormaly;
  26915. options.facetNormals[index].z = faceNormalz;
  26916. }
  26917. if (computeFacetPositions) {
  26918. // compute and the facet barycenter coordinates in the array facetPositions
  26919. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26920. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26921. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26922. }
  26923. if (computeFacetPartitioning) {
  26924. // store the facet indexes in arrays in the main facetPartitioning array :
  26925. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26926. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26927. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26928. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26929. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26930. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26931. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26932. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26933. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26934. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26935. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26936. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26937. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26938. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26939. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26940. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26941. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26942. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26943. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26944. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26945. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26946. // push each facet index in each block containing the vertex
  26947. options.facetPartitioning[block_idx_v1].push(index);
  26948. if (block_idx_v2 != block_idx_v1) {
  26949. options.facetPartitioning[block_idx_v2].push(index);
  26950. }
  26951. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26952. options.facetPartitioning[block_idx_v3].push(index);
  26953. }
  26954. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26955. options.facetPartitioning[block_idx_o].push(index);
  26956. }
  26957. }
  26958. // compute the normals anyway
  26959. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26960. normals[v1y] += faceNormaly;
  26961. normals[v1z] += faceNormalz;
  26962. normals[v2x] += faceNormalx;
  26963. normals[v2y] += faceNormaly;
  26964. normals[v2z] += faceNormalz;
  26965. normals[v3x] += faceNormalx;
  26966. normals[v3y] += faceNormaly;
  26967. normals[v3z] += faceNormalz;
  26968. }
  26969. // last normalization of each normal
  26970. for (index = 0; index < normals.length / 3; index++) {
  26971. faceNormalx = normals[index * 3];
  26972. faceNormaly = normals[index * 3 + 1];
  26973. faceNormalz = normals[index * 3 + 2];
  26974. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26975. length = (length === 0) ? 1.0 : length;
  26976. faceNormalx /= length;
  26977. faceNormaly /= length;
  26978. faceNormalz /= length;
  26979. normals[index * 3] = faceNormalx;
  26980. normals[index * 3 + 1] = faceNormaly;
  26981. normals[index * 3 + 2] = faceNormalz;
  26982. }
  26983. };
  26984. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26985. var li = indices.length;
  26986. var ln = normals.length;
  26987. var i;
  26988. var n;
  26989. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26990. switch (sideOrientation) {
  26991. case BABYLON.Mesh.FRONTSIDE:
  26992. // nothing changed
  26993. break;
  26994. case BABYLON.Mesh.BACKSIDE:
  26995. var tmp;
  26996. // indices
  26997. for (i = 0; i < li; i += 3) {
  26998. tmp = indices[i];
  26999. indices[i] = indices[i + 2];
  27000. indices[i + 2] = tmp;
  27001. }
  27002. // normals
  27003. for (n = 0; n < ln; n++) {
  27004. normals[n] = -normals[n];
  27005. }
  27006. break;
  27007. case BABYLON.Mesh.DOUBLESIDE:
  27008. // positions
  27009. var lp = positions.length;
  27010. var l = lp / 3;
  27011. for (var p = 0; p < lp; p++) {
  27012. positions[lp + p] = positions[p];
  27013. }
  27014. // indices
  27015. for (i = 0; i < li; i += 3) {
  27016. indices[i + li] = indices[i + 2] + l;
  27017. indices[i + 1 + li] = indices[i + 1] + l;
  27018. indices[i + 2 + li] = indices[i] + l;
  27019. }
  27020. // normals
  27021. for (n = 0; n < ln; n++) {
  27022. normals[ln + n] = -normals[n];
  27023. }
  27024. // uvs
  27025. var lu = uvs.length;
  27026. var u = 0;
  27027. for (u = 0; u < lu; u++) {
  27028. uvs[u + lu] = uvs[u];
  27029. }
  27030. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27031. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27032. u = 0;
  27033. for (i = 0; i < lu / 2; i++) {
  27034. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  27035. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  27036. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  27037. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  27038. u += 2;
  27039. }
  27040. break;
  27041. }
  27042. };
  27043. /**
  27044. * Creates a new VertexData from the imported parameters.
  27045. */
  27046. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27047. var vertexData = new VertexData();
  27048. // positions
  27049. var positions = parsedVertexData.positions;
  27050. if (positions) {
  27051. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27052. }
  27053. // normals
  27054. var normals = parsedVertexData.normals;
  27055. if (normals) {
  27056. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27057. }
  27058. // tangents
  27059. var tangents = parsedVertexData.tangents;
  27060. if (tangents) {
  27061. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27062. }
  27063. // uvs
  27064. var uvs = parsedVertexData.uvs;
  27065. if (uvs) {
  27066. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27067. }
  27068. // uv2s
  27069. var uv2s = parsedVertexData.uv2s;
  27070. if (uv2s) {
  27071. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27072. }
  27073. // uv3s
  27074. var uv3s = parsedVertexData.uv3s;
  27075. if (uv3s) {
  27076. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27077. }
  27078. // uv4s
  27079. var uv4s = parsedVertexData.uv4s;
  27080. if (uv4s) {
  27081. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27082. }
  27083. // uv5s
  27084. var uv5s = parsedVertexData.uv5s;
  27085. if (uv5s) {
  27086. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27087. }
  27088. // uv6s
  27089. var uv6s = parsedVertexData.uv6s;
  27090. if (uv6s) {
  27091. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27092. }
  27093. // colors
  27094. var colors = parsedVertexData.colors;
  27095. if (colors) {
  27096. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27097. }
  27098. // matricesIndices
  27099. var matricesIndices = parsedVertexData.matricesIndices;
  27100. if (matricesIndices) {
  27101. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27102. }
  27103. // matricesWeights
  27104. var matricesWeights = parsedVertexData.matricesWeights;
  27105. if (matricesWeights) {
  27106. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27107. }
  27108. // indices
  27109. var indices = parsedVertexData.indices;
  27110. if (indices) {
  27111. vertexData.indices = indices;
  27112. }
  27113. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27114. };
  27115. return VertexData;
  27116. }());
  27117. BABYLON.VertexData = VertexData;
  27118. })(BABYLON || (BABYLON = {}));
  27119. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27120. var BABYLON;
  27121. (function (BABYLON) {
  27122. var Geometry = (function () {
  27123. function Geometry(id, scene, vertexData, updatable, mesh) {
  27124. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27125. this._totalVertices = 0;
  27126. this._isDisposed = false;
  27127. this.id = id;
  27128. this._engine = scene.getEngine();
  27129. this._meshes = [];
  27130. this._scene = scene;
  27131. //Init vertex buffer cache
  27132. this._vertexBuffers = {};
  27133. this._indices = [];
  27134. // vertexData
  27135. if (vertexData) {
  27136. this.setAllVerticesData(vertexData, updatable);
  27137. }
  27138. else {
  27139. this._totalVertices = 0;
  27140. this._indices = [];
  27141. }
  27142. if (this._engine.getCaps().vertexArrayObject) {
  27143. this._vertexArrayObjects = {};
  27144. }
  27145. // applyToMesh
  27146. if (mesh) {
  27147. if (mesh.getClassName() === "LinesMesh") {
  27148. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  27149. this.updateExtend();
  27150. }
  27151. this.applyToMesh(mesh);
  27152. mesh.computeWorldMatrix(true);
  27153. }
  27154. }
  27155. Object.defineProperty(Geometry.prototype, "boundingBias", {
  27156. /**
  27157. * 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
  27158. * @returns The Bias Vector
  27159. */
  27160. get: function () {
  27161. return this._boundingBias;
  27162. },
  27163. set: function (value) {
  27164. if (this._boundingBias && this._boundingBias.equals(value)) {
  27165. return;
  27166. }
  27167. this._boundingBias = value.clone();
  27168. this.updateBoundingInfo(true, null);
  27169. },
  27170. enumerable: true,
  27171. configurable: true
  27172. });
  27173. Object.defineProperty(Geometry.prototype, "extend", {
  27174. get: function () {
  27175. return this._extend;
  27176. },
  27177. enumerable: true,
  27178. configurable: true
  27179. });
  27180. Geometry.prototype.getScene = function () {
  27181. return this._scene;
  27182. };
  27183. Geometry.prototype.getEngine = function () {
  27184. return this._engine;
  27185. };
  27186. Geometry.prototype.isReady = function () {
  27187. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27188. };
  27189. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  27190. get: function () {
  27191. for (var index = 0; index < this._meshes.length; index++) {
  27192. if (!this._meshes[index].doNotSerialize) {
  27193. return false;
  27194. }
  27195. }
  27196. return true;
  27197. },
  27198. enumerable: true,
  27199. configurable: true
  27200. });
  27201. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27202. vertexData.applyToGeometry(this, updatable);
  27203. this.notifyUpdate();
  27204. };
  27205. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27206. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27207. this.setVerticesBuffer(buffer);
  27208. };
  27209. Geometry.prototype.removeVerticesData = function (kind) {
  27210. if (this._vertexBuffers[kind]) {
  27211. this._vertexBuffers[kind].dispose();
  27212. delete this._vertexBuffers[kind];
  27213. }
  27214. };
  27215. Geometry.prototype.setVerticesBuffer = function (buffer) {
  27216. var kind = buffer.getKind();
  27217. if (this._vertexBuffers[kind]) {
  27218. this._vertexBuffers[kind].dispose();
  27219. }
  27220. this._vertexBuffers[kind] = buffer;
  27221. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27222. var data = buffer.getData();
  27223. var stride = buffer.getStrideSize();
  27224. this._totalVertices = data.length / stride;
  27225. this.updateExtend(data, stride);
  27226. this._resetPointsArrayCache();
  27227. var meshes = this._meshes;
  27228. var numOfMeshes = meshes.length;
  27229. for (var index = 0; index < numOfMeshes; index++) {
  27230. var mesh = meshes[index];
  27231. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27232. mesh._createGlobalSubMesh();
  27233. mesh.computeWorldMatrix(true);
  27234. }
  27235. }
  27236. this.notifyUpdate(kind);
  27237. if (this._vertexArrayObjects) {
  27238. this._disposeVertexArrayObjects();
  27239. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  27240. }
  27241. };
  27242. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27243. var vertexBuffer = this.getVertexBuffer(kind);
  27244. if (!vertexBuffer) {
  27245. return;
  27246. }
  27247. vertexBuffer.updateDirectly(data, offset);
  27248. this.notifyUpdate(kind);
  27249. };
  27250. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27251. var vertexBuffer = this.getVertexBuffer(kind);
  27252. if (!vertexBuffer) {
  27253. return;
  27254. }
  27255. vertexBuffer.update(data);
  27256. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27257. var stride = vertexBuffer.getStrideSize();
  27258. this._totalVertices = data.length / stride;
  27259. this.updateBoundingInfo(updateExtends, data);
  27260. }
  27261. this.notifyUpdate(kind);
  27262. };
  27263. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27264. if (updateExtends) {
  27265. this.updateExtend(data);
  27266. }
  27267. var meshes = this._meshes;
  27268. var numOfMeshes = meshes.length;
  27269. this._resetPointsArrayCache();
  27270. for (var index = 0; index < numOfMeshes; index++) {
  27271. var mesh = meshes[index];
  27272. if (updateExtends) {
  27273. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27274. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27275. var subMesh = mesh.subMeshes[subIndex];
  27276. subMesh.refreshBoundingInfo();
  27277. }
  27278. }
  27279. }
  27280. };
  27281. Geometry.prototype._bind = function (effect, indexToBind) {
  27282. if (indexToBind === void 0) { indexToBind = undefined; }
  27283. if (indexToBind === undefined) {
  27284. indexToBind = this._indexBuffer;
  27285. }
  27286. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27287. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27288. return;
  27289. }
  27290. // Using VAO
  27291. if (!this._vertexArrayObjects[effect.key]) {
  27292. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27293. }
  27294. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27295. };
  27296. Geometry.prototype.getTotalVertices = function () {
  27297. if (!this.isReady()) {
  27298. return 0;
  27299. }
  27300. return this._totalVertices;
  27301. };
  27302. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27303. var vertexBuffer = this.getVertexBuffer(kind);
  27304. if (!vertexBuffer) {
  27305. return null;
  27306. }
  27307. var orig = vertexBuffer.getData();
  27308. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27309. return orig;
  27310. }
  27311. else {
  27312. var len = orig.length;
  27313. var copy = [];
  27314. for (var i = 0; i < len; i++) {
  27315. copy.push(orig[i]);
  27316. }
  27317. return copy;
  27318. }
  27319. };
  27320. Geometry.prototype.getVertexBuffer = function (kind) {
  27321. if (!this.isReady()) {
  27322. return null;
  27323. }
  27324. return this._vertexBuffers[kind];
  27325. };
  27326. Geometry.prototype.getVertexBuffers = function () {
  27327. if (!this.isReady()) {
  27328. return null;
  27329. }
  27330. return this._vertexBuffers;
  27331. };
  27332. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27333. if (!this._vertexBuffers) {
  27334. if (this._delayInfo) {
  27335. return this._delayInfo.indexOf(kind) !== -1;
  27336. }
  27337. return false;
  27338. }
  27339. return this._vertexBuffers[kind] !== undefined;
  27340. };
  27341. Geometry.prototype.getVerticesDataKinds = function () {
  27342. var result = [];
  27343. var kind;
  27344. if (!this._vertexBuffers && this._delayInfo) {
  27345. for (kind in this._delayInfo) {
  27346. result.push(kind);
  27347. }
  27348. }
  27349. else {
  27350. for (kind in this._vertexBuffers) {
  27351. result.push(kind);
  27352. }
  27353. }
  27354. return result;
  27355. };
  27356. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27357. if (this._indexBuffer) {
  27358. this._engine._releaseBuffer(this._indexBuffer);
  27359. }
  27360. this._disposeVertexArrayObjects();
  27361. this._indices = indices;
  27362. if (this._meshes.length !== 0 && this._indices) {
  27363. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27364. }
  27365. if (totalVertices !== undefined) {
  27366. this._totalVertices = totalVertices;
  27367. }
  27368. var meshes = this._meshes;
  27369. var numOfMeshes = meshes.length;
  27370. for (var index = 0; index < numOfMeshes; index++) {
  27371. meshes[index]._createGlobalSubMesh();
  27372. }
  27373. this.notifyUpdate();
  27374. };
  27375. Geometry.prototype.getTotalIndices = function () {
  27376. if (!this.isReady()) {
  27377. return 0;
  27378. }
  27379. return this._indices.length;
  27380. };
  27381. Geometry.prototype.getIndices = function (copyWhenShared) {
  27382. if (!this.isReady()) {
  27383. return null;
  27384. }
  27385. var orig = this._indices;
  27386. if (!copyWhenShared || this._meshes.length === 1) {
  27387. return orig;
  27388. }
  27389. else {
  27390. var len = orig.length;
  27391. var copy = [];
  27392. for (var i = 0; i < len; i++) {
  27393. copy.push(orig[i]);
  27394. }
  27395. return copy;
  27396. }
  27397. };
  27398. Geometry.prototype.getIndexBuffer = function () {
  27399. if (!this.isReady()) {
  27400. return null;
  27401. }
  27402. return this._indexBuffer;
  27403. };
  27404. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27405. if (!effect || !this._vertexArrayObjects) {
  27406. return;
  27407. }
  27408. if (this._vertexArrayObjects[effect.key]) {
  27409. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27410. delete this._vertexArrayObjects[effect.key];
  27411. }
  27412. };
  27413. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27414. var meshes = this._meshes;
  27415. var index = meshes.indexOf(mesh);
  27416. if (index === -1) {
  27417. return;
  27418. }
  27419. meshes.splice(index, 1);
  27420. mesh._geometry = null;
  27421. if (meshes.length === 0 && shouldDispose) {
  27422. this.dispose();
  27423. }
  27424. };
  27425. Geometry.prototype.applyToMesh = function (mesh) {
  27426. if (mesh._geometry === this) {
  27427. return;
  27428. }
  27429. var previousGeometry = mesh._geometry;
  27430. if (previousGeometry) {
  27431. previousGeometry.releaseForMesh(mesh);
  27432. }
  27433. var meshes = this._meshes;
  27434. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27435. mesh._geometry = this;
  27436. this._scene.pushGeometry(this);
  27437. meshes.push(mesh);
  27438. if (this.isReady()) {
  27439. this._applyToMesh(mesh);
  27440. }
  27441. else {
  27442. mesh._boundingInfo = this._boundingInfo;
  27443. }
  27444. };
  27445. Geometry.prototype.updateExtend = function (data, stride) {
  27446. if (data === void 0) { data = null; }
  27447. if (!data) {
  27448. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27449. }
  27450. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27451. };
  27452. Geometry.prototype._applyToMesh = function (mesh) {
  27453. var numOfMeshes = this._meshes.length;
  27454. // vertexBuffers
  27455. for (var kind in this._vertexBuffers) {
  27456. if (numOfMeshes === 1) {
  27457. this._vertexBuffers[kind].create();
  27458. }
  27459. var buffer = this._vertexBuffers[kind].getBuffer();
  27460. if (buffer)
  27461. buffer.references = numOfMeshes;
  27462. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27463. if (!this._extend) {
  27464. this.updateExtend(this._vertexBuffers[kind].getData());
  27465. }
  27466. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27467. mesh._createGlobalSubMesh();
  27468. //bounding info was just created again, world matrix should be applied again.
  27469. mesh._updateBoundingInfo();
  27470. }
  27471. }
  27472. // indexBuffer
  27473. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27474. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27475. }
  27476. if (this._indexBuffer) {
  27477. this._indexBuffer.references = numOfMeshes;
  27478. }
  27479. };
  27480. Geometry.prototype.notifyUpdate = function (kind) {
  27481. if (this.onGeometryUpdated) {
  27482. this.onGeometryUpdated(this, kind);
  27483. }
  27484. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27485. var mesh = _a[_i];
  27486. mesh._markSubMeshesAsAttributesDirty();
  27487. }
  27488. };
  27489. Geometry.prototype.load = function (scene, onLoaded) {
  27490. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27491. return;
  27492. }
  27493. if (this.isReady()) {
  27494. if (onLoaded) {
  27495. onLoaded();
  27496. }
  27497. return;
  27498. }
  27499. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27500. this._queueLoad(scene, onLoaded);
  27501. };
  27502. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27503. var _this = this;
  27504. scene._addPendingData(this);
  27505. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27506. _this._delayLoadingFunction(JSON.parse(data), _this);
  27507. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27508. _this._delayInfo = [];
  27509. scene._removePendingData(_this);
  27510. var meshes = _this._meshes;
  27511. var numOfMeshes = meshes.length;
  27512. for (var index = 0; index < numOfMeshes; index++) {
  27513. _this._applyToMesh(meshes[index]);
  27514. }
  27515. if (onLoaded) {
  27516. onLoaded();
  27517. }
  27518. }, function () { }, scene.database);
  27519. };
  27520. /**
  27521. * Invert the geometry to move from a right handed system to a left handed one.
  27522. */
  27523. Geometry.prototype.toLeftHanded = function () {
  27524. // Flip faces
  27525. var tIndices = this.getIndices(false);
  27526. if (tIndices != null && tIndices.length > 0) {
  27527. for (var i = 0; i < tIndices.length; i += 3) {
  27528. var tTemp = tIndices[i + 0];
  27529. tIndices[i + 0] = tIndices[i + 2];
  27530. tIndices[i + 2] = tTemp;
  27531. }
  27532. this.setIndices(tIndices);
  27533. }
  27534. // Negate position.z
  27535. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27536. if (tPositions != null && tPositions.length > 0) {
  27537. for (var i = 0; i < tPositions.length; i += 3) {
  27538. tPositions[i + 2] = -tPositions[i + 2];
  27539. }
  27540. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27541. }
  27542. // Negate normal.z
  27543. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27544. if (tNormals != null && tNormals.length > 0) {
  27545. for (var i = 0; i < tNormals.length; i += 3) {
  27546. tNormals[i + 2] = -tNormals[i + 2];
  27547. }
  27548. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27549. }
  27550. };
  27551. // Cache
  27552. Geometry.prototype._resetPointsArrayCache = function () {
  27553. this._positions = null;
  27554. };
  27555. Geometry.prototype._generatePointsArray = function () {
  27556. if (this._positions)
  27557. return true;
  27558. this._positions = [];
  27559. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27560. if (!data) {
  27561. return false;
  27562. }
  27563. for (var index = 0; index < data.length; index += 3) {
  27564. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27565. }
  27566. return true;
  27567. };
  27568. Geometry.prototype.isDisposed = function () {
  27569. return this._isDisposed;
  27570. };
  27571. Geometry.prototype._disposeVertexArrayObjects = function () {
  27572. if (this._vertexArrayObjects) {
  27573. for (var kind in this._vertexArrayObjects) {
  27574. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27575. }
  27576. this._vertexArrayObjects = {};
  27577. }
  27578. };
  27579. Geometry.prototype.dispose = function () {
  27580. var meshes = this._meshes;
  27581. var numOfMeshes = meshes.length;
  27582. var index;
  27583. for (index = 0; index < numOfMeshes; index++) {
  27584. this.releaseForMesh(meshes[index]);
  27585. }
  27586. this._meshes = [];
  27587. this._disposeVertexArrayObjects();
  27588. for (var kind in this._vertexBuffers) {
  27589. this._vertexBuffers[kind].dispose();
  27590. }
  27591. this._vertexBuffers = {};
  27592. this._totalVertices = 0;
  27593. if (this._indexBuffer) {
  27594. this._engine._releaseBuffer(this._indexBuffer);
  27595. }
  27596. this._indexBuffer = null;
  27597. this._indices = [];
  27598. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27599. this.delayLoadingFile = null;
  27600. this._delayLoadingFunction = null;
  27601. this._delayInfo = [];
  27602. this._boundingInfo = null;
  27603. this._scene.removeGeometry(this);
  27604. this._isDisposed = true;
  27605. };
  27606. Geometry.prototype.copy = function (id) {
  27607. var vertexData = new BABYLON.VertexData();
  27608. vertexData.indices = [];
  27609. var indices = this.getIndices();
  27610. for (var index = 0; index < indices.length; index++) {
  27611. vertexData.indices.push(indices[index]);
  27612. }
  27613. var updatable = false;
  27614. var stopChecking = false;
  27615. var kind;
  27616. for (kind in this._vertexBuffers) {
  27617. // using slice() to make a copy of the array and not just reference it
  27618. var data = this.getVerticesData(kind);
  27619. if (data instanceof Float32Array) {
  27620. vertexData.set(new Float32Array(data), kind);
  27621. }
  27622. else {
  27623. vertexData.set(data.slice(0), kind);
  27624. }
  27625. if (!stopChecking) {
  27626. updatable = this.getVertexBuffer(kind).isUpdatable();
  27627. stopChecking = !updatable;
  27628. }
  27629. }
  27630. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27631. geometry.delayLoadState = this.delayLoadState;
  27632. geometry.delayLoadingFile = this.delayLoadingFile;
  27633. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27634. for (kind in this._delayInfo) {
  27635. geometry._delayInfo = geometry._delayInfo || [];
  27636. geometry._delayInfo.push(kind);
  27637. }
  27638. // Bounding info
  27639. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27640. return geometry;
  27641. };
  27642. Geometry.prototype.serialize = function () {
  27643. var serializationObject = {};
  27644. serializationObject.id = this.id;
  27645. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27646. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27647. }
  27648. return serializationObject;
  27649. };
  27650. Geometry.prototype.toNumberArray = function (origin) {
  27651. if (Array.isArray(origin)) {
  27652. return origin;
  27653. }
  27654. else {
  27655. return Array.prototype.slice.call(origin);
  27656. }
  27657. };
  27658. Geometry.prototype.serializeVerticeData = function () {
  27659. var serializationObject = this.serialize();
  27660. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27661. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27662. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27663. serializationObject.positions._updatable = true;
  27664. }
  27665. }
  27666. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27667. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27668. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27669. serializationObject.normals._updatable = true;
  27670. }
  27671. }
  27672. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27673. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27674. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27675. serializationObject.uvs._updatable = true;
  27676. }
  27677. }
  27678. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27679. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27680. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27681. serializationObject.uv2s._updatable = true;
  27682. }
  27683. }
  27684. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27685. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27686. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27687. serializationObject.uv3s._updatable = true;
  27688. }
  27689. }
  27690. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27691. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27692. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27693. serializationObject.uv4s._updatable = true;
  27694. }
  27695. }
  27696. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27697. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27698. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27699. serializationObject.uv5s._updatable = true;
  27700. }
  27701. }
  27702. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27703. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27704. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27705. serializationObject.uv6s._updatable = true;
  27706. }
  27707. }
  27708. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27709. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27710. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27711. serializationObject.colors._updatable = true;
  27712. }
  27713. }
  27714. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27715. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27716. serializationObject.matricesIndices._isExpanded = true;
  27717. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27718. serializationObject.matricesIndices._updatable = true;
  27719. }
  27720. }
  27721. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27722. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27723. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27724. serializationObject.matricesWeights._updatable = true;
  27725. }
  27726. }
  27727. serializationObject.indices = this.toNumberArray(this.getIndices());
  27728. return serializationObject;
  27729. };
  27730. // Statics
  27731. Geometry.ExtractFromMesh = function (mesh, id) {
  27732. var geometry = mesh._geometry;
  27733. if (!geometry) {
  27734. return null;
  27735. }
  27736. return geometry.copy(id);
  27737. };
  27738. /**
  27739. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27740. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27741. * Be aware Math.random() could cause collisions, but:
  27742. * "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"
  27743. */
  27744. Geometry.RandomId = function () {
  27745. return BABYLON.Tools.RandomId();
  27746. };
  27747. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27748. var scene = mesh.getScene();
  27749. // Geometry
  27750. var geometryId = parsedGeometry.geometryId;
  27751. if (geometryId) {
  27752. var geometry = scene.getGeometryByID(geometryId);
  27753. if (geometry) {
  27754. geometry.applyToMesh(mesh);
  27755. }
  27756. }
  27757. else if (parsedGeometry instanceof ArrayBuffer) {
  27758. var binaryInfo = mesh._binaryInfo;
  27759. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27760. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27761. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27762. }
  27763. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27764. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27765. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27766. }
  27767. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27768. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27769. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27770. }
  27771. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27772. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27773. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27774. }
  27775. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27776. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27777. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27778. }
  27779. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27780. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27781. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27782. }
  27783. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27784. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27785. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27786. }
  27787. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27788. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27789. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27790. }
  27791. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27792. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27793. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27794. }
  27795. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27796. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27797. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27798. }
  27799. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27800. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27801. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27802. }
  27803. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27804. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27805. mesh.setIndices(indicesData);
  27806. }
  27807. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27808. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27809. mesh.subMeshes = [];
  27810. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27811. var materialIndex = subMeshesData[(i * 5) + 0];
  27812. var verticesStart = subMeshesData[(i * 5) + 1];
  27813. var verticesCount = subMeshesData[(i * 5) + 2];
  27814. var indexStart = subMeshesData[(i * 5) + 3];
  27815. var indexCount = subMeshesData[(i * 5) + 4];
  27816. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27817. }
  27818. }
  27819. }
  27820. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27821. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27822. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27823. if (parsedGeometry.uvs) {
  27824. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27825. }
  27826. if (parsedGeometry.uvs2) {
  27827. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27828. }
  27829. if (parsedGeometry.uvs3) {
  27830. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27831. }
  27832. if (parsedGeometry.uvs4) {
  27833. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27834. }
  27835. if (parsedGeometry.uvs5) {
  27836. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27837. }
  27838. if (parsedGeometry.uvs6) {
  27839. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27840. }
  27841. if (parsedGeometry.colors) {
  27842. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27843. }
  27844. if (parsedGeometry.matricesIndices) {
  27845. if (!parsedGeometry.matricesIndices._isExpanded) {
  27846. var floatIndices = [];
  27847. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27848. var matricesIndex = parsedGeometry.matricesIndices[i];
  27849. floatIndices.push(matricesIndex & 0x000000FF);
  27850. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27851. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27852. floatIndices.push(matricesIndex >> 24);
  27853. }
  27854. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27855. }
  27856. else {
  27857. delete parsedGeometry.matricesIndices._isExpanded;
  27858. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27859. }
  27860. }
  27861. if (parsedGeometry.matricesIndicesExtra) {
  27862. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27863. var floatIndices = [];
  27864. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27865. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27866. floatIndices.push(matricesIndex & 0x000000FF);
  27867. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27868. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27869. floatIndices.push(matricesIndex >> 24);
  27870. }
  27871. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27872. }
  27873. else {
  27874. delete parsedGeometry.matricesIndices._isExpanded;
  27875. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27876. }
  27877. }
  27878. if (parsedGeometry.matricesWeights) {
  27879. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27880. }
  27881. if (parsedGeometry.matricesWeightsExtra) {
  27882. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27883. }
  27884. mesh.setIndices(parsedGeometry.indices);
  27885. }
  27886. // SubMeshes
  27887. if (parsedGeometry.subMeshes) {
  27888. mesh.subMeshes = [];
  27889. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27890. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27891. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27892. }
  27893. }
  27894. // Flat shading
  27895. if (mesh._shouldGenerateFlatShading) {
  27896. mesh.convertToFlatShadedMesh();
  27897. delete mesh._shouldGenerateFlatShading;
  27898. }
  27899. // Update
  27900. mesh.computeWorldMatrix(true);
  27901. // Octree
  27902. if (scene['_selectionOctree']) {
  27903. scene['_selectionOctree'].addMesh(mesh);
  27904. }
  27905. };
  27906. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27907. if (scene.getGeometryByID(parsedVertexData.id)) {
  27908. return null; // null since geometry could be something else than a box...
  27909. }
  27910. var geometry = new Geometry(parsedVertexData.id, scene);
  27911. if (BABYLON.Tags) {
  27912. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27913. }
  27914. if (parsedVertexData.delayLoadingFile) {
  27915. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27916. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27917. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27918. geometry._delayInfo = [];
  27919. if (parsedVertexData.hasUVs) {
  27920. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27921. }
  27922. if (parsedVertexData.hasUVs2) {
  27923. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27924. }
  27925. if (parsedVertexData.hasUVs3) {
  27926. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27927. }
  27928. if (parsedVertexData.hasUVs4) {
  27929. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27930. }
  27931. if (parsedVertexData.hasUVs5) {
  27932. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27933. }
  27934. if (parsedVertexData.hasUVs6) {
  27935. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27936. }
  27937. if (parsedVertexData.hasColors) {
  27938. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27939. }
  27940. if (parsedVertexData.hasMatricesIndices) {
  27941. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27942. }
  27943. if (parsedVertexData.hasMatricesWeights) {
  27944. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27945. }
  27946. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27947. }
  27948. else {
  27949. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27950. }
  27951. scene.pushGeometry(geometry, true);
  27952. return geometry;
  27953. };
  27954. return Geometry;
  27955. }());
  27956. BABYLON.Geometry = Geometry;
  27957. /////// Primitives //////////////////////////////////////////////
  27958. (function (Geometry) {
  27959. var Primitives;
  27960. (function (Primitives) {
  27961. /// Abstract class
  27962. var _Primitive = (function (_super) {
  27963. __extends(_Primitive, _super);
  27964. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27965. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27966. _this._canBeRegenerated = _canBeRegenerated;
  27967. _this._beingRegenerated = true;
  27968. _this.regenerate();
  27969. _this._beingRegenerated = false;
  27970. return _this;
  27971. }
  27972. _Primitive.prototype.canBeRegenerated = function () {
  27973. return this._canBeRegenerated;
  27974. };
  27975. _Primitive.prototype.regenerate = function () {
  27976. if (!this._canBeRegenerated) {
  27977. return;
  27978. }
  27979. this._beingRegenerated = true;
  27980. this.setAllVerticesData(this._regenerateVertexData(), false);
  27981. this._beingRegenerated = false;
  27982. };
  27983. _Primitive.prototype.asNewGeometry = function (id) {
  27984. return _super.prototype.copy.call(this, id);
  27985. };
  27986. // overrides
  27987. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27988. if (!this._beingRegenerated) {
  27989. return;
  27990. }
  27991. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27992. };
  27993. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27994. if (!this._beingRegenerated) {
  27995. return;
  27996. }
  27997. _super.prototype.setVerticesData.call(this, kind, data, false);
  27998. };
  27999. // to override
  28000. // protected
  28001. _Primitive.prototype._regenerateVertexData = function () {
  28002. throw new Error("Abstract method");
  28003. };
  28004. _Primitive.prototype.copy = function (id) {
  28005. throw new Error("Must be overriden in sub-classes.");
  28006. };
  28007. _Primitive.prototype.serialize = function () {
  28008. var serializationObject = _super.prototype.serialize.call(this);
  28009. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28010. return serializationObject;
  28011. };
  28012. return _Primitive;
  28013. }(Geometry));
  28014. Primitives._Primitive = _Primitive;
  28015. var Ribbon = (function (_super) {
  28016. __extends(Ribbon, _super);
  28017. // Members
  28018. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28019. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28020. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28021. _this.pathArray = pathArray;
  28022. _this.closeArray = closeArray;
  28023. _this.closePath = closePath;
  28024. _this.offset = offset;
  28025. _this.side = side;
  28026. return _this;
  28027. }
  28028. Ribbon.prototype._regenerateVertexData = function () {
  28029. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28030. };
  28031. Ribbon.prototype.copy = function (id) {
  28032. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28033. };
  28034. return Ribbon;
  28035. }(_Primitive));
  28036. Primitives.Ribbon = Ribbon;
  28037. var Box = (function (_super) {
  28038. __extends(Box, _super);
  28039. // Members
  28040. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28041. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28042. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28043. _this.size = size;
  28044. _this.side = side;
  28045. return _this;
  28046. }
  28047. Box.prototype._regenerateVertexData = function () {
  28048. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28049. };
  28050. Box.prototype.copy = function (id) {
  28051. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28052. };
  28053. Box.prototype.serialize = function () {
  28054. var serializationObject = _super.prototype.serialize.call(this);
  28055. serializationObject.size = this.size;
  28056. return serializationObject;
  28057. };
  28058. Box.Parse = function (parsedBox, scene) {
  28059. if (scene.getGeometryByID(parsedBox.id)) {
  28060. return null; // null since geometry could be something else than a box...
  28061. }
  28062. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28063. if (BABYLON.Tags) {
  28064. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28065. }
  28066. scene.pushGeometry(box, true);
  28067. return box;
  28068. };
  28069. return Box;
  28070. }(_Primitive));
  28071. Primitives.Box = Box;
  28072. var Sphere = (function (_super) {
  28073. __extends(Sphere, _super);
  28074. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28075. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28076. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28077. _this.segments = segments;
  28078. _this.diameter = diameter;
  28079. _this.side = side;
  28080. return _this;
  28081. }
  28082. Sphere.prototype._regenerateVertexData = function () {
  28083. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28084. };
  28085. Sphere.prototype.copy = function (id) {
  28086. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28087. };
  28088. Sphere.prototype.serialize = function () {
  28089. var serializationObject = _super.prototype.serialize.call(this);
  28090. serializationObject.segments = this.segments;
  28091. serializationObject.diameter = this.diameter;
  28092. return serializationObject;
  28093. };
  28094. Sphere.Parse = function (parsedSphere, scene) {
  28095. if (scene.getGeometryByID(parsedSphere.id)) {
  28096. return null; // null since geometry could be something else than a sphere...
  28097. }
  28098. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28099. if (BABYLON.Tags) {
  28100. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28101. }
  28102. scene.pushGeometry(sphere, true);
  28103. return sphere;
  28104. };
  28105. return Sphere;
  28106. }(_Primitive));
  28107. Primitives.Sphere = Sphere;
  28108. var Disc = (function (_super) {
  28109. __extends(Disc, _super);
  28110. // Members
  28111. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28112. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28113. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28114. _this.radius = radius;
  28115. _this.tessellation = tessellation;
  28116. _this.side = side;
  28117. return _this;
  28118. }
  28119. Disc.prototype._regenerateVertexData = function () {
  28120. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28121. };
  28122. Disc.prototype.copy = function (id) {
  28123. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28124. };
  28125. return Disc;
  28126. }(_Primitive));
  28127. Primitives.Disc = Disc;
  28128. var Cylinder = (function (_super) {
  28129. __extends(Cylinder, _super);
  28130. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28131. if (subdivisions === void 0) { subdivisions = 1; }
  28132. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28133. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28134. _this.height = height;
  28135. _this.diameterTop = diameterTop;
  28136. _this.diameterBottom = diameterBottom;
  28137. _this.tessellation = tessellation;
  28138. _this.subdivisions = subdivisions;
  28139. _this.side = side;
  28140. return _this;
  28141. }
  28142. Cylinder.prototype._regenerateVertexData = function () {
  28143. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28144. };
  28145. Cylinder.prototype.copy = function (id) {
  28146. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28147. };
  28148. Cylinder.prototype.serialize = function () {
  28149. var serializationObject = _super.prototype.serialize.call(this);
  28150. serializationObject.height = this.height;
  28151. serializationObject.diameterTop = this.diameterTop;
  28152. serializationObject.diameterBottom = this.diameterBottom;
  28153. serializationObject.tessellation = this.tessellation;
  28154. return serializationObject;
  28155. };
  28156. Cylinder.Parse = function (parsedCylinder, scene) {
  28157. if (scene.getGeometryByID(parsedCylinder.id)) {
  28158. return null; // null since geometry could be something else than a cylinder...
  28159. }
  28160. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28161. if (BABYLON.Tags) {
  28162. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28163. }
  28164. scene.pushGeometry(cylinder, true);
  28165. return cylinder;
  28166. };
  28167. return Cylinder;
  28168. }(_Primitive));
  28169. Primitives.Cylinder = Cylinder;
  28170. var Torus = (function (_super) {
  28171. __extends(Torus, _super);
  28172. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28173. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28174. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28175. _this.diameter = diameter;
  28176. _this.thickness = thickness;
  28177. _this.tessellation = tessellation;
  28178. _this.side = side;
  28179. return _this;
  28180. }
  28181. Torus.prototype._regenerateVertexData = function () {
  28182. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28183. };
  28184. Torus.prototype.copy = function (id) {
  28185. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28186. };
  28187. Torus.prototype.serialize = function () {
  28188. var serializationObject = _super.prototype.serialize.call(this);
  28189. serializationObject.diameter = this.diameter;
  28190. serializationObject.thickness = this.thickness;
  28191. serializationObject.tessellation = this.tessellation;
  28192. return serializationObject;
  28193. };
  28194. Torus.Parse = function (parsedTorus, scene) {
  28195. if (scene.getGeometryByID(parsedTorus.id)) {
  28196. return null; // null since geometry could be something else than a torus...
  28197. }
  28198. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28199. if (BABYLON.Tags) {
  28200. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28201. }
  28202. scene.pushGeometry(torus, true);
  28203. return torus;
  28204. };
  28205. return Torus;
  28206. }(_Primitive));
  28207. Primitives.Torus = Torus;
  28208. var Ground = (function (_super) {
  28209. __extends(Ground, _super);
  28210. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28211. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28212. _this.width = width;
  28213. _this.height = height;
  28214. _this.subdivisions = subdivisions;
  28215. return _this;
  28216. }
  28217. Ground.prototype._regenerateVertexData = function () {
  28218. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28219. };
  28220. Ground.prototype.copy = function (id) {
  28221. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28222. };
  28223. Ground.prototype.serialize = function () {
  28224. var serializationObject = _super.prototype.serialize.call(this);
  28225. serializationObject.width = this.width;
  28226. serializationObject.height = this.height;
  28227. serializationObject.subdivisions = this.subdivisions;
  28228. return serializationObject;
  28229. };
  28230. Ground.Parse = function (parsedGround, scene) {
  28231. if (scene.getGeometryByID(parsedGround.id)) {
  28232. return null; // null since geometry could be something else than a ground...
  28233. }
  28234. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28235. if (BABYLON.Tags) {
  28236. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28237. }
  28238. scene.pushGeometry(ground, true);
  28239. return ground;
  28240. };
  28241. return Ground;
  28242. }(_Primitive));
  28243. Primitives.Ground = Ground;
  28244. var TiledGround = (function (_super) {
  28245. __extends(TiledGround, _super);
  28246. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28247. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28248. _this.xmin = xmin;
  28249. _this.zmin = zmin;
  28250. _this.xmax = xmax;
  28251. _this.zmax = zmax;
  28252. _this.subdivisions = subdivisions;
  28253. _this.precision = precision;
  28254. return _this;
  28255. }
  28256. TiledGround.prototype._regenerateVertexData = function () {
  28257. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28258. };
  28259. TiledGround.prototype.copy = function (id) {
  28260. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28261. };
  28262. return TiledGround;
  28263. }(_Primitive));
  28264. Primitives.TiledGround = TiledGround;
  28265. var Plane = (function (_super) {
  28266. __extends(Plane, _super);
  28267. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28268. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28269. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28270. _this.size = size;
  28271. _this.side = side;
  28272. return _this;
  28273. }
  28274. Plane.prototype._regenerateVertexData = function () {
  28275. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28276. };
  28277. Plane.prototype.copy = function (id) {
  28278. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28279. };
  28280. Plane.prototype.serialize = function () {
  28281. var serializationObject = _super.prototype.serialize.call(this);
  28282. serializationObject.size = this.size;
  28283. return serializationObject;
  28284. };
  28285. Plane.Parse = function (parsedPlane, scene) {
  28286. if (scene.getGeometryByID(parsedPlane.id)) {
  28287. return null; // null since geometry could be something else than a ground...
  28288. }
  28289. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28290. if (BABYLON.Tags) {
  28291. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28292. }
  28293. scene.pushGeometry(plane, true);
  28294. return plane;
  28295. };
  28296. return Plane;
  28297. }(_Primitive));
  28298. Primitives.Plane = Plane;
  28299. var TorusKnot = (function (_super) {
  28300. __extends(TorusKnot, _super);
  28301. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28302. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28303. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28304. _this.radius = radius;
  28305. _this.tube = tube;
  28306. _this.radialSegments = radialSegments;
  28307. _this.tubularSegments = tubularSegments;
  28308. _this.p = p;
  28309. _this.q = q;
  28310. _this.side = side;
  28311. return _this;
  28312. }
  28313. TorusKnot.prototype._regenerateVertexData = function () {
  28314. 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 });
  28315. };
  28316. TorusKnot.prototype.copy = function (id) {
  28317. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28318. };
  28319. TorusKnot.prototype.serialize = function () {
  28320. var serializationObject = _super.prototype.serialize.call(this);
  28321. serializationObject.radius = this.radius;
  28322. serializationObject.tube = this.tube;
  28323. serializationObject.radialSegments = this.radialSegments;
  28324. serializationObject.tubularSegments = this.tubularSegments;
  28325. serializationObject.p = this.p;
  28326. serializationObject.q = this.q;
  28327. return serializationObject;
  28328. };
  28329. ;
  28330. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28331. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28332. return null; // null since geometry could be something else than a ground...
  28333. }
  28334. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28335. if (BABYLON.Tags) {
  28336. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28337. }
  28338. scene.pushGeometry(torusKnot, true);
  28339. return torusKnot;
  28340. };
  28341. return TorusKnot;
  28342. }(_Primitive));
  28343. Primitives.TorusKnot = TorusKnot;
  28344. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28345. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28346. })(BABYLON || (BABYLON = {}));
  28347. //# sourceMappingURL=babylon.geometry.js.map
  28348. var BABYLON;
  28349. (function (BABYLON) {
  28350. var PostProcessManager = (function () {
  28351. function PostProcessManager(scene) {
  28352. this._vertexBuffers = {};
  28353. this._scene = scene;
  28354. }
  28355. PostProcessManager.prototype._prepareBuffers = function () {
  28356. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28357. return;
  28358. }
  28359. // VBO
  28360. var vertices = [];
  28361. vertices.push(1, 1);
  28362. vertices.push(-1, 1);
  28363. vertices.push(-1, -1);
  28364. vertices.push(1, -1);
  28365. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28366. // Indices
  28367. var indices = [];
  28368. indices.push(0);
  28369. indices.push(1);
  28370. indices.push(2);
  28371. indices.push(0);
  28372. indices.push(2);
  28373. indices.push(3);
  28374. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28375. };
  28376. // Methods
  28377. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28378. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28379. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28380. return false;
  28381. }
  28382. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28383. return true;
  28384. };
  28385. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28386. var engine = this._scene.getEngine();
  28387. for (var index = 0; index < postProcesses.length; index++) {
  28388. if (index < postProcesses.length - 1) {
  28389. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28390. }
  28391. else {
  28392. if (targetTexture) {
  28393. engine.bindFramebuffer(targetTexture);
  28394. }
  28395. else {
  28396. engine.restoreDefaultFramebuffer();
  28397. }
  28398. }
  28399. var pp = postProcesses[index];
  28400. var effect = pp.apply();
  28401. if (effect) {
  28402. pp.onBeforeRenderObservable.notifyObservers(effect);
  28403. // VBOs
  28404. this._prepareBuffers();
  28405. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28406. // Draw order
  28407. engine.draw(true, 0, 6);
  28408. pp.onAfterRenderObservable.notifyObservers(effect);
  28409. }
  28410. }
  28411. // Restore depth buffer
  28412. engine.setDepthBuffer(true);
  28413. engine.setDepthWrite(true);
  28414. };
  28415. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28416. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28417. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28418. return;
  28419. }
  28420. var engine = this._scene.getEngine();
  28421. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28422. if (index < len - 1) {
  28423. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28424. }
  28425. else {
  28426. if (targetTexture) {
  28427. engine.bindFramebuffer(targetTexture, faceIndex);
  28428. }
  28429. else {
  28430. engine.restoreDefaultFramebuffer();
  28431. }
  28432. }
  28433. if (doNotPresent) {
  28434. break;
  28435. }
  28436. var pp = postProcesses[index];
  28437. var effect = pp.apply();
  28438. if (effect) {
  28439. pp.onBeforeRenderObservable.notifyObservers(effect);
  28440. // VBOs
  28441. this._prepareBuffers();
  28442. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28443. // Draw order
  28444. engine.draw(true, 0, 6);
  28445. pp.onAfterRenderObservable.notifyObservers(effect);
  28446. }
  28447. }
  28448. // Restore states
  28449. engine.setDepthBuffer(true);
  28450. engine.setDepthWrite(true);
  28451. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28452. };
  28453. PostProcessManager.prototype.dispose = function () {
  28454. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28455. if (buffer) {
  28456. buffer.dispose();
  28457. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28458. }
  28459. if (this._indexBuffer) {
  28460. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28461. this._indexBuffer = null;
  28462. }
  28463. };
  28464. return PostProcessManager;
  28465. }());
  28466. BABYLON.PostProcessManager = PostProcessManager;
  28467. })(BABYLON || (BABYLON = {}));
  28468. //# sourceMappingURL=babylon.postProcessManager.js.map
  28469. var BABYLON;
  28470. (function (BABYLON) {
  28471. var StandardMaterialDefines = (function (_super) {
  28472. __extends(StandardMaterialDefines, _super);
  28473. function StandardMaterialDefines() {
  28474. var _this = _super.call(this) || this;
  28475. _this.DIFFUSE = false;
  28476. _this.AMBIENT = false;
  28477. _this.OPACITY = false;
  28478. _this.OPACITYRGB = false;
  28479. _this.REFLECTION = false;
  28480. _this.EMISSIVE = false;
  28481. _this.SPECULAR = false;
  28482. _this.BUMP = false;
  28483. _this.PARALLAX = false;
  28484. _this.PARALLAXOCCLUSION = false;
  28485. _this.SPECULAROVERALPHA = false;
  28486. _this.CLIPPLANE = false;
  28487. _this.ALPHATEST = false;
  28488. _this.ALPHAFROMDIFFUSE = false;
  28489. _this.POINTSIZE = false;
  28490. _this.FOG = false;
  28491. _this.SPECULARTERM = false;
  28492. _this.DIFFUSEFRESNEL = false;
  28493. _this.OPACITYFRESNEL = false;
  28494. _this.REFLECTIONFRESNEL = false;
  28495. _this.REFRACTIONFRESNEL = false;
  28496. _this.EMISSIVEFRESNEL = false;
  28497. _this.FRESNEL = false;
  28498. _this.NORMAL = false;
  28499. _this.UV1 = false;
  28500. _this.UV2 = false;
  28501. _this.VERTEXCOLOR = false;
  28502. _this.VERTEXALPHA = false;
  28503. _this.NUM_BONE_INFLUENCERS = 0;
  28504. _this.BonesPerMesh = 0;
  28505. _this.INSTANCES = false;
  28506. _this.GLOSSINESS = false;
  28507. _this.ROUGHNESS = false;
  28508. _this.EMISSIVEASILLUMINATION = false;
  28509. _this.LINKEMISSIVEWITHDIFFUSE = false;
  28510. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  28511. _this.LIGHTMAP = false;
  28512. _this.USELIGHTMAPASSHADOWMAP = false;
  28513. _this.REFLECTIONMAP_3D = false;
  28514. _this.REFLECTIONMAP_SPHERICAL = false;
  28515. _this.REFLECTIONMAP_PLANAR = false;
  28516. _this.REFLECTIONMAP_CUBIC = false;
  28517. _this.REFLECTIONMAP_PROJECTION = false;
  28518. _this.REFLECTIONMAP_SKYBOX = false;
  28519. _this.REFLECTIONMAP_EXPLICIT = false;
  28520. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28521. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28522. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28523. _this.INVERTCUBICMAP = false;
  28524. _this.LOGARITHMICDEPTH = false;
  28525. _this.REFRACTION = false;
  28526. _this.REFRACTIONMAP_3D = false;
  28527. _this.REFLECTIONOVERALPHA = false;
  28528. _this.INVERTNORMALMAPX = false;
  28529. _this.INVERTNORMALMAPY = false;
  28530. _this.TWOSIDEDLIGHTING = false;
  28531. _this.SHADOWFLOAT = false;
  28532. _this.MORPHTARGETS = false;
  28533. _this.MORPHTARGETS_NORMAL = false;
  28534. _this.MORPHTARGETS_TANGENT = false;
  28535. _this.NUM_MORPH_INFLUENCERS = 0;
  28536. _this.USERIGHTHANDEDSYSTEM = false;
  28537. _this.IMAGEPROCESSING = false;
  28538. _this.VIGNETTE = false;
  28539. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  28540. _this.VIGNETTEBLENDMODEOPAQUE = false;
  28541. _this.TONEMAPPING = false;
  28542. _this.CONTRAST = false;
  28543. _this.COLORCURVES = false;
  28544. _this.COLORGRADING = false;
  28545. _this.SAMPLER3DGREENDEPTH = false;
  28546. _this.SAMPLER3DBGRMAP = false;
  28547. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  28548. _this.EXPOSURE = false;
  28549. _this.rebuild();
  28550. return _this;
  28551. }
  28552. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  28553. var modes = [
  28554. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  28555. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  28556. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  28557. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  28558. ];
  28559. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  28560. var mode = modes_1[_i];
  28561. this[mode] = (mode === modeToEnable);
  28562. }
  28563. };
  28564. return StandardMaterialDefines;
  28565. }(BABYLON.MaterialDefines));
  28566. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  28567. var StandardMaterial = (function (_super) {
  28568. __extends(StandardMaterial, _super);
  28569. function StandardMaterial(name, scene) {
  28570. var _this = _super.call(this, name, scene) || this;
  28571. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28572. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  28573. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  28574. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28575. _this.specularPower = 64;
  28576. _this._useAlphaFromDiffuseTexture = false;
  28577. _this._useEmissiveAsIllumination = false;
  28578. _this._linkEmissiveWithDiffuse = false;
  28579. _this._useSpecularOverAlpha = false;
  28580. _this._useReflectionOverAlpha = false;
  28581. _this._disableLighting = false;
  28582. _this._useParallax = false;
  28583. _this._useParallaxOcclusion = false;
  28584. _this.parallaxScaleBias = 0.05;
  28585. _this._roughness = 0;
  28586. _this.indexOfRefraction = 0.98;
  28587. _this.invertRefractionY = true;
  28588. _this._useLightmapAsShadowmap = false;
  28589. _this._useReflectionFresnelFromSpecular = false;
  28590. _this._useGlossinessFromSpecularMapAlpha = false;
  28591. _this._maxSimultaneousLights = 4;
  28592. /**
  28593. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28594. */
  28595. _this._invertNormalMapX = false;
  28596. /**
  28597. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28598. */
  28599. _this._invertNormalMapY = false;
  28600. /**
  28601. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28602. */
  28603. _this._twoSidedLighting = false;
  28604. _this._renderTargets = new BABYLON.SmartArray(16);
  28605. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28606. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28607. // Setup the default processing configuration to the scene.
  28608. _this._attachImageProcessingConfiguration(null);
  28609. _this.getRenderTargetTextures = function () {
  28610. _this._renderTargets.reset();
  28611. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  28612. _this._renderTargets.push(_this._reflectionTexture);
  28613. }
  28614. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  28615. _this._renderTargets.push(_this._refractionTexture);
  28616. }
  28617. return _this._renderTargets;
  28618. };
  28619. return _this;
  28620. }
  28621. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  28622. /**
  28623. * Gets the image processing configuration used either in this material.
  28624. */
  28625. get: function () {
  28626. return this._imageProcessingConfiguration;
  28627. },
  28628. /**
  28629. * Sets the Default image processing configuration used either in the this material.
  28630. *
  28631. * If sets to null, the scene one is in use.
  28632. */
  28633. set: function (value) {
  28634. this._attachImageProcessingConfiguration(value);
  28635. // Ensure the effect will be rebuilt.
  28636. this._markAllSubMeshesAsTexturesDirty();
  28637. },
  28638. enumerable: true,
  28639. configurable: true
  28640. });
  28641. /**
  28642. * Attaches a new image processing configuration to the Standard Material.
  28643. * @param configuration
  28644. */
  28645. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  28646. var _this = this;
  28647. if (configuration === this._imageProcessingConfiguration) {
  28648. return;
  28649. }
  28650. // Detaches observer.
  28651. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  28652. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  28653. }
  28654. // Pick the scene configuration if needed.
  28655. if (!configuration) {
  28656. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  28657. }
  28658. else {
  28659. this._imageProcessingConfiguration = configuration;
  28660. }
  28661. // Attaches observer.
  28662. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  28663. _this._markAllSubMeshesAsImageProcessingDirty();
  28664. });
  28665. };
  28666. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  28667. /**
  28668. * Gets wether the color curves effect is enabled.
  28669. */
  28670. get: function () {
  28671. return this.imageProcessingConfiguration.colorCurvesEnabled;
  28672. },
  28673. /**
  28674. * Sets wether the color curves effect is enabled.
  28675. */
  28676. set: function (value) {
  28677. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  28678. },
  28679. enumerable: true,
  28680. configurable: true
  28681. });
  28682. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  28683. /**
  28684. * Gets wether the color grading effect is enabled.
  28685. */
  28686. get: function () {
  28687. return this.imageProcessingConfiguration.colorGradingEnabled;
  28688. },
  28689. /**
  28690. * Gets wether the color grading effect is enabled.
  28691. */
  28692. set: function (value) {
  28693. this.imageProcessingConfiguration.colorGradingEnabled = value;
  28694. },
  28695. enumerable: true,
  28696. configurable: true
  28697. });
  28698. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  28699. /**
  28700. * Gets wether tonemapping is enabled or not.
  28701. */
  28702. get: function () {
  28703. return this._imageProcessingConfiguration.toneMappingEnabled;
  28704. },
  28705. /**
  28706. * Sets wether tonemapping is enabled or not
  28707. */
  28708. set: function (value) {
  28709. this._imageProcessingConfiguration.toneMappingEnabled = value;
  28710. },
  28711. enumerable: true,
  28712. configurable: true
  28713. });
  28714. ;
  28715. ;
  28716. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  28717. /**
  28718. * The camera exposure used on this material.
  28719. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28720. * This corresponds to a photographic exposure.
  28721. */
  28722. get: function () {
  28723. return this._imageProcessingConfiguration.exposure;
  28724. },
  28725. /**
  28726. * The camera exposure used on this material.
  28727. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28728. * This corresponds to a photographic exposure.
  28729. */
  28730. set: function (value) {
  28731. this._imageProcessingConfiguration.exposure = value;
  28732. },
  28733. enumerable: true,
  28734. configurable: true
  28735. });
  28736. ;
  28737. ;
  28738. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  28739. /**
  28740. * Gets The camera contrast used on this material.
  28741. */
  28742. get: function () {
  28743. return this._imageProcessingConfiguration.contrast;
  28744. },
  28745. /**
  28746. * Sets The camera contrast used on this material.
  28747. */
  28748. set: function (value) {
  28749. this._imageProcessingConfiguration.contrast = value;
  28750. },
  28751. enumerable: true,
  28752. configurable: true
  28753. });
  28754. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  28755. /**
  28756. * Gets the Color Grading 2D Lookup Texture.
  28757. */
  28758. get: function () {
  28759. return this._imageProcessingConfiguration.colorGradingTexture;
  28760. },
  28761. /**
  28762. * Sets the Color Grading 2D Lookup Texture.
  28763. */
  28764. set: function (value) {
  28765. this._imageProcessingConfiguration.colorGradingTexture = value;
  28766. },
  28767. enumerable: true,
  28768. configurable: true
  28769. });
  28770. StandardMaterial.prototype.getClassName = function () {
  28771. return "StandardMaterial";
  28772. };
  28773. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  28774. get: function () {
  28775. return this._useLogarithmicDepth;
  28776. },
  28777. set: function (value) {
  28778. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28779. this._markAllSubMeshesAsMiscDirty();
  28780. },
  28781. enumerable: true,
  28782. configurable: true
  28783. });
  28784. StandardMaterial.prototype.needAlphaBlending = function () {
  28785. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  28786. };
  28787. StandardMaterial.prototype.needAlphaTesting = function () {
  28788. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  28789. };
  28790. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  28791. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  28792. };
  28793. StandardMaterial.prototype.getAlphaTestTexture = function () {
  28794. return this._diffuseTexture;
  28795. };
  28796. /**
  28797. * Child classes can use it to update shaders
  28798. */
  28799. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28800. if (this.isFrozen) {
  28801. if (this._wasPreviouslyReady && subMesh.effect) {
  28802. return true;
  28803. }
  28804. }
  28805. if (!subMesh._materialDefines) {
  28806. subMesh._materialDefines = new StandardMaterialDefines();
  28807. }
  28808. var scene = this.getScene();
  28809. var defines = subMesh._materialDefines;
  28810. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  28811. if (defines._renderId === scene.getRenderId()) {
  28812. return true;
  28813. }
  28814. }
  28815. var engine = scene.getEngine();
  28816. // Lights
  28817. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  28818. // Textures
  28819. if (defines._areTexturesDirty) {
  28820. defines._needUVs = false;
  28821. if (scene.texturesEnabled) {
  28822. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28823. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  28824. return false;
  28825. }
  28826. else {
  28827. defines._needUVs = true;
  28828. defines.DIFFUSE = true;
  28829. }
  28830. }
  28831. else {
  28832. defines.DIFFUSE = false;
  28833. }
  28834. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28835. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  28836. return false;
  28837. }
  28838. else {
  28839. defines._needUVs = true;
  28840. defines.AMBIENT = true;
  28841. }
  28842. }
  28843. else {
  28844. defines.AMBIENT = false;
  28845. }
  28846. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28847. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  28848. return false;
  28849. }
  28850. else {
  28851. defines._needUVs = true;
  28852. defines.OPACITY = true;
  28853. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  28854. }
  28855. }
  28856. else {
  28857. defines.OPACITY = false;
  28858. }
  28859. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28860. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  28861. return false;
  28862. }
  28863. else {
  28864. defines._needNormals = true;
  28865. defines.REFLECTION = true;
  28866. defines.ROUGHNESS = (this._roughness > 0);
  28867. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  28868. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  28869. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  28870. switch (this._reflectionTexture.coordinatesMode) {
  28871. case BABYLON.Texture.CUBIC_MODE:
  28872. case BABYLON.Texture.INVCUBIC_MODE:
  28873. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  28874. break;
  28875. case BABYLON.Texture.EXPLICIT_MODE:
  28876. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  28877. break;
  28878. case BABYLON.Texture.PLANAR_MODE:
  28879. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  28880. break;
  28881. case BABYLON.Texture.PROJECTION_MODE:
  28882. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  28883. break;
  28884. case BABYLON.Texture.SKYBOX_MODE:
  28885. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  28886. break;
  28887. case BABYLON.Texture.SPHERICAL_MODE:
  28888. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  28889. break;
  28890. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28891. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  28892. break;
  28893. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28894. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  28895. break;
  28896. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28897. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  28898. break;
  28899. }
  28900. }
  28901. }
  28902. else {
  28903. defines.REFLECTION = false;
  28904. }
  28905. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28906. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  28907. return false;
  28908. }
  28909. else {
  28910. defines._needUVs = true;
  28911. defines.EMISSIVE = true;
  28912. }
  28913. }
  28914. else {
  28915. defines.EMISSIVE = false;
  28916. }
  28917. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28918. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  28919. return false;
  28920. }
  28921. else {
  28922. defines._needUVs = true;
  28923. defines.LIGHTMAP = true;
  28924. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  28925. }
  28926. }
  28927. else {
  28928. defines.LIGHTMAP = false;
  28929. }
  28930. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28931. if (!this._specularTexture.isReadyOrNotBlocking()) {
  28932. return false;
  28933. }
  28934. else {
  28935. defines._needUVs = true;
  28936. defines.SPECULAR = true;
  28937. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  28938. }
  28939. }
  28940. else {
  28941. defines.SPECULAR = false;
  28942. }
  28943. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  28944. // Bump texure can not be not blocking.
  28945. if (!this._bumpTexture.isReady()) {
  28946. return false;
  28947. }
  28948. else {
  28949. defines._needUVs = true;
  28950. defines.BUMP = true;
  28951. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  28952. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  28953. defines.PARALLAX = this._useParallax;
  28954. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  28955. }
  28956. }
  28957. else {
  28958. defines.BUMP = false;
  28959. }
  28960. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28961. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  28962. return false;
  28963. }
  28964. else {
  28965. defines._needUVs = true;
  28966. defines.REFRACTION = true;
  28967. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  28968. }
  28969. }
  28970. else {
  28971. defines.REFRACTION = false;
  28972. }
  28973. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  28974. }
  28975. else {
  28976. defines.DIFFUSE = false;
  28977. defines.AMBIENT = false;
  28978. defines.OPACITY = false;
  28979. defines.REFLECTION = false;
  28980. defines.EMISSIVE = false;
  28981. defines.LIGHTMAP = false;
  28982. defines.BUMP = false;
  28983. defines.REFRACTION = false;
  28984. }
  28985. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  28986. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  28987. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  28988. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  28989. }
  28990. if (defines._areImageProcessingDirty) {
  28991. if (!this._imageProcessingConfiguration.isReady()) {
  28992. return false;
  28993. }
  28994. this._imageProcessingConfiguration.prepareDefines(defines);
  28995. }
  28996. if (defines._areFresnelDirty) {
  28997. if (StandardMaterial.FresnelEnabled) {
  28998. // Fresnel
  28999. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  29000. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  29001. this._reflectionFresnelParameters) {
  29002. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  29003. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  29004. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  29005. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  29006. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  29007. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  29008. defines._needNormals = true;
  29009. defines.FRESNEL = true;
  29010. }
  29011. }
  29012. else {
  29013. defines.FRESNEL = false;
  29014. }
  29015. }
  29016. // Misc.
  29017. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  29018. // Attribs
  29019. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  29020. // Values that need to be evaluated on every frame
  29021. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  29022. if (scene._mirroredCameraPosition && defines.BUMP) {
  29023. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  29024. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  29025. defines.markAsUnprocessed();
  29026. }
  29027. // Get correct effect
  29028. if (defines.isDirty) {
  29029. defines.markAsProcessed();
  29030. scene.resetCachedMaterial();
  29031. // Fallbacks
  29032. var fallbacks = new BABYLON.EffectFallbacks();
  29033. if (defines.REFLECTION) {
  29034. fallbacks.addFallback(0, "REFLECTION");
  29035. }
  29036. if (defines.SPECULAR) {
  29037. fallbacks.addFallback(0, "SPECULAR");
  29038. }
  29039. if (defines.BUMP) {
  29040. fallbacks.addFallback(0, "BUMP");
  29041. }
  29042. if (defines.PARALLAX) {
  29043. fallbacks.addFallback(1, "PARALLAX");
  29044. }
  29045. if (defines.PARALLAXOCCLUSION) {
  29046. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29047. }
  29048. if (defines.SPECULAROVERALPHA) {
  29049. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29050. }
  29051. if (defines.FOG) {
  29052. fallbacks.addFallback(1, "FOG");
  29053. }
  29054. if (defines.POINTSIZE) {
  29055. fallbacks.addFallback(0, "POINTSIZE");
  29056. }
  29057. if (defines.LOGARITHMICDEPTH) {
  29058. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29059. }
  29060. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  29061. if (defines.SPECULARTERM) {
  29062. fallbacks.addFallback(0, "SPECULARTERM");
  29063. }
  29064. if (defines.DIFFUSEFRESNEL) {
  29065. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  29066. }
  29067. if (defines.OPACITYFRESNEL) {
  29068. fallbacks.addFallback(2, "OPACITYFRESNEL");
  29069. }
  29070. if (defines.REFLECTIONFRESNEL) {
  29071. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  29072. }
  29073. if (defines.EMISSIVEFRESNEL) {
  29074. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  29075. }
  29076. if (defines.FRESNEL) {
  29077. fallbacks.addFallback(4, "FRESNEL");
  29078. }
  29079. //Attributes
  29080. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29081. if (defines.NORMAL) {
  29082. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29083. }
  29084. if (defines.UV1) {
  29085. attribs.push(BABYLON.VertexBuffer.UVKind);
  29086. }
  29087. if (defines.UV2) {
  29088. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29089. }
  29090. if (defines.VERTEXCOLOR) {
  29091. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29092. }
  29093. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  29094. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  29095. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  29096. var shaderName = "default";
  29097. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  29098. "vFogInfos", "vFogColor", "pointSize",
  29099. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29100. "mBones",
  29101. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29102. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  29103. "logarithmicDepthConstant"
  29104. ];
  29105. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29106. var uniformBuffers = ["Material", "Scene"];
  29107. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  29108. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  29109. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  29110. uniformsNames: uniforms,
  29111. uniformBuffersNames: uniformBuffers,
  29112. samplers: samplers,
  29113. defines: defines,
  29114. maxSimultaneousLights: this._maxSimultaneousLights
  29115. });
  29116. if (this.customShaderNameResolve) {
  29117. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  29118. }
  29119. var join = defines.toString();
  29120. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  29121. attributes: attribs,
  29122. uniformsNames: uniforms,
  29123. uniformBuffersNames: uniformBuffers,
  29124. samplers: samplers,
  29125. defines: join,
  29126. fallbacks: fallbacks,
  29127. onCompiled: this.onCompiled,
  29128. onError: this.onError,
  29129. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  29130. }, engine), defines);
  29131. this.buildUniformLayout();
  29132. }
  29133. if (!subMesh.effect.isReady()) {
  29134. return false;
  29135. }
  29136. defines._renderId = scene.getRenderId();
  29137. this._wasPreviouslyReady = true;
  29138. return true;
  29139. };
  29140. StandardMaterial.prototype.buildUniformLayout = function () {
  29141. // Order is important !
  29142. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  29143. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  29144. this._uniformBuffer.addUniform("opacityParts", 4);
  29145. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  29146. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  29147. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  29148. this._uniformBuffer.addUniform("refractionRightColor", 4);
  29149. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  29150. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  29151. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  29152. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  29153. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  29154. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  29155. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  29156. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  29157. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  29158. this._uniformBuffer.addUniform("vBumpInfos", 3);
  29159. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  29160. this._uniformBuffer.addUniform("ambientMatrix", 16);
  29161. this._uniformBuffer.addUniform("opacityMatrix", 16);
  29162. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  29163. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  29164. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  29165. this._uniformBuffer.addUniform("specularMatrix", 16);
  29166. this._uniformBuffer.addUniform("bumpMatrix", 16);
  29167. this._uniformBuffer.addUniform("refractionMatrix", 16);
  29168. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  29169. this._uniformBuffer.addUniform("vSpecularColor", 4);
  29170. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  29171. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  29172. this._uniformBuffer.addUniform("pointSize", 1);
  29173. this._uniformBuffer.create();
  29174. };
  29175. StandardMaterial.prototype.unbind = function () {
  29176. if (this._activeEffect) {
  29177. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  29178. this._activeEffect.setTexture("reflection2DSampler", null);
  29179. }
  29180. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  29181. this._activeEffect.setTexture("refraction2DSampler", null);
  29182. }
  29183. }
  29184. _super.prototype.unbind.call(this);
  29185. };
  29186. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29187. var scene = this.getScene();
  29188. var defines = subMesh._materialDefines;
  29189. if (!defines) {
  29190. return;
  29191. }
  29192. var effect = subMesh.effect;
  29193. this._activeEffect = effect;
  29194. // Matrices
  29195. this.bindOnlyWorldMatrix(world);
  29196. // Bones
  29197. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  29198. if (this._mustRebind(scene, effect, mesh.visibility)) {
  29199. this._uniformBuffer.bindToEffect(effect, "Material");
  29200. this.bindViewProjection(effect);
  29201. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  29202. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  29203. // Fresnel
  29204. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29205. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  29206. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  29207. }
  29208. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29209. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29210. }
  29211. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29212. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  29213. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  29214. }
  29215. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29216. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  29217. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  29218. }
  29219. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29220. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29221. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29222. }
  29223. }
  29224. // Textures
  29225. if (scene.texturesEnabled) {
  29226. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29227. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  29228. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  29229. }
  29230. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29231. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  29232. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  29233. }
  29234. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29235. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  29236. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  29237. }
  29238. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29239. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  29240. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  29241. }
  29242. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29243. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  29244. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  29245. }
  29246. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29247. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  29248. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  29249. }
  29250. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29251. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  29252. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  29253. }
  29254. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29255. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  29256. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  29257. }
  29258. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29259. var depth = 1.0;
  29260. if (!this._refractionTexture.isCube) {
  29261. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  29262. if (this._refractionTexture.depth) {
  29263. depth = this._refractionTexture.depth;
  29264. }
  29265. }
  29266. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29267. }
  29268. }
  29269. // Point size
  29270. if (this.pointsCloud) {
  29271. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  29272. }
  29273. if (defines.SPECULARTERM) {
  29274. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  29275. }
  29276. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  29277. // Diffuse
  29278. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  29279. }
  29280. // Textures
  29281. if (scene.texturesEnabled) {
  29282. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29283. effect.setTexture("diffuseSampler", this._diffuseTexture);
  29284. }
  29285. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29286. effect.setTexture("ambientSampler", this._ambientTexture);
  29287. }
  29288. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29289. effect.setTexture("opacitySampler", this._opacityTexture);
  29290. }
  29291. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29292. if (this._reflectionTexture.isCube) {
  29293. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  29294. }
  29295. else {
  29296. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  29297. }
  29298. }
  29299. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29300. effect.setTexture("emissiveSampler", this._emissiveTexture);
  29301. }
  29302. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29303. effect.setTexture("lightmapSampler", this._lightmapTexture);
  29304. }
  29305. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29306. effect.setTexture("specularSampler", this._specularTexture);
  29307. }
  29308. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29309. effect.setTexture("bumpSampler", this._bumpTexture);
  29310. }
  29311. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29312. var depth = 1.0;
  29313. if (this._refractionTexture.isCube) {
  29314. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  29315. }
  29316. else {
  29317. effect.setTexture("refraction2DSampler", this._refractionTexture);
  29318. }
  29319. }
  29320. }
  29321. // Clip plane
  29322. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  29323. // Colors
  29324. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29325. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  29326. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29327. }
  29328. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  29329. // Lights
  29330. if (scene.lightsEnabled && !this._disableLighting) {
  29331. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  29332. }
  29333. // View
  29334. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  29335. this.bindView(effect);
  29336. }
  29337. // Fog
  29338. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  29339. // Morph targets
  29340. if (defines.NUM_MORPH_INFLUENCERS) {
  29341. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  29342. }
  29343. // Log. depth
  29344. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  29345. // image processing
  29346. this._imageProcessingConfiguration.bind(this._activeEffect);
  29347. }
  29348. this._uniformBuffer.update();
  29349. this._afterBind(mesh, this._activeEffect);
  29350. };
  29351. StandardMaterial.prototype.getAnimatables = function () {
  29352. var results = [];
  29353. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  29354. results.push(this._diffuseTexture);
  29355. }
  29356. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  29357. results.push(this._ambientTexture);
  29358. }
  29359. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  29360. results.push(this._opacityTexture);
  29361. }
  29362. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  29363. results.push(this._reflectionTexture);
  29364. }
  29365. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  29366. results.push(this._emissiveTexture);
  29367. }
  29368. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  29369. results.push(this._specularTexture);
  29370. }
  29371. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  29372. results.push(this._bumpTexture);
  29373. }
  29374. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  29375. results.push(this._lightmapTexture);
  29376. }
  29377. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  29378. results.push(this._refractionTexture);
  29379. }
  29380. return results;
  29381. };
  29382. StandardMaterial.prototype.getActiveTextures = function () {
  29383. var activeTextures = _super.prototype.getActiveTextures.call(this);
  29384. if (this._diffuseTexture) {
  29385. activeTextures.push(this._diffuseTexture);
  29386. }
  29387. if (this._ambientTexture) {
  29388. activeTextures.push(this._ambientTexture);
  29389. }
  29390. if (this._opacityTexture) {
  29391. activeTextures.push(this._opacityTexture);
  29392. }
  29393. if (this._reflectionTexture) {
  29394. activeTextures.push(this._reflectionTexture);
  29395. }
  29396. if (this._emissiveTexture) {
  29397. activeTextures.push(this._emissiveTexture);
  29398. }
  29399. if (this._specularTexture) {
  29400. activeTextures.push(this._specularTexture);
  29401. }
  29402. if (this._bumpTexture) {
  29403. activeTextures.push(this._bumpTexture);
  29404. }
  29405. if (this._lightmapTexture) {
  29406. activeTextures.push(this._lightmapTexture);
  29407. }
  29408. if (this._refractionTexture) {
  29409. activeTextures.push(this._refractionTexture);
  29410. }
  29411. return activeTextures;
  29412. };
  29413. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29414. if (forceDisposeTextures) {
  29415. if (this._diffuseTexture) {
  29416. this._diffuseTexture.dispose();
  29417. }
  29418. if (this._ambientTexture) {
  29419. this._ambientTexture.dispose();
  29420. }
  29421. if (this._opacityTexture) {
  29422. this._opacityTexture.dispose();
  29423. }
  29424. if (this._reflectionTexture) {
  29425. this._reflectionTexture.dispose();
  29426. }
  29427. if (this._emissiveTexture) {
  29428. this._emissiveTexture.dispose();
  29429. }
  29430. if (this._specularTexture) {
  29431. this._specularTexture.dispose();
  29432. }
  29433. if (this._bumpTexture) {
  29434. this._bumpTexture.dispose();
  29435. }
  29436. if (this._lightmapTexture) {
  29437. this._lightmapTexture.dispose();
  29438. }
  29439. if (this._refractionTexture) {
  29440. this._refractionTexture.dispose();
  29441. }
  29442. }
  29443. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  29444. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  29445. }
  29446. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29447. };
  29448. StandardMaterial.prototype.clone = function (name) {
  29449. var _this = this;
  29450. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  29451. result.name = name;
  29452. result.id = name;
  29453. return result;
  29454. };
  29455. StandardMaterial.prototype.serialize = function () {
  29456. return BABYLON.SerializationHelper.Serialize(this);
  29457. };
  29458. // Statics
  29459. StandardMaterial.Parse = function (source, scene, rootUrl) {
  29460. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  29461. };
  29462. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  29463. get: function () {
  29464. return StandardMaterial._DiffuseTextureEnabled;
  29465. },
  29466. set: function (value) {
  29467. if (StandardMaterial._DiffuseTextureEnabled === value) {
  29468. return;
  29469. }
  29470. StandardMaterial._DiffuseTextureEnabled = value;
  29471. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29472. },
  29473. enumerable: true,
  29474. configurable: true
  29475. });
  29476. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  29477. get: function () {
  29478. return StandardMaterial._AmbientTextureEnabled;
  29479. },
  29480. set: function (value) {
  29481. if (StandardMaterial._AmbientTextureEnabled === value) {
  29482. return;
  29483. }
  29484. StandardMaterial._AmbientTextureEnabled = value;
  29485. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29486. },
  29487. enumerable: true,
  29488. configurable: true
  29489. });
  29490. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  29491. get: function () {
  29492. return StandardMaterial._OpacityTextureEnabled;
  29493. },
  29494. set: function (value) {
  29495. if (StandardMaterial._OpacityTextureEnabled === value) {
  29496. return;
  29497. }
  29498. StandardMaterial._OpacityTextureEnabled = value;
  29499. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29500. },
  29501. enumerable: true,
  29502. configurable: true
  29503. });
  29504. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  29505. get: function () {
  29506. return StandardMaterial._ReflectionTextureEnabled;
  29507. },
  29508. set: function (value) {
  29509. if (StandardMaterial._ReflectionTextureEnabled === value) {
  29510. return;
  29511. }
  29512. StandardMaterial._ReflectionTextureEnabled = value;
  29513. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29514. },
  29515. enumerable: true,
  29516. configurable: true
  29517. });
  29518. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  29519. get: function () {
  29520. return StandardMaterial._EmissiveTextureEnabled;
  29521. },
  29522. set: function (value) {
  29523. if (StandardMaterial._EmissiveTextureEnabled === value) {
  29524. return;
  29525. }
  29526. StandardMaterial._EmissiveTextureEnabled = value;
  29527. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29528. },
  29529. enumerable: true,
  29530. configurable: true
  29531. });
  29532. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  29533. get: function () {
  29534. return StandardMaterial._SpecularTextureEnabled;
  29535. },
  29536. set: function (value) {
  29537. if (StandardMaterial._SpecularTextureEnabled === value) {
  29538. return;
  29539. }
  29540. StandardMaterial._SpecularTextureEnabled = value;
  29541. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29542. },
  29543. enumerable: true,
  29544. configurable: true
  29545. });
  29546. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  29547. get: function () {
  29548. return StandardMaterial._BumpTextureEnabled;
  29549. },
  29550. set: function (value) {
  29551. if (StandardMaterial._BumpTextureEnabled === value) {
  29552. return;
  29553. }
  29554. StandardMaterial._BumpTextureEnabled = value;
  29555. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29556. },
  29557. enumerable: true,
  29558. configurable: true
  29559. });
  29560. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  29561. get: function () {
  29562. return StandardMaterial._LightmapTextureEnabled;
  29563. },
  29564. set: function (value) {
  29565. if (StandardMaterial._LightmapTextureEnabled === value) {
  29566. return;
  29567. }
  29568. StandardMaterial._LightmapTextureEnabled = value;
  29569. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29570. },
  29571. enumerable: true,
  29572. configurable: true
  29573. });
  29574. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  29575. get: function () {
  29576. return StandardMaterial._RefractionTextureEnabled;
  29577. },
  29578. set: function (value) {
  29579. if (StandardMaterial._RefractionTextureEnabled === value) {
  29580. return;
  29581. }
  29582. StandardMaterial._RefractionTextureEnabled = value;
  29583. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29584. },
  29585. enumerable: true,
  29586. configurable: true
  29587. });
  29588. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  29589. get: function () {
  29590. return StandardMaterial._ColorGradingTextureEnabled;
  29591. },
  29592. set: function (value) {
  29593. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  29594. return;
  29595. }
  29596. StandardMaterial._ColorGradingTextureEnabled = value;
  29597. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29598. },
  29599. enumerable: true,
  29600. configurable: true
  29601. });
  29602. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  29603. get: function () {
  29604. return StandardMaterial._FresnelEnabled;
  29605. },
  29606. set: function (value) {
  29607. if (StandardMaterial._FresnelEnabled === value) {
  29608. return;
  29609. }
  29610. StandardMaterial._FresnelEnabled = value;
  29611. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  29612. },
  29613. enumerable: true,
  29614. configurable: true
  29615. });
  29616. return StandardMaterial;
  29617. }(BABYLON.PushMaterial));
  29618. // Flags used to enable or disable a type of texture for all Standard Materials
  29619. StandardMaterial._DiffuseTextureEnabled = true;
  29620. StandardMaterial._AmbientTextureEnabled = true;
  29621. StandardMaterial._OpacityTextureEnabled = true;
  29622. StandardMaterial._ReflectionTextureEnabled = true;
  29623. StandardMaterial._EmissiveTextureEnabled = true;
  29624. StandardMaterial._SpecularTextureEnabled = true;
  29625. StandardMaterial._BumpTextureEnabled = true;
  29626. StandardMaterial._LightmapTextureEnabled = true;
  29627. StandardMaterial._RefractionTextureEnabled = true;
  29628. StandardMaterial._ColorGradingTextureEnabled = true;
  29629. StandardMaterial._FresnelEnabled = true;
  29630. __decorate([
  29631. BABYLON.serializeAsTexture("diffuseTexture")
  29632. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  29633. __decorate([
  29634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29635. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  29636. __decorate([
  29637. BABYLON.serializeAsTexture("ambientTexture")
  29638. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  29639. __decorate([
  29640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29641. ], StandardMaterial.prototype, "ambientTexture", void 0);
  29642. __decorate([
  29643. BABYLON.serializeAsTexture("opacityTexture")
  29644. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  29645. __decorate([
  29646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29647. ], StandardMaterial.prototype, "opacityTexture", void 0);
  29648. __decorate([
  29649. BABYLON.serializeAsTexture("reflectionTexture")
  29650. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  29651. __decorate([
  29652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29653. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  29654. __decorate([
  29655. BABYLON.serializeAsTexture("emissiveTexture")
  29656. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  29657. __decorate([
  29658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29659. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  29660. __decorate([
  29661. BABYLON.serializeAsTexture("specularTexture")
  29662. ], StandardMaterial.prototype, "_specularTexture", void 0);
  29663. __decorate([
  29664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29665. ], StandardMaterial.prototype, "specularTexture", void 0);
  29666. __decorate([
  29667. BABYLON.serializeAsTexture("bumpTexture")
  29668. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  29669. __decorate([
  29670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29671. ], StandardMaterial.prototype, "bumpTexture", void 0);
  29672. __decorate([
  29673. BABYLON.serializeAsTexture("lightmapTexture")
  29674. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  29675. __decorate([
  29676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29677. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  29678. __decorate([
  29679. BABYLON.serializeAsTexture("refractionTexture")
  29680. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  29681. __decorate([
  29682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29683. ], StandardMaterial.prototype, "refractionTexture", void 0);
  29684. __decorate([
  29685. BABYLON.serializeAsColor3("ambient")
  29686. ], StandardMaterial.prototype, "ambientColor", void 0);
  29687. __decorate([
  29688. BABYLON.serializeAsColor3("diffuse")
  29689. ], StandardMaterial.prototype, "diffuseColor", void 0);
  29690. __decorate([
  29691. BABYLON.serializeAsColor3("specular")
  29692. ], StandardMaterial.prototype, "specularColor", void 0);
  29693. __decorate([
  29694. BABYLON.serializeAsColor3("emissive")
  29695. ], StandardMaterial.prototype, "emissiveColor", void 0);
  29696. __decorate([
  29697. BABYLON.serialize()
  29698. ], StandardMaterial.prototype, "specularPower", void 0);
  29699. __decorate([
  29700. BABYLON.serialize("useAlphaFromDiffuseTexture")
  29701. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  29702. __decorate([
  29703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29704. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  29705. __decorate([
  29706. BABYLON.serialize("useEmissiveAsIllumination")
  29707. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  29708. __decorate([
  29709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29710. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29711. __decorate([
  29712. BABYLON.serialize("linkEmissiveWithDiffuse")
  29713. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  29714. __decorate([
  29715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29716. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  29717. __decorate([
  29718. BABYLON.serialize("useSpecularOverAlpha")
  29719. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  29720. __decorate([
  29721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29722. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  29723. __decorate([
  29724. BABYLON.serialize("useReflectionOverAlpha")
  29725. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  29726. __decorate([
  29727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29728. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  29729. __decorate([
  29730. BABYLON.serialize("disableLighting")
  29731. ], StandardMaterial.prototype, "_disableLighting", void 0);
  29732. __decorate([
  29733. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29734. ], StandardMaterial.prototype, "disableLighting", void 0);
  29735. __decorate([
  29736. BABYLON.serialize("useParallax")
  29737. ], StandardMaterial.prototype, "_useParallax", void 0);
  29738. __decorate([
  29739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29740. ], StandardMaterial.prototype, "useParallax", void 0);
  29741. __decorate([
  29742. BABYLON.serialize("useParallaxOcclusion")
  29743. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  29744. __decorate([
  29745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29746. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  29747. __decorate([
  29748. BABYLON.serialize()
  29749. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  29750. __decorate([
  29751. BABYLON.serialize("roughness")
  29752. ], StandardMaterial.prototype, "_roughness", void 0);
  29753. __decorate([
  29754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29755. ], StandardMaterial.prototype, "roughness", void 0);
  29756. __decorate([
  29757. BABYLON.serialize()
  29758. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  29759. __decorate([
  29760. BABYLON.serialize()
  29761. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  29762. __decorate([
  29763. BABYLON.serialize("useLightmapAsShadowmap")
  29764. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  29765. __decorate([
  29766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29767. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29768. __decorate([
  29769. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  29770. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  29771. __decorate([
  29772. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29773. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  29774. __decorate([
  29775. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  29776. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  29777. __decorate([
  29778. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29779. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  29780. __decorate([
  29781. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  29782. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  29783. __decorate([
  29784. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29785. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  29786. __decorate([
  29787. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  29788. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  29789. __decorate([
  29790. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29791. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  29792. __decorate([
  29793. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  29794. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  29795. __decorate([
  29796. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29797. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  29798. __decorate([
  29799. BABYLON.serialize("useReflectionFresnelFromSpecular")
  29800. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  29801. __decorate([
  29802. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29803. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  29804. __decorate([
  29805. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  29806. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  29807. __decorate([
  29808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29809. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  29810. __decorate([
  29811. BABYLON.serialize("maxSimultaneousLights")
  29812. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  29813. __decorate([
  29814. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29815. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  29816. __decorate([
  29817. BABYLON.serialize("invertNormalMapX")
  29818. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  29819. __decorate([
  29820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29821. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  29822. __decorate([
  29823. BABYLON.serialize("invertNormalMapY")
  29824. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  29825. __decorate([
  29826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29827. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  29828. __decorate([
  29829. BABYLON.serialize("twoSidedLighting")
  29830. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  29831. __decorate([
  29832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29833. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  29834. __decorate([
  29835. BABYLON.serialize()
  29836. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  29837. BABYLON.StandardMaterial = StandardMaterial;
  29838. })(BABYLON || (BABYLON = {}));
  29839. //# sourceMappingURL=babylon.standardMaterial.js.map
  29840. var BABYLON;
  29841. (function (BABYLON) {
  29842. var PBRMaterialDefines = (function (_super) {
  29843. __extends(PBRMaterialDefines, _super);
  29844. function PBRMaterialDefines() {
  29845. var _this = _super.call(this) || this;
  29846. _this.PBR = true;
  29847. _this.ALBEDO = false;
  29848. _this.AMBIENT = false;
  29849. _this.AMBIENTINGRAYSCALE = false;
  29850. _this.OPACITY = false;
  29851. _this.OPACITYRGB = false;
  29852. _this.REFLECTION = false;
  29853. _this.EMISSIVE = false;
  29854. _this.REFLECTIVITY = false;
  29855. _this.BUMP = false;
  29856. _this.PARALLAX = false;
  29857. _this.PARALLAXOCCLUSION = false;
  29858. _this.SPECULAROVERALPHA = false;
  29859. _this.CLIPPLANE = false;
  29860. _this.ALPHATEST = false;
  29861. _this.ALPHABLEND = false;
  29862. _this.ALPHAFROMALBEDO = false;
  29863. _this.POINTSIZE = false;
  29864. _this.FOG = false;
  29865. _this.SPECULARTERM = false;
  29866. _this.NORMAL = false;
  29867. _this.TANGENT = false;
  29868. _this.UV1 = false;
  29869. _this.UV2 = false;
  29870. _this.VERTEXCOLOR = false;
  29871. _this.VERTEXALPHA = false;
  29872. _this.NUM_BONE_INFLUENCERS = 0;
  29873. _this.BonesPerMesh = 0;
  29874. _this.INSTANCES = false;
  29875. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  29876. _this.MICROSURFACEAUTOMATIC = false;
  29877. _this.LIGHTMAP = false;
  29878. _this.USELIGHTMAPASSHADOWMAP = false;
  29879. _this.REFLECTIONMAP_3D = false;
  29880. _this.REFLECTIONMAP_SPHERICAL = false;
  29881. _this.REFLECTIONMAP_PLANAR = false;
  29882. _this.REFLECTIONMAP_CUBIC = false;
  29883. _this.REFLECTIONMAP_PROJECTION = false;
  29884. _this.REFLECTIONMAP_SKYBOX = false;
  29885. _this.REFLECTIONMAP_EXPLICIT = false;
  29886. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29887. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29888. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29889. _this.INVERTCUBICMAP = false;
  29890. _this.LOGARITHMICDEPTH = false;
  29891. _this.USESPHERICALFROMREFLECTIONMAP = false;
  29892. _this.REFRACTION = false;
  29893. _this.REFRACTIONMAP_3D = false;
  29894. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  29895. _this.REFRACTIONMAPINLINEARSPACE = false;
  29896. _this.LODBASEDMICROSFURACE = false;
  29897. _this.USEPHYSICALLIGHTFALLOFF = false;
  29898. _this.RADIANCEOVERALPHA = false;
  29899. _this.USEPMREMREFLECTION = false;
  29900. _this.USEPMREMREFRACTION = false;
  29901. _this.INVERTNORMALMAPX = false;
  29902. _this.INVERTNORMALMAPY = false;
  29903. _this.TWOSIDEDLIGHTING = false;
  29904. _this.SHADOWFLOAT = false;
  29905. _this.NORMALXYSCALE = true;
  29906. _this.USERIGHTHANDEDSYSTEM = false;
  29907. _this.METALLICWORKFLOW = false;
  29908. _this.METALLICMAP = false;
  29909. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  29910. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  29911. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  29912. _this.AOSTOREINMETALMAPRED = false;
  29913. _this.MICROSURFACEMAP = false;
  29914. _this.MORPHTARGETS = false;
  29915. _this.MORPHTARGETS_NORMAL = false;
  29916. _this.MORPHTARGETS_TANGENT = false;
  29917. _this.NUM_MORPH_INFLUENCERS = 0;
  29918. _this.ALPHATESTVALUE = 0.5;
  29919. _this.PREMULTIPLYALPHA = false;
  29920. _this.ALPHAFRESNEL = false;
  29921. _this.IMAGEPROCESSING = false;
  29922. _this.VIGNETTE = false;
  29923. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  29924. _this.VIGNETTEBLENDMODEOPAQUE = false;
  29925. _this.TONEMAPPING = false;
  29926. _this.CONTRAST = false;
  29927. _this.COLORCURVES = false;
  29928. _this.COLORGRADING = false;
  29929. _this.SAMPLER3DGREENDEPTH = false;
  29930. _this.SAMPLER3DBGRMAP = false;
  29931. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  29932. _this.EXPOSURE = false;
  29933. _this.rebuild();
  29934. return _this;
  29935. }
  29936. PBRMaterialDefines.prototype.reset = function () {
  29937. _super.prototype.reset.call(this);
  29938. this.ALPHATESTVALUE = 0.5;
  29939. this.PBR = true;
  29940. };
  29941. return PBRMaterialDefines;
  29942. }(BABYLON.MaterialDefines));
  29943. /**
  29944. * The Physically based material base class of BJS.
  29945. *
  29946. * This offers the main features of a standard PBR material.
  29947. * For more information, please refer to the documentation :
  29948. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  29949. */
  29950. var PBRBaseMaterial = (function (_super) {
  29951. __extends(PBRBaseMaterial, _super);
  29952. /**
  29953. * Instantiates a new PBRMaterial instance.
  29954. *
  29955. * @param name The material name
  29956. * @param scene The scene the material will be use in.
  29957. */
  29958. function PBRBaseMaterial(name, scene) {
  29959. var _this = _super.call(this, name, scene) || this;
  29960. /**
  29961. * Intensity of the direct lights e.g. the four lights available in your scene.
  29962. * This impacts both the direct diffuse and specular highlights.
  29963. */
  29964. _this._directIntensity = 1.0;
  29965. /**
  29966. * Intensity of the emissive part of the material.
  29967. * This helps controlling the emissive effect without modifying the emissive color.
  29968. */
  29969. _this._emissiveIntensity = 1.0;
  29970. /**
  29971. * Intensity of the environment e.g. how much the environment will light the object
  29972. * either through harmonics for rough material or through the refelction for shiny ones.
  29973. */
  29974. _this._environmentIntensity = 1.0;
  29975. /**
  29976. * This is a special control allowing the reduction of the specular highlights coming from the
  29977. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  29978. */
  29979. _this._specularIntensity = 1.0;
  29980. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  29981. /**
  29982. * Debug Control allowing disabling the bump map on this material.
  29983. */
  29984. _this._disableBumpMap = false;
  29985. /**
  29986. * AKA Occlusion Texture Intensity in other nomenclature.
  29987. */
  29988. _this._ambientTextureStrength = 1.0;
  29989. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  29990. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  29991. /**
  29992. * AKA Diffuse Color in other nomenclature.
  29993. */
  29994. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  29995. /**
  29996. * AKA Specular Color in other nomenclature.
  29997. */
  29998. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  29999. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  30000. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  30001. /**
  30002. * AKA Glossiness in other nomenclature.
  30003. */
  30004. _this._microSurface = 0.9;
  30005. /**
  30006. * source material index of refraction (IOR)' / 'destination material IOR.
  30007. */
  30008. _this._indexOfRefraction = 0.66;
  30009. /**
  30010. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  30011. */
  30012. _this._invertRefractionY = false;
  30013. /**
  30014. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  30015. * Materials half opaque for instance using refraction could benefit from this control.
  30016. */
  30017. _this._linkRefractionWithTransparency = false;
  30018. _this._useLightmapAsShadowmap = false;
  30019. /**
  30020. * Specifies that the alpha is coming form the albedo channel alpha channel.
  30021. */
  30022. _this._useAlphaFromAlbedoTexture = false;
  30023. /**
  30024. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  30025. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  30026. */
  30027. _this._useSpecularOverAlpha = true;
  30028. /**
  30029. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  30030. */
  30031. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  30032. /**
  30033. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  30034. */
  30035. _this._useRoughnessFromMetallicTextureAlpha = true;
  30036. /**
  30037. * Specifies if the metallic texture contains the roughness information in its green channel.
  30038. */
  30039. _this._useRoughnessFromMetallicTextureGreen = false;
  30040. /**
  30041. * Specifies if the metallic texture contains the metallness information in its blue channel.
  30042. */
  30043. _this._useMetallnessFromMetallicTextureBlue = false;
  30044. /**
  30045. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  30046. */
  30047. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  30048. /**
  30049. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  30050. */
  30051. _this._useAmbientInGrayScale = false;
  30052. /**
  30053. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  30054. * The material will try to infer what glossiness each pixel should be.
  30055. */
  30056. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  30057. /**
  30058. * BJS is using an harcoded light falloff based on a manually sets up range.
  30059. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  30060. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  30061. */
  30062. _this._usePhysicalLightFalloff = true;
  30063. /**
  30064. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  30065. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  30066. */
  30067. _this._useRadianceOverAlpha = true;
  30068. /**
  30069. * Allows using the bump map in parallax mode.
  30070. */
  30071. _this._useParallax = false;
  30072. /**
  30073. * Allows using the bump map in parallax occlusion mode.
  30074. */
  30075. _this._useParallaxOcclusion = false;
  30076. /**
  30077. * Controls the scale bias of the parallax mode.
  30078. */
  30079. _this._parallaxScaleBias = 0.05;
  30080. /**
  30081. * If sets to true, disables all the lights affecting the material.
  30082. */
  30083. _this._disableLighting = false;
  30084. /**
  30085. * Number of Simultaneous lights allowed on the material.
  30086. */
  30087. _this._maxSimultaneousLights = 4;
  30088. /**
  30089. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30090. */
  30091. _this._invertNormalMapX = false;
  30092. /**
  30093. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30094. */
  30095. _this._invertNormalMapY = false;
  30096. /**
  30097. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30098. */
  30099. _this._twoSidedLighting = false;
  30100. /**
  30101. * Defines the alpha limits in alpha test mode.
  30102. */
  30103. _this._alphaCutOff = 0.4;
  30104. /**
  30105. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  30106. */
  30107. _this._forceAlphaTest = false;
  30108. /**
  30109. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  30110. * in your scene composition.
  30111. */
  30112. _this._premultiplyAlpha = false;
  30113. /**
  30114. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  30115. * And/Or occlude the blended part.
  30116. */
  30117. _this._useAlphaFresnel = false;
  30118. _this._renderTargets = new BABYLON.SmartArray(16);
  30119. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30120. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30121. _this._tempColor = new BABYLON.Color3();
  30122. // Setup the default processing configuration to the scene.
  30123. _this._attachImageProcessingConfiguration(null);
  30124. _this.getRenderTargetTextures = function () {
  30125. _this._renderTargets.reset();
  30126. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30127. _this._renderTargets.push(_this._reflectionTexture);
  30128. }
  30129. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30130. _this._renderTargets.push(_this._refractionTexture);
  30131. }
  30132. return _this._renderTargets;
  30133. };
  30134. return _this;
  30135. }
  30136. /**
  30137. * Attaches a new image processing configuration to the PBR Material.
  30138. * @param configuration
  30139. */
  30140. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30141. var _this = this;
  30142. if (configuration === this._imageProcessingConfiguration) {
  30143. return;
  30144. }
  30145. // Detaches observer.
  30146. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30147. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30148. }
  30149. // Pick the scene configuration if needed.
  30150. if (!configuration) {
  30151. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30152. }
  30153. else {
  30154. this._imageProcessingConfiguration = configuration;
  30155. }
  30156. // Attaches observer.
  30157. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30158. _this._markAllSubMeshesAsImageProcessingDirty();
  30159. });
  30160. };
  30161. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  30162. get: function () {
  30163. return this._useLogarithmicDepth;
  30164. },
  30165. set: function (value) {
  30166. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30167. },
  30168. enumerable: true,
  30169. configurable: true
  30170. });
  30171. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  30172. if (this._linkRefractionWithTransparency) {
  30173. return false;
  30174. }
  30175. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  30176. };
  30177. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  30178. if (this._forceAlphaTest) {
  30179. return true;
  30180. }
  30181. if (this._linkRefractionWithTransparency) {
  30182. return false;
  30183. }
  30184. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  30185. };
  30186. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30187. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  30188. };
  30189. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  30190. return this._albedoTexture;
  30191. };
  30192. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30193. if (this.isFrozen) {
  30194. if (this._wasPreviouslyReady) {
  30195. return true;
  30196. }
  30197. }
  30198. if (!subMesh._materialDefines) {
  30199. subMesh._materialDefines = new PBRMaterialDefines();
  30200. }
  30201. var scene = this.getScene();
  30202. var defines = subMesh._materialDefines;
  30203. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30204. if (defines._renderId === scene.getRenderId()) {
  30205. return true;
  30206. }
  30207. }
  30208. var engine = scene.getEngine();
  30209. // Lights
  30210. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30211. defines._needNormals = true;
  30212. // Textures
  30213. if (defines._areTexturesDirty) {
  30214. defines._needUVs = false;
  30215. if (scene.texturesEnabled) {
  30216. if (scene.getEngine().getCaps().textureLOD) {
  30217. defines.LODBASEDMICROSFURACE = true;
  30218. }
  30219. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30220. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  30221. return false;
  30222. }
  30223. defines._needUVs = true;
  30224. defines.ALBEDO = true;
  30225. }
  30226. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30227. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30228. return false;
  30229. }
  30230. defines._needUVs = true;
  30231. defines.AMBIENT = true;
  30232. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  30233. }
  30234. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30235. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30236. return false;
  30237. }
  30238. defines._needUVs = true;
  30239. defines.OPACITY = true;
  30240. if (this._opacityTexture.getAlphaFromRGB) {
  30241. defines.OPACITYRGB = true;
  30242. }
  30243. }
  30244. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  30245. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30246. if (!reflectionTexture.isReadyOrNotBlocking()) {
  30247. return false;
  30248. }
  30249. defines.REFLECTION = true;
  30250. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  30251. defines.INVERTCUBICMAP = true;
  30252. }
  30253. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  30254. switch (reflectionTexture.coordinatesMode) {
  30255. case BABYLON.Texture.CUBIC_MODE:
  30256. case BABYLON.Texture.INVCUBIC_MODE:
  30257. defines.REFLECTIONMAP_CUBIC = true;
  30258. break;
  30259. case BABYLON.Texture.EXPLICIT_MODE:
  30260. defines.REFLECTIONMAP_EXPLICIT = true;
  30261. break;
  30262. case BABYLON.Texture.PLANAR_MODE:
  30263. defines.REFLECTIONMAP_PLANAR = true;
  30264. break;
  30265. case BABYLON.Texture.PROJECTION_MODE:
  30266. defines.REFLECTIONMAP_PROJECTION = true;
  30267. break;
  30268. case BABYLON.Texture.SKYBOX_MODE:
  30269. defines.REFLECTIONMAP_SKYBOX = true;
  30270. break;
  30271. case BABYLON.Texture.SPHERICAL_MODE:
  30272. defines.REFLECTIONMAP_SPHERICAL = true;
  30273. break;
  30274. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30275. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  30276. break;
  30277. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30278. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  30279. break;
  30280. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30281. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  30282. break;
  30283. }
  30284. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  30285. defines.USESPHERICALFROMREFLECTIONMAP = true;
  30286. if (reflectionTexture.isPMREM) {
  30287. defines.USEPMREMREFLECTION = true;
  30288. }
  30289. }
  30290. }
  30291. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30292. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30293. return false;
  30294. }
  30295. defines._needUVs = true;
  30296. defines.LIGHTMAP = true;
  30297. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30298. }
  30299. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30300. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30301. return false;
  30302. }
  30303. defines._needUVs = true;
  30304. defines.EMISSIVE = true;
  30305. }
  30306. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30307. if (this._metallicTexture) {
  30308. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  30309. return false;
  30310. }
  30311. defines._needUVs = true;
  30312. defines.METALLICWORKFLOW = true;
  30313. defines.METALLICMAP = true;
  30314. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  30315. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  30316. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  30317. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  30318. }
  30319. else if (this._reflectivityTexture) {
  30320. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  30321. return false;
  30322. }
  30323. defines._needUVs = true;
  30324. defines.REFLECTIVITY = true;
  30325. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  30326. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  30327. }
  30328. if (this._microSurfaceTexture) {
  30329. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  30330. return false;
  30331. }
  30332. defines._needUVs = true;
  30333. defines.MICROSURFACEMAP = true;
  30334. }
  30335. }
  30336. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30337. // Bump texure can not be none blocking.
  30338. if (!this._bumpTexture.isReady()) {
  30339. return false;
  30340. }
  30341. defines._needUVs = true;
  30342. defines.BUMP = true;
  30343. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30344. defines.PARALLAX = true;
  30345. if (this._useParallaxOcclusion) {
  30346. defines.PARALLAXOCCLUSION = true;
  30347. }
  30348. }
  30349. if (this._invertNormalMapX) {
  30350. defines.INVERTNORMALMAPX = true;
  30351. }
  30352. if (this._invertNormalMapY) {
  30353. defines.INVERTNORMALMAPY = true;
  30354. }
  30355. if (scene._mirroredCameraPosition) {
  30356. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  30357. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  30358. }
  30359. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  30360. }
  30361. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30362. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30363. return false;
  30364. }
  30365. defines._needUVs = true;
  30366. defines.REFRACTION = true;
  30367. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30368. if (this._linkRefractionWithTransparency) {
  30369. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  30370. }
  30371. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  30372. defines.REFRACTIONMAPINLINEARSPACE = true;
  30373. if (this._refractionTexture.isPMREM) {
  30374. defines.USEPMREMREFRACTION = true;
  30375. }
  30376. }
  30377. }
  30378. if (this._shouldUseAlphaFromAlbedoTexture()) {
  30379. defines.ALPHAFROMALBEDO = true;
  30380. }
  30381. }
  30382. if (this._useSpecularOverAlpha) {
  30383. defines.SPECULAROVERALPHA = true;
  30384. }
  30385. if (this._usePhysicalLightFalloff) {
  30386. defines.USEPHYSICALLIGHTFALLOFF = true;
  30387. }
  30388. if (this._useRadianceOverAlpha) {
  30389. defines.RADIANCEOVERALPHA = true;
  30390. }
  30391. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  30392. defines.METALLICWORKFLOW = true;
  30393. }
  30394. if (!this.backFaceCulling && this._twoSidedLighting) {
  30395. defines.TWOSIDEDLIGHTING = true;
  30396. }
  30397. defines.ALPHATESTVALUE = this._alphaCutOff;
  30398. defines.PREMULTIPLYALPHA = this._premultiplyAlpha;
  30399. defines.ALPHABLEND = this.needAlphaBlending();
  30400. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  30401. }
  30402. if (defines._areImageProcessingDirty) {
  30403. if (!this._imageProcessingConfiguration.isReady()) {
  30404. return false;
  30405. }
  30406. this._imageProcessingConfiguration.prepareDefines(defines);
  30407. }
  30408. // Misc.
  30409. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  30410. // Values that need to be evaluated on every frame
  30411. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  30412. // Attribs
  30413. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  30414. if (mesh) {
  30415. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30416. mesh.createNormals(true);
  30417. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  30418. }
  30419. }
  30420. }
  30421. // Get correct effect
  30422. if (defines.isDirty) {
  30423. defines.markAsProcessed();
  30424. scene.resetCachedMaterial();
  30425. // Fallbacks
  30426. var fallbacks = new BABYLON.EffectFallbacks();
  30427. if (defines.REFLECTION) {
  30428. fallbacks.addFallback(0, "REFLECTION");
  30429. }
  30430. if (defines.REFRACTION) {
  30431. fallbacks.addFallback(0, "REFRACTION");
  30432. }
  30433. if (defines.REFLECTIVITY) {
  30434. fallbacks.addFallback(0, "REFLECTIVITY");
  30435. }
  30436. if (defines.BUMP) {
  30437. fallbacks.addFallback(0, "BUMP");
  30438. }
  30439. if (defines.PARALLAX) {
  30440. fallbacks.addFallback(1, "PARALLAX");
  30441. }
  30442. if (defines.PARALLAXOCCLUSION) {
  30443. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30444. }
  30445. if (defines.SPECULAROVERALPHA) {
  30446. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30447. }
  30448. if (defines.FOG) {
  30449. fallbacks.addFallback(1, "FOG");
  30450. }
  30451. if (defines.POINTSIZE) {
  30452. fallbacks.addFallback(0, "POINTSIZE");
  30453. }
  30454. if (defines.LOGARITHMICDEPTH) {
  30455. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30456. }
  30457. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  30458. if (defines.SPECULARTERM) {
  30459. fallbacks.addFallback(0, "SPECULARTERM");
  30460. }
  30461. if (defines.NUM_BONE_INFLUENCERS > 0) {
  30462. fallbacks.addCPUSkinningFallback(0, mesh);
  30463. }
  30464. //Attributes
  30465. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30466. if (defines.NORMAL) {
  30467. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30468. }
  30469. if (defines.TANGENT) {
  30470. attribs.push(BABYLON.VertexBuffer.TangentKind);
  30471. }
  30472. if (defines.UV1) {
  30473. attribs.push(BABYLON.VertexBuffer.UVKind);
  30474. }
  30475. if (defines.UV2) {
  30476. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30477. }
  30478. if (defines.VERTEXCOLOR) {
  30479. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30480. }
  30481. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  30482. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  30483. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  30484. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  30485. "vFogInfos", "vFogColor", "pointSize",
  30486. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30487. "mBones",
  30488. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30489. "vLightingIntensity",
  30490. "logarithmicDepthConstant",
  30491. "vSphericalX", "vSphericalY", "vSphericalZ",
  30492. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  30493. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  30494. "vMicrosurfaceTextureLods"
  30495. ];
  30496. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30497. var uniformBuffers = ["Material", "Scene"];
  30498. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  30499. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  30500. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30501. uniformsNames: uniforms,
  30502. uniformBuffersNames: uniformBuffers,
  30503. samplers: samplers,
  30504. defines: defines,
  30505. maxSimultaneousLights: this._maxSimultaneousLights
  30506. });
  30507. var onCompiled = function (effect) {
  30508. if (this.onCompiled) {
  30509. this.onCompiled(effect);
  30510. }
  30511. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  30512. }.bind(this);
  30513. var join = defines.toString();
  30514. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  30515. attributes: attribs,
  30516. uniformsNames: uniforms,
  30517. uniformBuffersNames: uniformBuffers,
  30518. samplers: samplers,
  30519. defines: join,
  30520. fallbacks: fallbacks,
  30521. onCompiled: onCompiled,
  30522. onError: this.onError,
  30523. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  30524. }, engine), defines);
  30525. this.buildUniformLayout();
  30526. }
  30527. if (!subMesh.effect.isReady()) {
  30528. return false;
  30529. }
  30530. defines._renderId = scene.getRenderId();
  30531. this._wasPreviouslyReady = true;
  30532. return true;
  30533. };
  30534. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  30535. // Order is important !
  30536. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  30537. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  30538. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30539. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30540. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30541. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  30542. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  30543. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30544. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30545. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30546. this._uniformBuffer.addUniform("albedoMatrix", 16);
  30547. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30548. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30549. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30550. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30551. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  30552. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  30553. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30554. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30555. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30556. this._uniformBuffer.addUniform("vReflectionColor", 3);
  30557. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  30558. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  30559. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  30560. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  30561. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30562. this._uniformBuffer.addUniform("pointSize", 1);
  30563. this._uniformBuffer.create();
  30564. };
  30565. PBRBaseMaterial.prototype.unbind = function () {
  30566. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30567. this._uniformBuffer.setTexture("reflection2DSampler", null);
  30568. }
  30569. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30570. this._uniformBuffer.setTexture("refraction2DSampler", null);
  30571. }
  30572. _super.prototype.unbind.call(this);
  30573. };
  30574. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30575. this._activeEffect.setMatrix("world", world);
  30576. };
  30577. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30578. var scene = this.getScene();
  30579. var defines = subMesh._materialDefines;
  30580. if (!defines) {
  30581. return;
  30582. }
  30583. var effect = subMesh.effect;
  30584. this._activeEffect = effect;
  30585. // Matrices
  30586. this.bindOnlyWorldMatrix(world);
  30587. // Bones
  30588. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  30589. if (this._mustRebind(scene, effect, mesh.visibility)) {
  30590. this._uniformBuffer.bindToEffect(effect, "Material");
  30591. this.bindViewProjection(effect);
  30592. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30593. // Texture uniforms
  30594. if (scene.texturesEnabled) {
  30595. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30596. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  30597. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  30598. }
  30599. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30600. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  30601. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  30602. }
  30603. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30604. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30605. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  30606. }
  30607. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  30608. ;
  30609. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30610. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  30611. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  30612. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  30613. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  30614. this._activeEffect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  30615. this._activeEffect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  30616. this._activeEffect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  30617. this._activeEffect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  30618. this._activeEffect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  30619. this._activeEffect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  30620. this._activeEffect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  30621. this._activeEffect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  30622. this._activeEffect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  30623. }
  30624. }
  30625. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30626. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30627. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  30628. }
  30629. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30630. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30631. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  30632. }
  30633. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30634. if (this._metallicTexture) {
  30635. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  30636. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  30637. }
  30638. else if (this._reflectivityTexture) {
  30639. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  30640. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  30641. }
  30642. if (this._microSurfaceTexture) {
  30643. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  30644. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  30645. }
  30646. }
  30647. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30648. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  30649. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  30650. }
  30651. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30652. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  30653. var depth = 1.0;
  30654. if (!this._refractionTexture.isCube) {
  30655. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30656. if (this._refractionTexture.depth) {
  30657. depth = this._refractionTexture.depth;
  30658. }
  30659. }
  30660. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  30661. }
  30662. if ((reflectionTexture || this._refractionTexture)) {
  30663. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  30664. }
  30665. }
  30666. // Point size
  30667. if (this.pointsCloud) {
  30668. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30669. }
  30670. // Colors
  30671. if (defines.METALLICWORKFLOW) {
  30672. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  30673. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  30674. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  30675. }
  30676. else {
  30677. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  30678. }
  30679. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  30680. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  30681. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  30682. // Misc
  30683. this._lightingInfos.x = this._directIntensity;
  30684. this._lightingInfos.y = this._emissiveIntensity;
  30685. this._lightingInfos.z = this._environmentIntensity;
  30686. this._lightingInfos.w = this._specularIntensity;
  30687. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  30688. }
  30689. // Textures
  30690. if (scene.texturesEnabled) {
  30691. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30692. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  30693. }
  30694. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30695. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  30696. }
  30697. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30698. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  30699. }
  30700. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30701. if (reflectionTexture.isCube) {
  30702. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  30703. }
  30704. else {
  30705. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  30706. }
  30707. }
  30708. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30709. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  30710. }
  30711. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30712. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  30713. }
  30714. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30715. if (this._metallicTexture) {
  30716. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  30717. }
  30718. else if (this._reflectivityTexture) {
  30719. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  30720. }
  30721. if (this._microSurfaceTexture) {
  30722. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  30723. }
  30724. }
  30725. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30726. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  30727. }
  30728. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30729. if (this._refractionTexture.isCube) {
  30730. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  30731. }
  30732. else {
  30733. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  30734. }
  30735. }
  30736. }
  30737. // Clip plane
  30738. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  30739. // Colors
  30740. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  30741. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  30742. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30743. }
  30744. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  30745. // Lights
  30746. if (scene.lightsEnabled && !this._disableLighting) {
  30747. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  30748. }
  30749. // View
  30750. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  30751. this.bindView(effect);
  30752. }
  30753. // Fog
  30754. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  30755. // Morph targets
  30756. if (defines.NUM_MORPH_INFLUENCERS) {
  30757. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  30758. }
  30759. // image processing
  30760. this._imageProcessingConfiguration.bind(this._activeEffect);
  30761. // Log. depth
  30762. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  30763. }
  30764. this._uniformBuffer.update();
  30765. this._afterBind(mesh);
  30766. scene = null;
  30767. };
  30768. PBRBaseMaterial.prototype.getAnimatables = function () {
  30769. var results = [];
  30770. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  30771. results.push(this._albedoTexture);
  30772. }
  30773. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30774. results.push(this._ambientTexture);
  30775. }
  30776. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30777. results.push(this._opacityTexture);
  30778. }
  30779. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30780. results.push(this._reflectionTexture);
  30781. }
  30782. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30783. results.push(this._emissiveTexture);
  30784. }
  30785. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  30786. results.push(this._metallicTexture);
  30787. }
  30788. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  30789. results.push(this._reflectivityTexture);
  30790. }
  30791. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30792. results.push(this._bumpTexture);
  30793. }
  30794. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30795. results.push(this._lightmapTexture);
  30796. }
  30797. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30798. results.push(this._refractionTexture);
  30799. }
  30800. return results;
  30801. };
  30802. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30803. if (forceDisposeTextures) {
  30804. if (this._albedoTexture) {
  30805. this._albedoTexture.dispose();
  30806. }
  30807. if (this._ambientTexture) {
  30808. this._ambientTexture.dispose();
  30809. }
  30810. if (this._opacityTexture) {
  30811. this._opacityTexture.dispose();
  30812. }
  30813. if (this._reflectionTexture) {
  30814. this._reflectionTexture.dispose();
  30815. }
  30816. if (this._emissiveTexture) {
  30817. this._emissiveTexture.dispose();
  30818. }
  30819. if (this._metallicTexture) {
  30820. this._metallicTexture.dispose();
  30821. }
  30822. if (this._reflectivityTexture) {
  30823. this._reflectivityTexture.dispose();
  30824. }
  30825. if (this._bumpTexture) {
  30826. this._bumpTexture.dispose();
  30827. }
  30828. if (this._lightmapTexture) {
  30829. this._lightmapTexture.dispose();
  30830. }
  30831. if (this._refractionTexture) {
  30832. this._refractionTexture.dispose();
  30833. }
  30834. }
  30835. this._renderTargets.dispose();
  30836. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30837. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30838. }
  30839. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30840. };
  30841. return PBRBaseMaterial;
  30842. }(BABYLON.PushMaterial));
  30843. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  30844. __decorate([
  30845. BABYLON.serializeAsImageProcessingConfiguration()
  30846. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  30847. __decorate([
  30848. BABYLON.serialize()
  30849. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  30850. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  30851. })(BABYLON || (BABYLON = {}));
  30852. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  30853. var BABYLON;
  30854. (function (BABYLON) {
  30855. var Internals;
  30856. (function (Internals) {
  30857. /**
  30858. * The Physically based simple base material of BJS.
  30859. *
  30860. * This enables better naming and convention enforcements on top of the pbrMaterial.
  30861. * It is used as the base class for both the specGloss and metalRough conventions.
  30862. */
  30863. var PBRBaseSimpleMaterial = (function (_super) {
  30864. __extends(PBRBaseSimpleMaterial, _super);
  30865. /**
  30866. * Instantiates a new PBRMaterial instance.
  30867. *
  30868. * @param name The material name
  30869. * @param scene The scene the material will be use in.
  30870. */
  30871. function PBRBaseSimpleMaterial(name, scene) {
  30872. var _this = _super.call(this, name, scene) || this;
  30873. /**
  30874. * Number of Simultaneous lights allowed on the material.
  30875. */
  30876. _this.maxSimultaneousLights = 4;
  30877. /**
  30878. * If sets to true, disables all the lights affecting the material.
  30879. */
  30880. _this.disableLighting = false;
  30881. /**
  30882. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30883. */
  30884. _this.invertNormalMapX = false;
  30885. /**
  30886. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30887. */
  30888. _this.invertNormalMapY = false;
  30889. /**
  30890. * Emissivie color used to self-illuminate the model.
  30891. */
  30892. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30893. /**
  30894. * Occlusion Channel Strenght.
  30895. */
  30896. _this.occlusionStrength = 1.0;
  30897. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30898. _this._useAmbientInGrayScale = true;
  30899. return _this;
  30900. }
  30901. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  30902. /**
  30903. * Gets the current transparency mode.
  30904. */
  30905. get: function () {
  30906. return this._transparencyMode;
  30907. },
  30908. /**
  30909. * Sets the transparency mode of the material.
  30910. */
  30911. set: function (value) {
  30912. if (this._transparencyMode === value) {
  30913. return;
  30914. }
  30915. this._transparencyMode = value;
  30916. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  30917. this._forceAlphaTest = true;
  30918. }
  30919. else {
  30920. this._forceAlphaTest = false;
  30921. }
  30922. this._markAllSubMeshesAsTexturesDirty();
  30923. },
  30924. enumerable: true,
  30925. configurable: true
  30926. });
  30927. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  30928. /**
  30929. * Gets the current double sided mode.
  30930. */
  30931. get: function () {
  30932. return this._twoSidedLighting;
  30933. },
  30934. /**
  30935. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30936. */
  30937. set: function (value) {
  30938. if (this._twoSidedLighting === value) {
  30939. return;
  30940. }
  30941. this._twoSidedLighting = value;
  30942. this.backFaceCulling = !value;
  30943. this._markAllSubMeshesAsTexturesDirty();
  30944. },
  30945. enumerable: true,
  30946. configurable: true
  30947. });
  30948. /**
  30949. * Specifies wether or not the alpha value of the albedo texture should be used.
  30950. */
  30951. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30952. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30953. };
  30954. /**
  30955. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  30956. */
  30957. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  30958. if (this._linkRefractionWithTransparency) {
  30959. return false;
  30960. }
  30961. return (this.alpha < 1.0) ||
  30962. (this._shouldUseAlphaFromAlbedoTexture() &&
  30963. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  30964. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  30965. };
  30966. /**
  30967. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  30968. */
  30969. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  30970. if (this._linkRefractionWithTransparency) {
  30971. return false;
  30972. }
  30973. return this._shouldUseAlphaFromAlbedoTexture() &&
  30974. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  30975. };
  30976. return PBRBaseSimpleMaterial;
  30977. }(BABYLON.PBRBaseMaterial));
  30978. __decorate([
  30979. BABYLON.serialize(),
  30980. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30981. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  30982. __decorate([
  30983. BABYLON.serialize(),
  30984. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30985. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  30986. __decorate([
  30987. BABYLON.serializeAsTexture(),
  30988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  30989. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  30990. __decorate([
  30991. BABYLON.serialize(),
  30992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30993. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  30994. __decorate([
  30995. BABYLON.serialize(),
  30996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30997. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  30998. __decorate([
  30999. BABYLON.serializeAsTexture(),
  31000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  31001. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  31002. __decorate([
  31003. BABYLON.serializeAsColor3("emissive"),
  31004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31005. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  31006. __decorate([
  31007. BABYLON.serializeAsTexture(),
  31008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31009. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  31010. __decorate([
  31011. BABYLON.serialize(),
  31012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  31013. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  31014. __decorate([
  31015. BABYLON.serializeAsTexture(),
  31016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  31017. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  31018. __decorate([
  31019. BABYLON.serialize(),
  31020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  31021. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  31022. __decorate([
  31023. BABYLON.serialize()
  31024. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  31025. __decorate([
  31026. BABYLON.serialize()
  31027. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  31028. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  31029. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31030. })(BABYLON || (BABYLON = {}));
  31031. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  31032. var BABYLON;
  31033. (function (BABYLON) {
  31034. /**
  31035. * The Physically based material of BJS.
  31036. *
  31037. * This offers the main features of a standard PBR material.
  31038. * For more information, please refer to the documentation :
  31039. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31040. */
  31041. var PBRMaterial = (function (_super) {
  31042. __extends(PBRMaterial, _super);
  31043. /**
  31044. * Instantiates a new PBRMaterial instance.
  31045. *
  31046. * @param name The material name
  31047. * @param scene The scene the material will be use in.
  31048. */
  31049. function PBRMaterial(name, scene) {
  31050. var _this = _super.call(this, name, scene) || this;
  31051. /**
  31052. * Intensity of the direct lights e.g. the four lights available in your scene.
  31053. * This impacts both the direct diffuse and specular highlights.
  31054. */
  31055. _this.directIntensity = 1.0;
  31056. /**
  31057. * Intensity of the emissive part of the material.
  31058. * This helps controlling the emissive effect without modifying the emissive color.
  31059. */
  31060. _this.emissiveIntensity = 1.0;
  31061. /**
  31062. * Intensity of the environment e.g. how much the environment will light the object
  31063. * either through harmonics for rough material or through the refelction for shiny ones.
  31064. */
  31065. _this.environmentIntensity = 1.0;
  31066. /**
  31067. * This is a special control allowing the reduction of the specular highlights coming from the
  31068. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31069. */
  31070. _this.specularIntensity = 1.0;
  31071. /**
  31072. * Debug Control allowing disabling the bump map on this material.
  31073. */
  31074. _this.disableBumpMap = false;
  31075. /**
  31076. * AKA Occlusion Texture Intensity in other nomenclature.
  31077. */
  31078. _this.ambientTextureStrength = 1.0;
  31079. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  31080. /**
  31081. * AKA Diffuse Color in other nomenclature.
  31082. */
  31083. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  31084. /**
  31085. * AKA Specular Color in other nomenclature.
  31086. */
  31087. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31088. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  31089. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  31090. /**
  31091. * AKA Glossiness in other nomenclature.
  31092. */
  31093. _this.microSurface = 0.9;
  31094. /**
  31095. * source material index of refraction (IOR)' / 'destination material IOR.
  31096. */
  31097. _this.indexOfRefraction = 0.66;
  31098. /**
  31099. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31100. */
  31101. _this.invertRefractionY = false;
  31102. /**
  31103. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31104. * Materials half opaque for instance using refraction could benefit from this control.
  31105. */
  31106. _this.linkRefractionWithTransparency = false;
  31107. _this.useLightmapAsShadowmap = false;
  31108. /**
  31109. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31110. */
  31111. _this.useAlphaFromAlbedoTexture = false;
  31112. /**
  31113. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31114. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31115. */
  31116. _this.useSpecularOverAlpha = true;
  31117. /**
  31118. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31119. */
  31120. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  31121. /**
  31122. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31123. */
  31124. _this.useRoughnessFromMetallicTextureAlpha = true;
  31125. /**
  31126. * Specifies if the metallic texture contains the roughness information in its green channel.
  31127. */
  31128. _this.useRoughnessFromMetallicTextureGreen = false;
  31129. /**
  31130. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31131. */
  31132. _this.useMetallnessFromMetallicTextureBlue = false;
  31133. /**
  31134. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31135. */
  31136. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  31137. /**
  31138. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31139. */
  31140. _this.useAmbientInGrayScale = false;
  31141. /**
  31142. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31143. * The material will try to infer what glossiness each pixel should be.
  31144. */
  31145. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  31146. /**
  31147. * BJS is using an harcoded light falloff based on a manually sets up range.
  31148. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  31149. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  31150. */
  31151. _this.usePhysicalLightFalloff = true;
  31152. /**
  31153. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  31154. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  31155. */
  31156. _this.useRadianceOverAlpha = true;
  31157. /**
  31158. * Allows using the bump map in parallax mode.
  31159. */
  31160. _this.useParallax = false;
  31161. /**
  31162. * Allows using the bump map in parallax occlusion mode.
  31163. */
  31164. _this.useParallaxOcclusion = false;
  31165. /**
  31166. * Controls the scale bias of the parallax mode.
  31167. */
  31168. _this.parallaxScaleBias = 0.05;
  31169. /**
  31170. * If sets to true, disables all the lights affecting the material.
  31171. */
  31172. _this.disableLighting = false;
  31173. /**
  31174. * Number of Simultaneous lights allowed on the material.
  31175. */
  31176. _this.maxSimultaneousLights = 4;
  31177. /**
  31178. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  31179. */
  31180. _this.invertNormalMapX = false;
  31181. /**
  31182. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  31183. */
  31184. _this.invertNormalMapY = false;
  31185. /**
  31186. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31187. */
  31188. _this.twoSidedLighting = false;
  31189. /**
  31190. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  31191. * in your scene composition.
  31192. */
  31193. _this.premultiplyAlpha = false;
  31194. /**
  31195. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31196. * And/Or occlude the blended part.
  31197. */
  31198. _this.useAlphaFresnel = false;
  31199. return _this;
  31200. }
  31201. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  31202. /**
  31203. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  31204. */
  31205. get: function () {
  31206. return this._PBRMATERIAL_OPAQUE;
  31207. },
  31208. enumerable: true,
  31209. configurable: true
  31210. });
  31211. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  31212. /**
  31213. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  31214. */
  31215. get: function () {
  31216. return this._PBRMATERIAL_ALPHATEST;
  31217. },
  31218. enumerable: true,
  31219. configurable: true
  31220. });
  31221. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  31222. /**
  31223. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  31224. */
  31225. get: function () {
  31226. return this._PBRMATERIAL_ALPHABLEND;
  31227. },
  31228. enumerable: true,
  31229. configurable: true
  31230. });
  31231. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  31232. /**
  31233. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  31234. * They are also discarded below the alpha cutoff threshold to improve performances.
  31235. */
  31236. get: function () {
  31237. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  31238. },
  31239. enumerable: true,
  31240. configurable: true
  31241. });
  31242. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  31243. /**
  31244. * Gets the image processing configuration used either in this material.
  31245. */
  31246. get: function () {
  31247. return this._imageProcessingConfiguration;
  31248. },
  31249. /**
  31250. * Sets the Default image processing configuration used either in the this material.
  31251. *
  31252. * If sets to null, the scene one is in use.
  31253. */
  31254. set: function (value) {
  31255. this._attachImageProcessingConfiguration(value);
  31256. // Ensure the effect will be rebuilt.
  31257. this._markAllSubMeshesAsTexturesDirty();
  31258. },
  31259. enumerable: true,
  31260. configurable: true
  31261. });
  31262. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  31263. /**
  31264. * Gets wether the color curves effect is enabled.
  31265. */
  31266. get: function () {
  31267. return this.imageProcessingConfiguration.colorCurvesEnabled;
  31268. },
  31269. /**
  31270. * Sets wether the color curves effect is enabled.
  31271. */
  31272. set: function (value) {
  31273. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  31274. },
  31275. enumerable: true,
  31276. configurable: true
  31277. });
  31278. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  31279. /**
  31280. * Gets wether the color grading effect is enabled.
  31281. */
  31282. get: function () {
  31283. return this.imageProcessingConfiguration.colorGradingEnabled;
  31284. },
  31285. /**
  31286. * Gets wether the color grading effect is enabled.
  31287. */
  31288. set: function (value) {
  31289. this.imageProcessingConfiguration.colorGradingEnabled = value;
  31290. },
  31291. enumerable: true,
  31292. configurable: true
  31293. });
  31294. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  31295. /**
  31296. * Gets wether tonemapping is enabled or not.
  31297. */
  31298. get: function () {
  31299. return this._imageProcessingConfiguration.toneMappingEnabled;
  31300. },
  31301. /**
  31302. * Sets wether tonemapping is enabled or not
  31303. */
  31304. set: function (value) {
  31305. this._imageProcessingConfiguration.toneMappingEnabled = value;
  31306. },
  31307. enumerable: true,
  31308. configurable: true
  31309. });
  31310. ;
  31311. ;
  31312. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  31313. /**
  31314. * The camera exposure used on this material.
  31315. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  31316. * This corresponds to a photographic exposure.
  31317. */
  31318. get: function () {
  31319. return this._imageProcessingConfiguration.exposure;
  31320. },
  31321. /**
  31322. * The camera exposure used on this material.
  31323. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  31324. * This corresponds to a photographic exposure.
  31325. */
  31326. set: function (value) {
  31327. this._imageProcessingConfiguration.exposure = value;
  31328. },
  31329. enumerable: true,
  31330. configurable: true
  31331. });
  31332. ;
  31333. ;
  31334. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  31335. /**
  31336. * Gets The camera contrast used on this material.
  31337. */
  31338. get: function () {
  31339. return this._imageProcessingConfiguration.contrast;
  31340. },
  31341. /**
  31342. * Sets The camera contrast used on this material.
  31343. */
  31344. set: function (value) {
  31345. this._imageProcessingConfiguration.contrast = value;
  31346. },
  31347. enumerable: true,
  31348. configurable: true
  31349. });
  31350. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  31351. /**
  31352. * Gets the Color Grading 2D Lookup Texture.
  31353. */
  31354. get: function () {
  31355. return this._imageProcessingConfiguration.colorGradingTexture;
  31356. },
  31357. /**
  31358. * Sets the Color Grading 2D Lookup Texture.
  31359. */
  31360. set: function (value) {
  31361. this._imageProcessingConfiguration.colorGradingTexture = value;
  31362. },
  31363. enumerable: true,
  31364. configurable: true
  31365. });
  31366. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  31367. /**
  31368. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  31369. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  31370. * 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;
  31371. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  31372. */
  31373. get: function () {
  31374. return this._imageProcessingConfiguration.colorCurves;
  31375. },
  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. set: function (value) {
  31383. this._imageProcessingConfiguration.colorCurves = value;
  31384. },
  31385. enumerable: true,
  31386. configurable: true
  31387. });
  31388. PBRMaterial.prototype.getClassName = function () {
  31389. return "PBRMaterial";
  31390. };
  31391. PBRMaterial.prototype.getActiveTextures = function () {
  31392. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31393. if (this._albedoTexture) {
  31394. activeTextures.push(this._albedoTexture);
  31395. }
  31396. if (this._ambientTexture) {
  31397. activeTextures.push(this._ambientTexture);
  31398. }
  31399. if (this._opacityTexture) {
  31400. activeTextures.push(this._opacityTexture);
  31401. }
  31402. if (this._reflectionTexture) {
  31403. activeTextures.push(this._reflectionTexture);
  31404. }
  31405. if (this._emissiveTexture) {
  31406. activeTextures.push(this._emissiveTexture);
  31407. }
  31408. if (this._reflectionTexture) {
  31409. activeTextures.push(this._reflectionTexture);
  31410. }
  31411. if (this._metallicTexture) {
  31412. activeTextures.push(this._metallicTexture);
  31413. }
  31414. if (this._microSurfaceTexture) {
  31415. activeTextures.push(this._microSurfaceTexture);
  31416. }
  31417. if (this._bumpTexture) {
  31418. activeTextures.push(this._bumpTexture);
  31419. }
  31420. if (this._lightmapTexture) {
  31421. activeTextures.push(this._lightmapTexture);
  31422. }
  31423. if (this._refractionTexture) {
  31424. activeTextures.push(this._refractionTexture);
  31425. }
  31426. return activeTextures;
  31427. };
  31428. PBRMaterial.prototype.clone = function (name) {
  31429. var _this = this;
  31430. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  31431. };
  31432. PBRMaterial.prototype.serialize = function () {
  31433. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31434. serializationObject.customType = "BABYLON.PBRMaterial";
  31435. return serializationObject;
  31436. };
  31437. // Statics
  31438. PBRMaterial.Parse = function (source, scene, rootUrl) {
  31439. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  31440. };
  31441. return PBRMaterial;
  31442. }(BABYLON.PBRBaseMaterial));
  31443. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  31444. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  31445. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  31446. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  31447. __decorate([
  31448. BABYLON.serialize(),
  31449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31450. ], PBRMaterial.prototype, "directIntensity", void 0);
  31451. __decorate([
  31452. BABYLON.serialize(),
  31453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31454. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  31455. __decorate([
  31456. BABYLON.serialize(),
  31457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31458. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  31459. __decorate([
  31460. BABYLON.serialize(),
  31461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31462. ], PBRMaterial.prototype, "specularIntensity", void 0);
  31463. __decorate([
  31464. BABYLON.serialize(),
  31465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31466. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  31467. __decorate([
  31468. BABYLON.serializeAsTexture(),
  31469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31470. ], PBRMaterial.prototype, "albedoTexture", void 0);
  31471. __decorate([
  31472. BABYLON.serializeAsTexture(),
  31473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31474. ], PBRMaterial.prototype, "ambientTexture", void 0);
  31475. __decorate([
  31476. BABYLON.serialize(),
  31477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31478. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  31479. __decorate([
  31480. BABYLON.serializeAsTexture(),
  31481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31482. ], PBRMaterial.prototype, "opacityTexture", void 0);
  31483. __decorate([
  31484. BABYLON.serializeAsTexture(),
  31485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31486. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  31487. __decorate([
  31488. BABYLON.serializeAsTexture(),
  31489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31490. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  31491. __decorate([
  31492. BABYLON.serializeAsTexture(),
  31493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31494. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  31495. __decorate([
  31496. BABYLON.serializeAsTexture(),
  31497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31498. ], PBRMaterial.prototype, "metallicTexture", void 0);
  31499. __decorate([
  31500. BABYLON.serialize(),
  31501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31502. ], PBRMaterial.prototype, "metallic", void 0);
  31503. __decorate([
  31504. BABYLON.serialize(),
  31505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31506. ], PBRMaterial.prototype, "roughness", void 0);
  31507. __decorate([
  31508. BABYLON.serializeAsTexture(),
  31509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31510. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  31511. __decorate([
  31512. BABYLON.serializeAsTexture(),
  31513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31514. ], PBRMaterial.prototype, "bumpTexture", void 0);
  31515. __decorate([
  31516. BABYLON.serializeAsTexture(),
  31517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  31518. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  31519. __decorate([
  31520. BABYLON.serializeAsTexture(),
  31521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31522. ], PBRMaterial.prototype, "refractionTexture", void 0);
  31523. __decorate([
  31524. BABYLON.serializeAsColor3("ambient"),
  31525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31526. ], PBRMaterial.prototype, "ambientColor", void 0);
  31527. __decorate([
  31528. BABYLON.serializeAsColor3("albedo"),
  31529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31530. ], PBRMaterial.prototype, "albedoColor", void 0);
  31531. __decorate([
  31532. BABYLON.serializeAsColor3("reflectivity"),
  31533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31534. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  31535. __decorate([
  31536. BABYLON.serializeAsColor3("reflection"),
  31537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31538. ], PBRMaterial.prototype, "reflectionColor", void 0);
  31539. __decorate([
  31540. BABYLON.serializeAsColor3("emissive"),
  31541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31542. ], PBRMaterial.prototype, "emissiveColor", void 0);
  31543. __decorate([
  31544. BABYLON.serialize(),
  31545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31546. ], PBRMaterial.prototype, "microSurface", void 0);
  31547. __decorate([
  31548. BABYLON.serialize(),
  31549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31550. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  31551. __decorate([
  31552. BABYLON.serialize(),
  31553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31554. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  31555. __decorate([
  31556. BABYLON.serialize(),
  31557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31558. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  31559. __decorate([
  31560. BABYLON.serialize(),
  31561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31562. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31563. __decorate([
  31564. BABYLON.serialize(),
  31565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31566. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  31567. __decorate([
  31568. BABYLON.serialize(),
  31569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31570. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  31571. __decorate([
  31572. BABYLON.serialize(),
  31573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31574. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  31575. __decorate([
  31576. BABYLON.serialize(),
  31577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31578. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  31579. __decorate([
  31580. BABYLON.serialize(),
  31581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31582. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  31583. __decorate([
  31584. BABYLON.serialize(),
  31585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31586. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  31587. __decorate([
  31588. BABYLON.serialize(),
  31589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31590. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  31591. __decorate([
  31592. BABYLON.serialize(),
  31593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31594. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  31595. __decorate([
  31596. BABYLON.serialize(),
  31597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31598. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  31599. __decorate([
  31600. BABYLON.serialize(),
  31601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31602. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  31603. __decorate([
  31604. BABYLON.serialize(),
  31605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31606. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  31607. __decorate([
  31608. BABYLON.serialize(),
  31609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31610. ], PBRMaterial.prototype, "useParallax", void 0);
  31611. __decorate([
  31612. BABYLON.serialize(),
  31613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31614. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  31615. __decorate([
  31616. BABYLON.serialize(),
  31617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31618. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  31619. __decorate([
  31620. BABYLON.serialize(),
  31621. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31622. ], PBRMaterial.prototype, "disableLighting", void 0);
  31623. __decorate([
  31624. BABYLON.serialize(),
  31625. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31626. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  31627. __decorate([
  31628. BABYLON.serialize(),
  31629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31630. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  31631. __decorate([
  31632. BABYLON.serialize(),
  31633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31634. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  31635. __decorate([
  31636. BABYLON.serialize(),
  31637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31638. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  31639. __decorate([
  31640. BABYLON.serialize(),
  31641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31642. ], PBRMaterial.prototype, "premultiplyAlpha", void 0);
  31643. __decorate([
  31644. BABYLON.serialize(),
  31645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31646. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  31647. BABYLON.PBRMaterial = PBRMaterial;
  31648. })(BABYLON || (BABYLON = {}));
  31649. //# sourceMappingURL=babylon.pbrMaterial.js.map
  31650. var BABYLON;
  31651. (function (BABYLON) {
  31652. /**
  31653. * The PBR material of BJS following the metal roughness convention.
  31654. *
  31655. * This fits to the define PBR convention in the GLTF definition:
  31656. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  31657. */
  31658. var PBRMetallicRoughnessMaterial = (function (_super) {
  31659. __extends(PBRMetallicRoughnessMaterial, _super);
  31660. /**
  31661. * Instantiates a new PBRMetalRoughnessMaterial instance.
  31662. *
  31663. * @param name The material name
  31664. * @param scene The scene the material will be use in.
  31665. */
  31666. function PBRMetallicRoughnessMaterial(name, scene) {
  31667. var _this = _super.call(this, name, scene) || this;
  31668. _this._useRoughnessFromMetallicTextureGreen = true;
  31669. _this._useMetallnessFromMetallicTextureBlue = true;
  31670. return _this;
  31671. }
  31672. /**
  31673. * Return the currrent class name of the material.
  31674. */
  31675. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  31676. return "PBRMetallicRoughnessMaterial";
  31677. };
  31678. /**
  31679. * Return the active textures of the material.
  31680. */
  31681. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  31682. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31683. if (this.baseTexture) {
  31684. activeTextures.push(this.baseTexture);
  31685. }
  31686. if (this.metallicRoughnessTexture) {
  31687. activeTextures.push(this.metallicRoughnessTexture);
  31688. }
  31689. return activeTextures;
  31690. };
  31691. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  31692. var _this = this;
  31693. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  31694. };
  31695. /**
  31696. * Serialize the material to a parsable JSON object.
  31697. */
  31698. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  31699. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31700. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  31701. return serializationObject;
  31702. };
  31703. /**
  31704. * Parses a JSON object correponding to the serialize function.
  31705. */
  31706. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  31707. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  31708. };
  31709. return PBRMetallicRoughnessMaterial;
  31710. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31711. __decorate([
  31712. BABYLON.serializeAsTexture(),
  31713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  31714. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  31715. __decorate([
  31716. BABYLON.serializeAsTexture(),
  31717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  31718. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  31719. __decorate([
  31720. BABYLON.serialize(),
  31721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31722. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  31723. __decorate([
  31724. BABYLON.serialize(),
  31725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31726. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  31727. __decorate([
  31728. BABYLON.serializeAsTexture(),
  31729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  31730. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  31731. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  31732. })(BABYLON || (BABYLON = {}));
  31733. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  31734. var BABYLON;
  31735. (function (BABYLON) {
  31736. /**
  31737. * The PBR material of BJS following the specular glossiness convention.
  31738. *
  31739. * This fits to the define PBR convention in the GLTF definition:
  31740. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  31741. */
  31742. var PBRSpecularGlossinessMaterial = (function (_super) {
  31743. __extends(PBRSpecularGlossinessMaterial, _super);
  31744. /**
  31745. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  31746. *
  31747. * @param name The material name
  31748. * @param scene The scene the material will be use in.
  31749. */
  31750. function PBRSpecularGlossinessMaterial(name, scene) {
  31751. var _this = _super.call(this, name, scene) || this;
  31752. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  31753. return _this;
  31754. }
  31755. /**
  31756. * Return the currrent class name of the material.
  31757. */
  31758. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  31759. return "PBRSpecularGlossinessMaterial";
  31760. };
  31761. /**
  31762. * Return the active textures of the material.
  31763. */
  31764. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  31765. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31766. if (this.diffuseTexture) {
  31767. activeTextures.push(this.diffuseTexture);
  31768. }
  31769. if (this.specularGlossinessTexture) {
  31770. activeTextures.push(this.specularGlossinessTexture);
  31771. }
  31772. return activeTextures;
  31773. };
  31774. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  31775. var _this = this;
  31776. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  31777. };
  31778. /**
  31779. * Serialize the material to a parsable JSON object.
  31780. */
  31781. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  31782. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31783. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  31784. return serializationObject;
  31785. };
  31786. /**
  31787. * Parses a JSON object correponding to the serialize function.
  31788. */
  31789. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  31790. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  31791. };
  31792. return PBRSpecularGlossinessMaterial;
  31793. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31794. __decorate([
  31795. BABYLON.serializeAsColor3(),
  31796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  31797. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  31798. __decorate([
  31799. BABYLON.serializeAsTexture(),
  31800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  31801. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  31802. __decorate([
  31803. BABYLON.serializeAsColor3(),
  31804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  31805. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  31806. __decorate([
  31807. BABYLON.serialize(),
  31808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  31809. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  31810. __decorate([
  31811. BABYLON.serializeAsTexture(),
  31812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  31813. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  31814. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  31815. })(BABYLON || (BABYLON = {}));
  31816. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  31817. var BABYLON;
  31818. (function (BABYLON) {
  31819. BABYLON.CameraInputTypes = {};
  31820. var CameraInputsManager = (function () {
  31821. function CameraInputsManager(camera) {
  31822. this.attached = {};
  31823. this.camera = camera;
  31824. this.checkInputs = function () { };
  31825. }
  31826. CameraInputsManager.prototype.add = function (input) {
  31827. var type = input.getSimpleName();
  31828. if (this.attached[type]) {
  31829. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31830. return;
  31831. }
  31832. this.attached[type] = input;
  31833. input.camera = this.camera;
  31834. //for checkInputs, we are dynamically creating a function
  31835. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31836. if (input.checkInputs) {
  31837. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31838. }
  31839. if (this.attachedElement) {
  31840. input.attachControl(this.attachedElement);
  31841. }
  31842. };
  31843. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31844. for (var cam in this.attached) {
  31845. var input = this.attached[cam];
  31846. if (input === inputToRemove) {
  31847. input.detachControl(this.attachedElement);
  31848. delete this.attached[cam];
  31849. this.rebuildInputCheck();
  31850. }
  31851. }
  31852. };
  31853. CameraInputsManager.prototype.removeByType = function (inputType) {
  31854. for (var cam in this.attached) {
  31855. var input = this.attached[cam];
  31856. if (input.getTypeName() === inputType) {
  31857. input.detachControl(this.attachedElement);
  31858. delete this.attached[cam];
  31859. this.rebuildInputCheck();
  31860. }
  31861. }
  31862. };
  31863. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31864. var current = this.checkInputs;
  31865. return function () {
  31866. current();
  31867. fn();
  31868. };
  31869. };
  31870. CameraInputsManager.prototype.attachInput = function (input) {
  31871. input.attachControl(this.attachedElement, this.noPreventDefault);
  31872. };
  31873. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31874. if (this.attachedElement) {
  31875. return;
  31876. }
  31877. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31878. this.attachedElement = element;
  31879. this.noPreventDefault = noPreventDefault;
  31880. for (var cam in this.attached) {
  31881. var input = this.attached[cam];
  31882. this.attached[cam].attachControl(element, noPreventDefault);
  31883. }
  31884. };
  31885. CameraInputsManager.prototype.detachElement = function (element) {
  31886. if (this.attachedElement !== element) {
  31887. return;
  31888. }
  31889. for (var cam in this.attached) {
  31890. var input = this.attached[cam];
  31891. this.attached[cam].detachControl(element);
  31892. }
  31893. this.attachedElement = null;
  31894. };
  31895. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31896. this.checkInputs = function () { };
  31897. for (var cam in this.attached) {
  31898. var input = this.attached[cam];
  31899. if (input.checkInputs) {
  31900. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31901. }
  31902. }
  31903. };
  31904. CameraInputsManager.prototype.clear = function () {
  31905. if (this.attachedElement) {
  31906. this.detachElement(this.attachedElement);
  31907. }
  31908. this.attached = {};
  31909. this.attachedElement = null;
  31910. this.checkInputs = function () { };
  31911. };
  31912. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31913. var inputs = {};
  31914. for (var cam in this.attached) {
  31915. var input = this.attached[cam];
  31916. var res = BABYLON.SerializationHelper.Serialize(input);
  31917. inputs[input.getTypeName()] = res;
  31918. }
  31919. serializedCamera.inputsmgr = inputs;
  31920. };
  31921. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31922. var parsedInputs = parsedCamera.inputsmgr;
  31923. if (parsedInputs) {
  31924. this.clear();
  31925. for (var n in parsedInputs) {
  31926. var construct = BABYLON.CameraInputTypes[n];
  31927. if (construct) {
  31928. var parsedinput = parsedInputs[n];
  31929. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31930. this.add(input);
  31931. }
  31932. }
  31933. }
  31934. else {
  31935. //2016-03-08 this part is for managing backward compatibility
  31936. for (var n in this.attached) {
  31937. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31938. if (construct) {
  31939. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31940. this.remove(this.attached[n]);
  31941. this.add(input);
  31942. }
  31943. }
  31944. }
  31945. };
  31946. return CameraInputsManager;
  31947. }());
  31948. BABYLON.CameraInputsManager = CameraInputsManager;
  31949. })(BABYLON || (BABYLON = {}));
  31950. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31951. var BABYLON;
  31952. (function (BABYLON) {
  31953. var FreeCameraMouseInput = (function () {
  31954. function FreeCameraMouseInput(touchEnabled) {
  31955. if (touchEnabled === void 0) { touchEnabled = true; }
  31956. this.touchEnabled = touchEnabled;
  31957. this.buttons = [0, 1, 2];
  31958. this.angularSensibility = 2000.0;
  31959. }
  31960. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  31961. var _this = this;
  31962. var engine = this.camera.getEngine();
  31963. if (!this._pointerInput) {
  31964. this._pointerInput = function (p, s) {
  31965. var evt = p.event;
  31966. if (!_this.touchEnabled && evt.pointerType === "touch") {
  31967. return;
  31968. }
  31969. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31970. return;
  31971. }
  31972. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31973. try {
  31974. evt.srcElement.setPointerCapture(evt.pointerId);
  31975. }
  31976. catch (e) {
  31977. //Nothing to do with the error. Execution will continue.
  31978. }
  31979. _this.previousPosition = {
  31980. x: evt.clientX,
  31981. y: evt.clientY
  31982. };
  31983. if (!noPreventDefault) {
  31984. evt.preventDefault();
  31985. element.focus();
  31986. }
  31987. }
  31988. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31989. try {
  31990. evt.srcElement.releasePointerCapture(evt.pointerId);
  31991. }
  31992. catch (e) {
  31993. //Nothing to do with the error.
  31994. }
  31995. _this.previousPosition = null;
  31996. if (!noPreventDefault) {
  31997. evt.preventDefault();
  31998. }
  31999. }
  32000. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32001. if (!_this.previousPosition || engine.isPointerLock) {
  32002. return;
  32003. }
  32004. var offsetX = evt.clientX - _this.previousPosition.x;
  32005. var offsetY = evt.clientY - _this.previousPosition.y;
  32006. if (_this.camera.getScene().useRightHandedSystem) {
  32007. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  32008. }
  32009. else {
  32010. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  32011. }
  32012. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  32013. _this.previousPosition = {
  32014. x: evt.clientX,
  32015. y: evt.clientY
  32016. };
  32017. if (!noPreventDefault) {
  32018. evt.preventDefault();
  32019. }
  32020. }
  32021. };
  32022. }
  32023. this._onMouseMove = function (evt) {
  32024. if (!engine.isPointerLock) {
  32025. return;
  32026. }
  32027. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32028. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32029. if (_this.camera.getScene().useRightHandedSystem) {
  32030. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  32031. }
  32032. else {
  32033. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  32034. }
  32035. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  32036. _this.previousPosition = null;
  32037. if (!noPreventDefault) {
  32038. evt.preventDefault();
  32039. }
  32040. };
  32041. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  32042. element.addEventListener("mousemove", this._onMouseMove, false);
  32043. };
  32044. FreeCameraMouseInput.prototype.detachControl = function (element) {
  32045. if (this._observer && element) {
  32046. this.camera.getScene().onPointerObservable.remove(this._observer);
  32047. element.removeEventListener("mousemove", this._onMouseMove);
  32048. this._observer = null;
  32049. this._onMouseMove = null;
  32050. this.previousPosition = null;
  32051. }
  32052. };
  32053. FreeCameraMouseInput.prototype.getTypeName = function () {
  32054. return "FreeCameraMouseInput";
  32055. };
  32056. FreeCameraMouseInput.prototype.getSimpleName = function () {
  32057. return "mouse";
  32058. };
  32059. return FreeCameraMouseInput;
  32060. }());
  32061. __decorate([
  32062. BABYLON.serialize()
  32063. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  32064. __decorate([
  32065. BABYLON.serialize()
  32066. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  32067. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  32068. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  32069. })(BABYLON || (BABYLON = {}));
  32070. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  32071. var BABYLON;
  32072. (function (BABYLON) {
  32073. var FreeCameraKeyboardMoveInput = (function () {
  32074. function FreeCameraKeyboardMoveInput() {
  32075. this._keys = [];
  32076. this.keysUp = [38];
  32077. this.keysDown = [40];
  32078. this.keysLeft = [37];
  32079. this.keysRight = [39];
  32080. }
  32081. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32082. var _this = this;
  32083. if (!this._onKeyDown) {
  32084. element.tabIndex = 1;
  32085. this._onKeyDown = function (evt) {
  32086. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32087. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32088. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32089. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32090. var index = _this._keys.indexOf(evt.keyCode);
  32091. if (index === -1) {
  32092. _this._keys.push(evt.keyCode);
  32093. }
  32094. if (!noPreventDefault) {
  32095. evt.preventDefault();
  32096. }
  32097. }
  32098. };
  32099. this._onKeyUp = function (evt) {
  32100. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32101. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32102. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32103. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32104. var index = _this._keys.indexOf(evt.keyCode);
  32105. if (index >= 0) {
  32106. _this._keys.splice(index, 1);
  32107. }
  32108. if (!noPreventDefault) {
  32109. evt.preventDefault();
  32110. }
  32111. }
  32112. };
  32113. element.addEventListener("keydown", this._onKeyDown, false);
  32114. element.addEventListener("keyup", this._onKeyUp, false);
  32115. BABYLON.Tools.RegisterTopRootEvents([
  32116. { name: "blur", handler: this._onLostFocus }
  32117. ]);
  32118. }
  32119. };
  32120. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32121. if (this._onKeyDown) {
  32122. element.removeEventListener("keydown", this._onKeyDown);
  32123. element.removeEventListener("keyup", this._onKeyUp);
  32124. BABYLON.Tools.UnregisterTopRootEvents([
  32125. { name: "blur", handler: this._onLostFocus }
  32126. ]);
  32127. this._keys = [];
  32128. this._onKeyDown = null;
  32129. this._onKeyUp = null;
  32130. }
  32131. };
  32132. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32133. if (this._onKeyDown) {
  32134. var camera = this.camera;
  32135. // Keyboard
  32136. for (var index = 0; index < this._keys.length; index++) {
  32137. var keyCode = this._keys[index];
  32138. var speed = camera._computeLocalCameraSpeed();
  32139. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32140. camera._localDirection.copyFromFloats(-speed, 0, 0);
  32141. }
  32142. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32143. camera._localDirection.copyFromFloats(0, 0, speed);
  32144. }
  32145. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32146. camera._localDirection.copyFromFloats(speed, 0, 0);
  32147. }
  32148. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32149. camera._localDirection.copyFromFloats(0, 0, -speed);
  32150. }
  32151. if (camera.getScene().useRightHandedSystem) {
  32152. camera._localDirection.z *= -1;
  32153. }
  32154. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  32155. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  32156. camera.cameraDirection.addInPlace(camera._transformedDirection);
  32157. }
  32158. }
  32159. };
  32160. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32161. return "FreeCameraKeyboardMoveInput";
  32162. };
  32163. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  32164. this._keys = [];
  32165. };
  32166. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32167. return "keyboard";
  32168. };
  32169. return FreeCameraKeyboardMoveInput;
  32170. }());
  32171. __decorate([
  32172. BABYLON.serialize()
  32173. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32174. __decorate([
  32175. BABYLON.serialize()
  32176. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32177. __decorate([
  32178. BABYLON.serialize()
  32179. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32180. __decorate([
  32181. BABYLON.serialize()
  32182. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32183. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  32184. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  32185. })(BABYLON || (BABYLON = {}));
  32186. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  32187. var BABYLON;
  32188. (function (BABYLON) {
  32189. var FreeCameraInputsManager = (function (_super) {
  32190. __extends(FreeCameraInputsManager, _super);
  32191. function FreeCameraInputsManager(camera) {
  32192. return _super.call(this, camera) || this;
  32193. }
  32194. FreeCameraInputsManager.prototype.addKeyboard = function () {
  32195. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  32196. return this;
  32197. };
  32198. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  32199. if (touchEnabled === void 0) { touchEnabled = true; }
  32200. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  32201. return this;
  32202. };
  32203. FreeCameraInputsManager.prototype.addGamepad = function () {
  32204. this.add(new BABYLON.FreeCameraGamepadInput());
  32205. return this;
  32206. };
  32207. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  32208. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  32209. return this;
  32210. };
  32211. FreeCameraInputsManager.prototype.addTouch = function () {
  32212. this.add(new BABYLON.FreeCameraTouchInput());
  32213. return this;
  32214. };
  32215. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  32216. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  32217. return this;
  32218. };
  32219. return FreeCameraInputsManager;
  32220. }(BABYLON.CameraInputsManager));
  32221. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  32222. })(BABYLON || (BABYLON = {}));
  32223. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  32224. /// <reference path="babylon.camera.ts" />
  32225. var BABYLON;
  32226. (function (BABYLON) {
  32227. var TargetCamera = (function (_super) {
  32228. __extends(TargetCamera, _super);
  32229. function TargetCamera(name, position, scene) {
  32230. var _this = _super.call(this, name, position, scene) || this;
  32231. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  32232. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  32233. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  32234. _this.speed = 2.0;
  32235. _this.noRotationConstraint = false;
  32236. _this.lockedTarget = null;
  32237. _this._currentTarget = BABYLON.Vector3.Zero();
  32238. _this._viewMatrix = BABYLON.Matrix.Zero();
  32239. _this._camMatrix = BABYLON.Matrix.Zero();
  32240. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  32241. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  32242. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  32243. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  32244. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  32245. _this._lookAtTemp = BABYLON.Matrix.Zero();
  32246. _this._tempMatrix = BABYLON.Matrix.Zero();
  32247. return _this;
  32248. }
  32249. TargetCamera.prototype.getFrontPosition = function (distance) {
  32250. var direction = this.getTarget().subtract(this.position);
  32251. direction.normalize();
  32252. direction.scaleInPlace(distance);
  32253. return this.globalPosition.add(direction);
  32254. };
  32255. TargetCamera.prototype._getLockedTargetPosition = function () {
  32256. if (!this.lockedTarget) {
  32257. return null;
  32258. }
  32259. if (this.lockedTarget.absolutePosition) {
  32260. this.lockedTarget.computeWorldMatrix();
  32261. }
  32262. return this.lockedTarget.absolutePosition || this.lockedTarget;
  32263. };
  32264. // Cache
  32265. TargetCamera.prototype._initCache = function () {
  32266. _super.prototype._initCache.call(this);
  32267. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32268. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32269. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32270. };
  32271. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  32272. if (!ignoreParentClass) {
  32273. _super.prototype._updateCache.call(this);
  32274. }
  32275. var lockedTargetPosition = this._getLockedTargetPosition();
  32276. if (!lockedTargetPosition) {
  32277. this._cache.lockedTarget = null;
  32278. }
  32279. else {
  32280. if (!this._cache.lockedTarget) {
  32281. this._cache.lockedTarget = lockedTargetPosition.clone();
  32282. }
  32283. else {
  32284. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  32285. }
  32286. }
  32287. this._cache.rotation.copyFrom(this.rotation);
  32288. if (this.rotationQuaternion)
  32289. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32290. };
  32291. // Synchronized
  32292. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  32293. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  32294. return false;
  32295. }
  32296. var lockedTargetPosition = this._getLockedTargetPosition();
  32297. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  32298. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  32299. };
  32300. // Methods
  32301. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  32302. var engine = this.getEngine();
  32303. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  32304. };
  32305. // Target
  32306. TargetCamera.prototype.setTarget = function (target) {
  32307. this.upVector.normalize();
  32308. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  32309. this._camMatrix.invert();
  32310. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  32311. var vDir = target.subtract(this.position);
  32312. if (vDir.x >= 0.0) {
  32313. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  32314. }
  32315. else {
  32316. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  32317. }
  32318. this.rotation.z = 0;
  32319. if (isNaN(this.rotation.x)) {
  32320. this.rotation.x = 0;
  32321. }
  32322. if (isNaN(this.rotation.y)) {
  32323. this.rotation.y = 0;
  32324. }
  32325. if (isNaN(this.rotation.z)) {
  32326. this.rotation.z = 0;
  32327. }
  32328. if (this.rotationQuaternion) {
  32329. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  32330. }
  32331. };
  32332. /**
  32333. * Return the current target position of the camera. This value is expressed in local space.
  32334. */
  32335. TargetCamera.prototype.getTarget = function () {
  32336. return this._currentTarget;
  32337. };
  32338. TargetCamera.prototype._decideIfNeedsToMove = function () {
  32339. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  32340. };
  32341. TargetCamera.prototype._updatePosition = function () {
  32342. if (this.parent) {
  32343. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  32344. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  32345. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  32346. return;
  32347. }
  32348. this.position.addInPlace(this.cameraDirection);
  32349. };
  32350. TargetCamera.prototype._checkInputs = function () {
  32351. var needToMove = this._decideIfNeedsToMove();
  32352. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  32353. // Move
  32354. if (needToMove) {
  32355. this._updatePosition();
  32356. }
  32357. // Rotate
  32358. if (needToRotate) {
  32359. this.rotation.x += this.cameraRotation.x;
  32360. this.rotation.y += this.cameraRotation.y;
  32361. //rotate, if quaternion is set and rotation was used
  32362. if (this.rotationQuaternion) {
  32363. var len = this.rotation.lengthSquared();
  32364. if (len) {
  32365. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  32366. }
  32367. }
  32368. if (!this.noRotationConstraint) {
  32369. var limit = (Math.PI / 2) * 0.95;
  32370. if (this.rotation.x > limit)
  32371. this.rotation.x = limit;
  32372. if (this.rotation.x < -limit)
  32373. this.rotation.x = -limit;
  32374. }
  32375. }
  32376. // Inertia
  32377. if (needToMove) {
  32378. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  32379. this.cameraDirection.x = 0;
  32380. }
  32381. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  32382. this.cameraDirection.y = 0;
  32383. }
  32384. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  32385. this.cameraDirection.z = 0;
  32386. }
  32387. this.cameraDirection.scaleInPlace(this.inertia);
  32388. }
  32389. if (needToRotate) {
  32390. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  32391. this.cameraRotation.x = 0;
  32392. }
  32393. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  32394. this.cameraRotation.y = 0;
  32395. }
  32396. this.cameraRotation.scaleInPlace(this.inertia);
  32397. }
  32398. _super.prototype._checkInputs.call(this);
  32399. };
  32400. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  32401. if (this.rotationQuaternion) {
  32402. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  32403. //update the up vector!
  32404. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  32405. }
  32406. else {
  32407. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  32408. }
  32409. };
  32410. TargetCamera.prototype._getViewMatrix = function () {
  32411. if (!this.lockedTarget) {
  32412. // Compute
  32413. this._updateCameraRotationMatrix();
  32414. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  32415. // Computing target and final matrix
  32416. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  32417. }
  32418. else {
  32419. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  32420. }
  32421. if (this.getScene().useRightHandedSystem) {
  32422. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  32423. }
  32424. else {
  32425. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  32426. }
  32427. return this._viewMatrix;
  32428. };
  32429. /**
  32430. * @override
  32431. * Override Camera.createRigCamera
  32432. */
  32433. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32434. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  32435. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  32436. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  32437. if (!this.rotationQuaternion) {
  32438. this.rotationQuaternion = new BABYLON.Quaternion();
  32439. }
  32440. rigCamera._cameraRigParams = {};
  32441. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  32442. }
  32443. return rigCamera;
  32444. }
  32445. return null;
  32446. };
  32447. /**
  32448. * @override
  32449. * Override Camera._updateRigCameras
  32450. */
  32451. TargetCamera.prototype._updateRigCameras = function () {
  32452. var camLeft = this._rigCameras[0];
  32453. var camRight = this._rigCameras[1];
  32454. switch (this.cameraRigMode) {
  32455. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32456. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32457. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32458. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32459. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  32460. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  32461. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  32462. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  32463. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  32464. camLeft.setTarget(this.getTarget());
  32465. camRight.setTarget(this.getTarget());
  32466. break;
  32467. case BABYLON.Camera.RIG_MODE_VR:
  32468. if (camLeft.rotationQuaternion) {
  32469. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32470. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32471. }
  32472. else {
  32473. camLeft.rotation.copyFrom(this.rotation);
  32474. camRight.rotation.copyFrom(this.rotation);
  32475. }
  32476. camLeft.position.copyFrom(this.position);
  32477. camRight.position.copyFrom(this.position);
  32478. break;
  32479. }
  32480. _super.prototype._updateRigCameras.call(this);
  32481. };
  32482. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  32483. if (!this._rigCamTransformMatrix) {
  32484. this._rigCamTransformMatrix = new BABYLON.Matrix();
  32485. }
  32486. var target = this.getTarget();
  32487. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  32488. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  32489. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  32490. };
  32491. TargetCamera.prototype.getClassName = function () {
  32492. return "TargetCamera";
  32493. };
  32494. return TargetCamera;
  32495. }(BABYLON.Camera));
  32496. __decorate([
  32497. BABYLON.serializeAsVector3()
  32498. ], TargetCamera.prototype, "rotation", void 0);
  32499. __decorate([
  32500. BABYLON.serialize()
  32501. ], TargetCamera.prototype, "speed", void 0);
  32502. __decorate([
  32503. BABYLON.serializeAsMeshReference("lockedTargetId")
  32504. ], TargetCamera.prototype, "lockedTarget", void 0);
  32505. BABYLON.TargetCamera = TargetCamera;
  32506. })(BABYLON || (BABYLON = {}));
  32507. //# sourceMappingURL=babylon.targetCamera.js.map
  32508. var BABYLON;
  32509. (function (BABYLON) {
  32510. var FreeCamera = (function (_super) {
  32511. __extends(FreeCamera, _super);
  32512. function FreeCamera(name, position, scene) {
  32513. var _this = _super.call(this, name, position, scene) || this;
  32514. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  32515. _this.checkCollisions = false;
  32516. _this.applyGravity = false;
  32517. _this._needMoveForGravity = false;
  32518. _this._oldPosition = BABYLON.Vector3.Zero();
  32519. _this._diffPosition = BABYLON.Vector3.Zero();
  32520. _this._newPosition = BABYLON.Vector3.Zero();
  32521. // Collisions
  32522. _this._collisionMask = -1;
  32523. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32524. if (collidedMesh === void 0) { collidedMesh = null; }
  32525. //TODO move this to the collision coordinator!
  32526. if (_this.getScene().workerCollisions)
  32527. newPosition.multiplyInPlace(_this._collider.radius);
  32528. var updatePosition = function (newPos) {
  32529. _this._newPosition.copyFrom(newPos);
  32530. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  32531. var oldPosition = _this.position.clone();
  32532. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  32533. _this.position.addInPlace(_this._diffPosition);
  32534. if (_this.onCollide && collidedMesh) {
  32535. _this.onCollide(collidedMesh);
  32536. }
  32537. }
  32538. };
  32539. updatePosition(newPosition);
  32540. };
  32541. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  32542. _this.inputs.addKeyboard().addMouse();
  32543. return _this;
  32544. }
  32545. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  32546. //-- begin properties for backward compatibility for inputs
  32547. get: function () {
  32548. var mouse = this.inputs.attached["mouse"];
  32549. if (mouse)
  32550. return mouse.angularSensibility;
  32551. },
  32552. set: function (value) {
  32553. var mouse = this.inputs.attached["mouse"];
  32554. if (mouse)
  32555. mouse.angularSensibility = value;
  32556. },
  32557. enumerable: true,
  32558. configurable: true
  32559. });
  32560. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  32561. get: function () {
  32562. var keyboard = this.inputs.attached["keyboard"];
  32563. if (keyboard)
  32564. return keyboard.keysUp;
  32565. },
  32566. set: function (value) {
  32567. var keyboard = this.inputs.attached["keyboard"];
  32568. if (keyboard)
  32569. keyboard.keysUp = value;
  32570. },
  32571. enumerable: true,
  32572. configurable: true
  32573. });
  32574. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  32575. get: function () {
  32576. var keyboard = this.inputs.attached["keyboard"];
  32577. if (keyboard)
  32578. return keyboard.keysDown;
  32579. },
  32580. set: function (value) {
  32581. var keyboard = this.inputs.attached["keyboard"];
  32582. if (keyboard)
  32583. keyboard.keysDown = value;
  32584. },
  32585. enumerable: true,
  32586. configurable: true
  32587. });
  32588. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  32589. get: function () {
  32590. var keyboard = this.inputs.attached["keyboard"];
  32591. if (keyboard)
  32592. return keyboard.keysLeft;
  32593. },
  32594. set: function (value) {
  32595. var keyboard = this.inputs.attached["keyboard"];
  32596. if (keyboard)
  32597. keyboard.keysLeft = value;
  32598. },
  32599. enumerable: true,
  32600. configurable: true
  32601. });
  32602. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  32603. get: function () {
  32604. var keyboard = this.inputs.attached["keyboard"];
  32605. if (keyboard)
  32606. return keyboard.keysRight;
  32607. },
  32608. set: function (value) {
  32609. var keyboard = this.inputs.attached["keyboard"];
  32610. if (keyboard)
  32611. keyboard.keysRight = value;
  32612. },
  32613. enumerable: true,
  32614. configurable: true
  32615. });
  32616. // Controls
  32617. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32618. this.inputs.attachElement(element, noPreventDefault);
  32619. };
  32620. FreeCamera.prototype.detachControl = function (element) {
  32621. this.inputs.detachElement(element);
  32622. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  32623. this.cameraRotation = new BABYLON.Vector2(0, 0);
  32624. };
  32625. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  32626. get: function () {
  32627. return this._collisionMask;
  32628. },
  32629. set: function (mask) {
  32630. this._collisionMask = !isNaN(mask) ? mask : -1;
  32631. },
  32632. enumerable: true,
  32633. configurable: true
  32634. });
  32635. FreeCamera.prototype._collideWithWorld = function (velocity) {
  32636. var globalPosition;
  32637. if (this.parent) {
  32638. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  32639. }
  32640. else {
  32641. globalPosition = this.position;
  32642. }
  32643. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  32644. if (!this._collider) {
  32645. this._collider = new BABYLON.Collider();
  32646. }
  32647. this._collider.radius = this.ellipsoid;
  32648. this._collider.collisionMask = this._collisionMask;
  32649. //no need for clone, as long as gravity is not on.
  32650. var actualVelocity = velocity;
  32651. //add gravity to the velocity to prevent the dual-collision checking
  32652. if (this.applyGravity) {
  32653. //this prevents mending with cameraDirection, a global variable of the free camera class.
  32654. actualVelocity = velocity.add(this.getScene().gravity);
  32655. }
  32656. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32657. };
  32658. FreeCamera.prototype._checkInputs = function () {
  32659. if (!this._localDirection) {
  32660. this._localDirection = BABYLON.Vector3.Zero();
  32661. this._transformedDirection = BABYLON.Vector3.Zero();
  32662. }
  32663. this.inputs.checkInputs();
  32664. _super.prototype._checkInputs.call(this);
  32665. };
  32666. FreeCamera.prototype._decideIfNeedsToMove = function () {
  32667. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  32668. };
  32669. FreeCamera.prototype._updatePosition = function () {
  32670. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  32671. this._collideWithWorld(this.cameraDirection);
  32672. }
  32673. else {
  32674. _super.prototype._updatePosition.call(this);
  32675. }
  32676. };
  32677. FreeCamera.prototype.dispose = function () {
  32678. this.inputs.clear();
  32679. _super.prototype.dispose.call(this);
  32680. };
  32681. FreeCamera.prototype.getClassName = function () {
  32682. return "FreeCamera";
  32683. };
  32684. return FreeCamera;
  32685. }(BABYLON.TargetCamera));
  32686. __decorate([
  32687. BABYLON.serializeAsVector3()
  32688. ], FreeCamera.prototype, "ellipsoid", void 0);
  32689. __decorate([
  32690. BABYLON.serialize()
  32691. ], FreeCamera.prototype, "checkCollisions", void 0);
  32692. __decorate([
  32693. BABYLON.serialize()
  32694. ], FreeCamera.prototype, "applyGravity", void 0);
  32695. BABYLON.FreeCamera = FreeCamera;
  32696. })(BABYLON || (BABYLON = {}));
  32697. //# sourceMappingURL=babylon.freeCamera.js.map
  32698. var BABYLON;
  32699. (function (BABYLON) {
  32700. var ArcRotateCameraKeyboardMoveInput = (function () {
  32701. function ArcRotateCameraKeyboardMoveInput() {
  32702. this._keys = [];
  32703. this.keysUp = [38];
  32704. this.keysDown = [40];
  32705. this.keysLeft = [37];
  32706. this.keysRight = [39];
  32707. }
  32708. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32709. var _this = this;
  32710. element.tabIndex = 1;
  32711. this._onKeyDown = function (evt) {
  32712. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32713. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32714. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32715. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32716. var index = _this._keys.indexOf(evt.keyCode);
  32717. if (index === -1) {
  32718. _this._keys.push(evt.keyCode);
  32719. }
  32720. if (evt.preventDefault) {
  32721. if (!noPreventDefault) {
  32722. evt.preventDefault();
  32723. }
  32724. }
  32725. }
  32726. };
  32727. this._onKeyUp = function (evt) {
  32728. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32729. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32730. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32731. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32732. var index = _this._keys.indexOf(evt.keyCode);
  32733. if (index >= 0) {
  32734. _this._keys.splice(index, 1);
  32735. }
  32736. if (evt.preventDefault) {
  32737. if (!noPreventDefault) {
  32738. evt.preventDefault();
  32739. }
  32740. }
  32741. }
  32742. };
  32743. this._onLostFocus = function () {
  32744. _this._keys = [];
  32745. };
  32746. element.addEventListener("keydown", this._onKeyDown, false);
  32747. element.addEventListener("keyup", this._onKeyUp, false);
  32748. BABYLON.Tools.RegisterTopRootEvents([
  32749. { name: "blur", handler: this._onLostFocus }
  32750. ]);
  32751. };
  32752. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32753. if (element) {
  32754. element.removeEventListener("keydown", this._onKeyDown);
  32755. element.removeEventListener("keyup", this._onKeyUp);
  32756. }
  32757. BABYLON.Tools.UnregisterTopRootEvents([
  32758. { name: "blur", handler: this._onLostFocus }
  32759. ]);
  32760. this._keys = [];
  32761. this._onKeyDown = null;
  32762. this._onKeyUp = null;
  32763. this._onLostFocus = null;
  32764. };
  32765. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32766. if (this._onKeyDown) {
  32767. var camera = this.camera;
  32768. for (var index = 0; index < this._keys.length; index++) {
  32769. var keyCode = this._keys[index];
  32770. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32771. camera.inertialAlphaOffset -= 0.01;
  32772. }
  32773. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32774. camera.inertialBetaOffset -= 0.01;
  32775. }
  32776. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32777. camera.inertialAlphaOffset += 0.01;
  32778. }
  32779. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32780. camera.inertialBetaOffset += 0.01;
  32781. }
  32782. }
  32783. }
  32784. };
  32785. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32786. return "ArcRotateCameraKeyboardMoveInput";
  32787. };
  32788. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32789. return "keyboard";
  32790. };
  32791. return ArcRotateCameraKeyboardMoveInput;
  32792. }());
  32793. __decorate([
  32794. BABYLON.serialize()
  32795. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32796. __decorate([
  32797. BABYLON.serialize()
  32798. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32799. __decorate([
  32800. BABYLON.serialize()
  32801. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32802. __decorate([
  32803. BABYLON.serialize()
  32804. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32805. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  32806. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  32807. })(BABYLON || (BABYLON = {}));
  32808. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  32809. var BABYLON;
  32810. (function (BABYLON) {
  32811. var ArcRotateCameraMouseWheelInput = (function () {
  32812. function ArcRotateCameraMouseWheelInput() {
  32813. this.wheelPrecision = 3.0;
  32814. }
  32815. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  32816. var _this = this;
  32817. this._wheel = function (p, s) {
  32818. //sanity check - this should be a PointerWheel event.
  32819. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  32820. return;
  32821. var event = p.event;
  32822. var delta = 0;
  32823. if (event.wheelDelta) {
  32824. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  32825. }
  32826. else if (event.detail) {
  32827. delta = -event.detail / _this.wheelPrecision;
  32828. }
  32829. if (delta)
  32830. _this.camera.inertialRadiusOffset += delta;
  32831. if (event.preventDefault) {
  32832. if (!noPreventDefault) {
  32833. event.preventDefault();
  32834. }
  32835. }
  32836. };
  32837. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  32838. };
  32839. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  32840. if (this._observer && element) {
  32841. this.camera.getScene().onPointerObservable.remove(this._observer);
  32842. this._observer = null;
  32843. this._wheel = null;
  32844. }
  32845. };
  32846. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  32847. return "ArcRotateCameraMouseWheelInput";
  32848. };
  32849. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  32850. return "mousewheel";
  32851. };
  32852. return ArcRotateCameraMouseWheelInput;
  32853. }());
  32854. __decorate([
  32855. BABYLON.serialize()
  32856. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  32857. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  32858. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  32859. })(BABYLON || (BABYLON = {}));
  32860. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  32861. var BABYLON;
  32862. (function (BABYLON) {
  32863. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  32864. var ArcRotateCameraPointersInput = (function () {
  32865. function ArcRotateCameraPointersInput() {
  32866. this.buttons = [0, 1, 2];
  32867. this.angularSensibilityX = 1000.0;
  32868. this.angularSensibilityY = 1000.0;
  32869. this.pinchPrecision = 6.0;
  32870. this.panningSensibility = 50.0;
  32871. this._isPanClick = false;
  32872. this.pinchInwards = true;
  32873. }
  32874. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  32875. var _this = this;
  32876. var engine = this.camera.getEngine();
  32877. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  32878. var pointA, pointB;
  32879. var previousPinchDistance = 0;
  32880. this._pointerInput = function (p, s) {
  32881. var evt = p.event;
  32882. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32883. return;
  32884. }
  32885. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32886. try {
  32887. evt.srcElement.setPointerCapture(evt.pointerId);
  32888. }
  32889. catch (e) {
  32890. //Nothing to do with the error. Execution will continue.
  32891. }
  32892. // Manage panning with pan button click
  32893. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  32894. // manage pointers
  32895. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  32896. if (pointA === undefined) {
  32897. pointA = cacheSoloPointer;
  32898. }
  32899. else if (pointB === undefined) {
  32900. pointB = cacheSoloPointer;
  32901. }
  32902. if (!noPreventDefault) {
  32903. evt.preventDefault();
  32904. element.focus();
  32905. }
  32906. }
  32907. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32908. try {
  32909. evt.srcElement.releasePointerCapture(evt.pointerId);
  32910. }
  32911. catch (e) {
  32912. //Nothing to do with the error.
  32913. }
  32914. cacheSoloPointer = null;
  32915. previousPinchDistance = 0;
  32916. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32917. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32918. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32919. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32920. pointA = pointB = undefined;
  32921. if (!noPreventDefault) {
  32922. evt.preventDefault();
  32923. }
  32924. }
  32925. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32926. if (!noPreventDefault) {
  32927. evt.preventDefault();
  32928. }
  32929. // One button down
  32930. if (pointA && pointB === undefined) {
  32931. if (_this.panningSensibility !== 0 &&
  32932. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32933. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32934. _this.camera
  32935. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32936. _this.camera
  32937. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32938. }
  32939. else {
  32940. var offsetX = evt.clientX - cacheSoloPointer.x;
  32941. var offsetY = evt.clientY - cacheSoloPointer.y;
  32942. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32943. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32944. }
  32945. cacheSoloPointer.x = evt.clientX;
  32946. cacheSoloPointer.y = evt.clientY;
  32947. }
  32948. else if (pointA && pointB) {
  32949. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32950. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32951. ed.x = evt.clientX;
  32952. ed.y = evt.clientY;
  32953. var direction = _this.pinchInwards ? 1 : -1;
  32954. var distX = pointA.x - pointB.x;
  32955. var distY = pointA.y - pointB.y;
  32956. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32957. if (previousPinchDistance === 0) {
  32958. previousPinchDistance = pinchSquaredDistance;
  32959. return;
  32960. }
  32961. if (pinchSquaredDistance !== previousPinchDistance) {
  32962. _this.camera
  32963. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32964. (_this.pinchPrecision *
  32965. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32966. direction);
  32967. previousPinchDistance = pinchSquaredDistance;
  32968. }
  32969. }
  32970. }
  32971. };
  32972. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  32973. this._onContextMenu = function (evt) {
  32974. evt.preventDefault();
  32975. };
  32976. if (!this.camera._useCtrlForPanning) {
  32977. element.addEventListener("contextmenu", this._onContextMenu, false);
  32978. }
  32979. this._onLostFocus = function () {
  32980. //this._keys = [];
  32981. pointA = pointB = undefined;
  32982. previousPinchDistance = 0;
  32983. cacheSoloPointer = null;
  32984. };
  32985. this._onMouseMove = function (evt) {
  32986. if (!engine.isPointerLock) {
  32987. return;
  32988. }
  32989. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32990. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32991. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32992. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32993. if (!noPreventDefault) {
  32994. evt.preventDefault();
  32995. }
  32996. };
  32997. this._onGestureStart = function (e) {
  32998. if (window.MSGesture === undefined) {
  32999. return;
  33000. }
  33001. if (!_this._MSGestureHandler) {
  33002. _this._MSGestureHandler = new MSGesture();
  33003. _this._MSGestureHandler.target = element;
  33004. }
  33005. _this._MSGestureHandler.addPointer(e.pointerId);
  33006. };
  33007. this._onGesture = function (e) {
  33008. _this.camera.radius *= e.scale;
  33009. if (e.preventDefault) {
  33010. if (!noPreventDefault) {
  33011. e.stopPropagation();
  33012. e.preventDefault();
  33013. }
  33014. }
  33015. };
  33016. element.addEventListener("mousemove", this._onMouseMove, false);
  33017. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  33018. element.addEventListener("MSGestureChange", this._onGesture, false);
  33019. BABYLON.Tools.RegisterTopRootEvents([
  33020. { name: "blur", handler: this._onLostFocus }
  33021. ]);
  33022. };
  33023. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  33024. if (element && this._observer) {
  33025. this.camera.getScene().onPointerObservable.remove(this._observer);
  33026. this._observer = null;
  33027. element.removeEventListener("contextmenu", this._onContextMenu);
  33028. element.removeEventListener("mousemove", this._onMouseMove);
  33029. element.removeEventListener("MSPointerDown", this._onGestureStart);
  33030. element.removeEventListener("MSGestureChange", this._onGesture);
  33031. this._isPanClick = false;
  33032. this.pinchInwards = true;
  33033. this._onMouseMove = null;
  33034. this._onGestureStart = null;
  33035. this._onGesture = null;
  33036. this._MSGestureHandler = null;
  33037. this._onLostFocus = null;
  33038. this._onContextMenu = null;
  33039. }
  33040. BABYLON.Tools.UnregisterTopRootEvents([
  33041. { name: "blur", handler: this._onLostFocus }
  33042. ]);
  33043. };
  33044. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  33045. return "ArcRotateCameraPointersInput";
  33046. };
  33047. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  33048. return "pointers";
  33049. };
  33050. return ArcRotateCameraPointersInput;
  33051. }());
  33052. __decorate([
  33053. BABYLON.serialize()
  33054. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  33055. __decorate([
  33056. BABYLON.serialize()
  33057. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  33058. __decorate([
  33059. BABYLON.serialize()
  33060. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  33061. __decorate([
  33062. BABYLON.serialize()
  33063. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  33064. __decorate([
  33065. BABYLON.serialize()
  33066. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  33067. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  33068. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  33069. })(BABYLON || (BABYLON = {}));
  33070. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  33071. /// <reference path="babylon.targetCamera.ts" />
  33072. /// <reference path="..\Tools\babylon.tools.ts" />
  33073. var BABYLON;
  33074. (function (BABYLON) {
  33075. var ArcRotateCamera = (function (_super) {
  33076. __extends(ArcRotateCamera, _super);
  33077. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  33078. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  33079. _this.inertialAlphaOffset = 0;
  33080. _this.inertialBetaOffset = 0;
  33081. _this.inertialRadiusOffset = 0;
  33082. _this.lowerAlphaLimit = null;
  33083. _this.upperAlphaLimit = null;
  33084. _this.lowerBetaLimit = 0.01;
  33085. _this.upperBetaLimit = Math.PI;
  33086. _this.lowerRadiusLimit = null;
  33087. _this.upperRadiusLimit = null;
  33088. _this.inertialPanningX = 0;
  33089. _this.inertialPanningY = 0;
  33090. _this.panningInertia = 0.9;
  33091. //-- end properties for backward compatibility for inputs
  33092. _this.zoomOnFactor = 1;
  33093. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  33094. _this.allowUpsideDown = true;
  33095. _this._viewMatrix = new BABYLON.Matrix();
  33096. // Panning
  33097. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  33098. _this.checkCollisions = false;
  33099. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  33100. _this._previousPosition = BABYLON.Vector3.Zero();
  33101. _this._collisionVelocity = BABYLON.Vector3.Zero();
  33102. _this._newPosition = BABYLON.Vector3.Zero();
  33103. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  33104. if (collidedMesh === void 0) { collidedMesh = null; }
  33105. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  33106. newPosition.multiplyInPlace(_this._collider.radius);
  33107. }
  33108. if (!collidedMesh) {
  33109. _this._previousPosition.copyFrom(_this.position);
  33110. }
  33111. else {
  33112. _this.setPosition(newPosition);
  33113. if (_this.onCollide) {
  33114. _this.onCollide(collidedMesh);
  33115. }
  33116. }
  33117. // Recompute because of constraints
  33118. var cosa = Math.cos(_this.alpha);
  33119. var sina = Math.sin(_this.alpha);
  33120. var cosb = Math.cos(_this.beta);
  33121. var sinb = Math.sin(_this.beta);
  33122. if (sinb === 0) {
  33123. sinb = 0.0001;
  33124. }
  33125. var target = _this._getTargetPosition();
  33126. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  33127. _this.position.copyFrom(_this._newPosition);
  33128. var up = _this.upVector;
  33129. if (_this.allowUpsideDown && _this.beta < 0) {
  33130. up = up.clone();
  33131. up = up.negate();
  33132. }
  33133. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  33134. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  33135. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  33136. _this._collisionTriggered = false;
  33137. };
  33138. _this._target = BABYLON.Vector3.Zero();
  33139. if (target) {
  33140. _this.setTarget(target);
  33141. }
  33142. _this.alpha = alpha;
  33143. _this.beta = beta;
  33144. _this.radius = radius;
  33145. _this.getViewMatrix();
  33146. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  33147. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  33148. return _this;
  33149. }
  33150. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  33151. get: function () {
  33152. return this._target;
  33153. },
  33154. set: function (value) {
  33155. this.setTarget(value);
  33156. },
  33157. enumerable: true,
  33158. configurable: true
  33159. });
  33160. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  33161. //-- begin properties for backward compatibility for inputs
  33162. get: function () {
  33163. var pointers = this.inputs.attached["pointers"];
  33164. if (pointers)
  33165. return pointers.angularSensibilityX;
  33166. },
  33167. set: function (value) {
  33168. var pointers = this.inputs.attached["pointers"];
  33169. if (pointers) {
  33170. pointers.angularSensibilityX = value;
  33171. }
  33172. },
  33173. enumerable: true,
  33174. configurable: true
  33175. });
  33176. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  33177. get: function () {
  33178. var pointers = this.inputs.attached["pointers"];
  33179. if (pointers)
  33180. return pointers.angularSensibilityY;
  33181. },
  33182. set: function (value) {
  33183. var pointers = this.inputs.attached["pointers"];
  33184. if (pointers) {
  33185. pointers.angularSensibilityY = value;
  33186. }
  33187. },
  33188. enumerable: true,
  33189. configurable: true
  33190. });
  33191. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  33192. get: function () {
  33193. var pointers = this.inputs.attached["pointers"];
  33194. if (pointers)
  33195. return pointers.pinchPrecision;
  33196. },
  33197. set: function (value) {
  33198. var pointers = this.inputs.attached["pointers"];
  33199. if (pointers) {
  33200. pointers.pinchPrecision = value;
  33201. }
  33202. },
  33203. enumerable: true,
  33204. configurable: true
  33205. });
  33206. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  33207. get: function () {
  33208. var pointers = this.inputs.attached["pointers"];
  33209. if (pointers)
  33210. return pointers.panningSensibility;
  33211. },
  33212. set: function (value) {
  33213. var pointers = this.inputs.attached["pointers"];
  33214. if (pointers) {
  33215. pointers.panningSensibility = value;
  33216. }
  33217. },
  33218. enumerable: true,
  33219. configurable: true
  33220. });
  33221. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  33222. get: function () {
  33223. var keyboard = this.inputs.attached["keyboard"];
  33224. if (keyboard)
  33225. return keyboard.keysUp;
  33226. },
  33227. set: function (value) {
  33228. var keyboard = this.inputs.attached["keyboard"];
  33229. if (keyboard)
  33230. keyboard.keysUp = value;
  33231. },
  33232. enumerable: true,
  33233. configurable: true
  33234. });
  33235. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  33236. get: function () {
  33237. var keyboard = this.inputs.attached["keyboard"];
  33238. if (keyboard)
  33239. return keyboard.keysDown;
  33240. },
  33241. set: function (value) {
  33242. var keyboard = this.inputs.attached["keyboard"];
  33243. if (keyboard)
  33244. keyboard.keysDown = value;
  33245. },
  33246. enumerable: true,
  33247. configurable: true
  33248. });
  33249. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  33250. get: function () {
  33251. var keyboard = this.inputs.attached["keyboard"];
  33252. if (keyboard)
  33253. return keyboard.keysLeft;
  33254. },
  33255. set: function (value) {
  33256. var keyboard = this.inputs.attached["keyboard"];
  33257. if (keyboard)
  33258. keyboard.keysLeft = value;
  33259. },
  33260. enumerable: true,
  33261. configurable: true
  33262. });
  33263. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  33264. get: function () {
  33265. var keyboard = this.inputs.attached["keyboard"];
  33266. if (keyboard)
  33267. return keyboard.keysRight;
  33268. },
  33269. set: function (value) {
  33270. var keyboard = this.inputs.attached["keyboard"];
  33271. if (keyboard)
  33272. keyboard.keysRight = value;
  33273. },
  33274. enumerable: true,
  33275. configurable: true
  33276. });
  33277. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  33278. get: function () {
  33279. var mousewheel = this.inputs.attached["mousewheel"];
  33280. if (mousewheel)
  33281. return mousewheel.wheelPrecision;
  33282. },
  33283. set: function (value) {
  33284. var mousewheel = this.inputs.attached["mousewheel"];
  33285. if (mousewheel)
  33286. mousewheel.wheelPrecision = value;
  33287. },
  33288. enumerable: true,
  33289. configurable: true
  33290. });
  33291. // Cache
  33292. ArcRotateCamera.prototype._initCache = function () {
  33293. _super.prototype._initCache.call(this);
  33294. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33295. this._cache.alpha = undefined;
  33296. this._cache.beta = undefined;
  33297. this._cache.radius = undefined;
  33298. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  33299. };
  33300. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  33301. if (!ignoreParentClass) {
  33302. _super.prototype._updateCache.call(this);
  33303. }
  33304. this._cache._target.copyFrom(this._getTargetPosition());
  33305. this._cache.alpha = this.alpha;
  33306. this._cache.beta = this.beta;
  33307. this._cache.radius = this.radius;
  33308. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  33309. };
  33310. ArcRotateCamera.prototype._getTargetPosition = function () {
  33311. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  33312. var pos = this._targetHost.getAbsolutePosition();
  33313. if (this._targetBoundingCenter) {
  33314. pos.addToRef(this._targetBoundingCenter, this._target);
  33315. }
  33316. else {
  33317. this._target.copyFrom(pos);
  33318. }
  33319. }
  33320. var lockedTargetPosition = this._getLockedTargetPosition();
  33321. if (lockedTargetPosition) {
  33322. return lockedTargetPosition;
  33323. }
  33324. return this._target;
  33325. };
  33326. // Synchronized
  33327. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  33328. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  33329. return false;
  33330. return this._cache._target.equals(this._getTargetPosition())
  33331. && this._cache.alpha === this.alpha
  33332. && this._cache.beta === this.beta
  33333. && this._cache.radius === this.radius
  33334. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  33335. };
  33336. // Methods
  33337. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  33338. var _this = this;
  33339. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  33340. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  33341. this._useCtrlForPanning = useCtrlForPanning;
  33342. this._panningMouseButton = panningMouseButton;
  33343. this.inputs.attachElement(element, noPreventDefault);
  33344. this._reset = function () {
  33345. _this.inertialAlphaOffset = 0;
  33346. _this.inertialBetaOffset = 0;
  33347. _this.inertialRadiusOffset = 0;
  33348. };
  33349. };
  33350. ArcRotateCamera.prototype.detachControl = function (element) {
  33351. this.inputs.detachElement(element);
  33352. if (this._reset) {
  33353. this._reset();
  33354. }
  33355. };
  33356. ArcRotateCamera.prototype._checkInputs = function () {
  33357. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  33358. if (this._collisionTriggered) {
  33359. return;
  33360. }
  33361. this.inputs.checkInputs();
  33362. // Inertia
  33363. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  33364. if (this.getScene().useRightHandedSystem) {
  33365. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  33366. }
  33367. else {
  33368. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  33369. }
  33370. this.beta += this.inertialBetaOffset;
  33371. this.radius -= this.inertialRadiusOffset;
  33372. this.inertialAlphaOffset *= this.inertia;
  33373. this.inertialBetaOffset *= this.inertia;
  33374. this.inertialRadiusOffset *= this.inertia;
  33375. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  33376. this.inertialAlphaOffset = 0;
  33377. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  33378. this.inertialBetaOffset = 0;
  33379. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  33380. this.inertialRadiusOffset = 0;
  33381. }
  33382. // Panning inertia
  33383. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  33384. if (!this._localDirection) {
  33385. this._localDirection = BABYLON.Vector3.Zero();
  33386. this._transformedDirection = BABYLON.Vector3.Zero();
  33387. }
  33388. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  33389. this._localDirection.multiplyInPlace(this.panningAxis);
  33390. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  33391. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  33392. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  33393. if (!this.panningAxis.y) {
  33394. this._transformedDirection.y = 0;
  33395. }
  33396. if (!this._targetHost) {
  33397. this._target.addInPlace(this._transformedDirection);
  33398. }
  33399. this.inertialPanningX *= this.panningInertia;
  33400. this.inertialPanningY *= this.panningInertia;
  33401. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  33402. this.inertialPanningX = 0;
  33403. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  33404. this.inertialPanningY = 0;
  33405. }
  33406. // Limits
  33407. this._checkLimits();
  33408. _super.prototype._checkInputs.call(this);
  33409. };
  33410. ArcRotateCamera.prototype._checkLimits = function () {
  33411. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  33412. if (this.allowUpsideDown && this.beta > Math.PI) {
  33413. this.beta = this.beta - (2 * Math.PI);
  33414. }
  33415. }
  33416. else {
  33417. if (this.beta < this.lowerBetaLimit) {
  33418. this.beta = this.lowerBetaLimit;
  33419. }
  33420. }
  33421. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  33422. if (this.allowUpsideDown && this.beta < -Math.PI) {
  33423. this.beta = this.beta + (2 * Math.PI);
  33424. }
  33425. }
  33426. else {
  33427. if (this.beta > this.upperBetaLimit) {
  33428. this.beta = this.upperBetaLimit;
  33429. }
  33430. }
  33431. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  33432. this.alpha = this.lowerAlphaLimit;
  33433. }
  33434. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  33435. this.alpha = this.upperAlphaLimit;
  33436. }
  33437. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  33438. this.radius = this.lowerRadiusLimit;
  33439. }
  33440. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  33441. this.radius = this.upperRadiusLimit;
  33442. }
  33443. };
  33444. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  33445. var radiusv3 = this.position.subtract(this._getTargetPosition());
  33446. this.radius = radiusv3.length();
  33447. // Alpha
  33448. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  33449. if (radiusv3.z < 0) {
  33450. this.alpha = 2 * Math.PI - this.alpha;
  33451. }
  33452. // Beta
  33453. this.beta = Math.acos(radiusv3.y / this.radius);
  33454. this._checkLimits();
  33455. };
  33456. ArcRotateCamera.prototype.setPosition = function (position) {
  33457. if (this.position.equals(position)) {
  33458. return;
  33459. }
  33460. this.position.copyFrom(position);
  33461. this.rebuildAnglesAndRadius();
  33462. };
  33463. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  33464. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  33465. if (allowSamePosition === void 0) { allowSamePosition = false; }
  33466. if (target.getBoundingInfo) {
  33467. if (toBoundingCenter) {
  33468. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  33469. }
  33470. else {
  33471. this._targetBoundingCenter = null;
  33472. }
  33473. this._targetHost = target;
  33474. this._target = this._getTargetPosition();
  33475. }
  33476. else {
  33477. var newTarget = target;
  33478. var currentTarget = this._getTargetPosition();
  33479. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  33480. return;
  33481. }
  33482. this._target = newTarget;
  33483. this._targetBoundingCenter = null;
  33484. }
  33485. this.rebuildAnglesAndRadius();
  33486. };
  33487. ArcRotateCamera.prototype._getViewMatrix = function () {
  33488. // Compute
  33489. var cosa = Math.cos(this.alpha);
  33490. var sina = Math.sin(this.alpha);
  33491. var cosb = Math.cos(this.beta);
  33492. var sinb = Math.sin(this.beta);
  33493. if (sinb === 0) {
  33494. sinb = 0.0001;
  33495. }
  33496. var target = this._getTargetPosition();
  33497. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  33498. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  33499. if (!this._collider) {
  33500. this._collider = new BABYLON.Collider();
  33501. }
  33502. this._collider.radius = this.collisionRadius;
  33503. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  33504. this._collisionTriggered = true;
  33505. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  33506. }
  33507. else {
  33508. this.position.copyFrom(this._newPosition);
  33509. var up = this.upVector;
  33510. if (this.allowUpsideDown && sinb < 0) {
  33511. up = up.clone();
  33512. up = up.negate();
  33513. }
  33514. if (this.getScene().useRightHandedSystem) {
  33515. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  33516. }
  33517. else {
  33518. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  33519. }
  33520. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  33521. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  33522. }
  33523. this._currentTarget = target;
  33524. return this._viewMatrix;
  33525. };
  33526. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  33527. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33528. meshes = meshes || this.getScene().meshes;
  33529. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  33530. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  33531. this.radius = distance * this.zoomOnFactor;
  33532. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  33533. };
  33534. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  33535. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33536. var meshesOrMinMaxVector;
  33537. var distance;
  33538. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  33539. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  33540. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  33541. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  33542. }
  33543. else {
  33544. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  33545. distance = meshesOrMinMaxVectorAndDistance.distance;
  33546. }
  33547. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  33548. if (!doNotUpdateMaxZ) {
  33549. this.maxZ = distance * 2;
  33550. }
  33551. };
  33552. /**
  33553. * @override
  33554. * Override Camera.createRigCamera
  33555. */
  33556. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  33557. var alphaShift;
  33558. switch (this.cameraRigMode) {
  33559. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33560. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33561. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33562. case BABYLON.Camera.RIG_MODE_VR:
  33563. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  33564. break;
  33565. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33566. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  33567. break;
  33568. }
  33569. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  33570. rigCam._cameraRigParams = {};
  33571. return rigCam;
  33572. };
  33573. /**
  33574. * @override
  33575. * Override Camera._updateRigCameras
  33576. */
  33577. ArcRotateCamera.prototype._updateRigCameras = function () {
  33578. var camLeft = this._rigCameras[0];
  33579. var camRight = this._rigCameras[1];
  33580. camLeft.beta = camRight.beta = this.beta;
  33581. camLeft.radius = camRight.radius = this.radius;
  33582. switch (this.cameraRigMode) {
  33583. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33584. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33585. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33586. case BABYLON.Camera.RIG_MODE_VR:
  33587. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33588. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33589. break;
  33590. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33591. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33592. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33593. break;
  33594. }
  33595. _super.prototype._updateRigCameras.call(this);
  33596. };
  33597. ArcRotateCamera.prototype.dispose = function () {
  33598. this.inputs.clear();
  33599. _super.prototype.dispose.call(this);
  33600. };
  33601. ArcRotateCamera.prototype.getClassName = function () {
  33602. return "ArcRotateCamera";
  33603. };
  33604. return ArcRotateCamera;
  33605. }(BABYLON.TargetCamera));
  33606. __decorate([
  33607. BABYLON.serialize()
  33608. ], ArcRotateCamera.prototype, "alpha", void 0);
  33609. __decorate([
  33610. BABYLON.serialize()
  33611. ], ArcRotateCamera.prototype, "beta", void 0);
  33612. __decorate([
  33613. BABYLON.serialize()
  33614. ], ArcRotateCamera.prototype, "radius", void 0);
  33615. __decorate([
  33616. BABYLON.serializeAsVector3("target")
  33617. ], ArcRotateCamera.prototype, "_target", void 0);
  33618. __decorate([
  33619. BABYLON.serialize()
  33620. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  33621. __decorate([
  33622. BABYLON.serialize()
  33623. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  33624. __decorate([
  33625. BABYLON.serialize()
  33626. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  33627. __decorate([
  33628. BABYLON.serialize()
  33629. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  33630. __decorate([
  33631. BABYLON.serialize()
  33632. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  33633. __decorate([
  33634. BABYLON.serialize()
  33635. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  33636. __decorate([
  33637. BABYLON.serialize()
  33638. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  33639. __decorate([
  33640. BABYLON.serialize()
  33641. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  33642. __decorate([
  33643. BABYLON.serialize()
  33644. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  33645. __decorate([
  33646. BABYLON.serialize()
  33647. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  33648. __decorate([
  33649. BABYLON.serialize()
  33650. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  33651. __decorate([
  33652. BABYLON.serialize()
  33653. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  33654. __decorate([
  33655. BABYLON.serialize()
  33656. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  33657. __decorate([
  33658. BABYLON.serialize()
  33659. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  33660. BABYLON.ArcRotateCamera = ArcRotateCamera;
  33661. })(BABYLON || (BABYLON = {}));
  33662. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  33663. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  33664. var BABYLON;
  33665. (function (BABYLON) {
  33666. var ArcRotateCameraInputsManager = (function (_super) {
  33667. __extends(ArcRotateCameraInputsManager, _super);
  33668. function ArcRotateCameraInputsManager(camera) {
  33669. return _super.call(this, camera) || this;
  33670. }
  33671. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  33672. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  33673. return this;
  33674. };
  33675. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  33676. this.add(new BABYLON.ArcRotateCameraPointersInput());
  33677. return this;
  33678. };
  33679. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  33680. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  33681. return this;
  33682. };
  33683. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  33684. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  33685. return this;
  33686. };
  33687. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  33688. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  33689. return this;
  33690. };
  33691. return ArcRotateCameraInputsManager;
  33692. }(BABYLON.CameraInputsManager));
  33693. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  33694. })(BABYLON || (BABYLON = {}));
  33695. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  33696. var BABYLON;
  33697. (function (BABYLON) {
  33698. var HemisphericLight = (function (_super) {
  33699. __extends(HemisphericLight, _super);
  33700. /**
  33701. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  33702. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  33703. * The HemisphericLight can't cast shadows.
  33704. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33705. */
  33706. function HemisphericLight(name, direction, scene) {
  33707. var _this = _super.call(this, name, scene) || this;
  33708. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  33709. _this.direction = direction || BABYLON.Vector3.Up();
  33710. return _this;
  33711. }
  33712. HemisphericLight.prototype._buildUniformLayout = function () {
  33713. this._uniformBuffer.addUniform("vLightData", 4);
  33714. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33715. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33716. this._uniformBuffer.addUniform("vLightGround", 3);
  33717. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33718. this._uniformBuffer.addUniform("depthValues", 2);
  33719. this._uniformBuffer.create();
  33720. };
  33721. /**
  33722. * Returns the string "HemisphericLight".
  33723. */
  33724. HemisphericLight.prototype.getClassName = function () {
  33725. return "HemisphericLight";
  33726. };
  33727. /**
  33728. * Sets the HemisphericLight direction towards the passed target (Vector3).
  33729. * Returns the updated direction.
  33730. */
  33731. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  33732. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  33733. return this.direction;
  33734. };
  33735. HemisphericLight.prototype.getShadowGenerator = function () {
  33736. return null;
  33737. };
  33738. /**
  33739. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  33740. * Returns the HemisphericLight.
  33741. */
  33742. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  33743. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33744. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  33745. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  33746. return this;
  33747. };
  33748. HemisphericLight.prototype._getWorldMatrix = function () {
  33749. if (!this._worldMatrix) {
  33750. this._worldMatrix = BABYLON.Matrix.Identity();
  33751. }
  33752. return this._worldMatrix;
  33753. };
  33754. /**
  33755. * Returns the integer 3.
  33756. */
  33757. HemisphericLight.prototype.getTypeID = function () {
  33758. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  33759. };
  33760. return HemisphericLight;
  33761. }(BABYLON.Light));
  33762. __decorate([
  33763. BABYLON.serializeAsColor3()
  33764. ], HemisphericLight.prototype, "groundColor", void 0);
  33765. __decorate([
  33766. BABYLON.serializeAsVector3()
  33767. ], HemisphericLight.prototype, "direction", void 0);
  33768. BABYLON.HemisphericLight = HemisphericLight;
  33769. })(BABYLON || (BABYLON = {}));
  33770. //# sourceMappingURL=babylon.hemisphericLight.js.map
  33771. var BABYLON;
  33772. (function (BABYLON) {
  33773. var ShadowLight = (function (_super) {
  33774. __extends(ShadowLight, _super);
  33775. function ShadowLight() {
  33776. var _this = _super !== null && _super.apply(this, arguments) || this;
  33777. _this._needProjectionMatrixCompute = true;
  33778. return _this;
  33779. }
  33780. Object.defineProperty(ShadowLight.prototype, "direction", {
  33781. get: function () {
  33782. return this._direction;
  33783. },
  33784. set: function (value) {
  33785. this._direction = value;
  33786. },
  33787. enumerable: true,
  33788. configurable: true
  33789. });
  33790. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33791. get: function () {
  33792. return this._shadowMinZ;
  33793. },
  33794. set: function (value) {
  33795. this._shadowMinZ = value;
  33796. this.forceProjectionMatrixCompute();
  33797. },
  33798. enumerable: true,
  33799. configurable: true
  33800. });
  33801. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33802. get: function () {
  33803. return this._shadowMaxZ;
  33804. },
  33805. set: function (value) {
  33806. this._shadowMaxZ = value;
  33807. this.forceProjectionMatrixCompute();
  33808. },
  33809. enumerable: true,
  33810. configurable: true
  33811. });
  33812. /**
  33813. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33814. */
  33815. ShadowLight.prototype.computeTransformedInformation = function () {
  33816. if (this.parent && this.parent.getWorldMatrix) {
  33817. if (!this.transformedPosition) {
  33818. this.transformedPosition = BABYLON.Vector3.Zero();
  33819. }
  33820. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33821. // In case the direction is present.
  33822. if (this.direction) {
  33823. if (!this.transformedDirection) {
  33824. this.transformedDirection = BABYLON.Vector3.Zero();
  33825. }
  33826. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33827. }
  33828. return true;
  33829. }
  33830. return false;
  33831. };
  33832. /**
  33833. * Return the depth scale used for the shadow map.
  33834. */
  33835. ShadowLight.prototype.getDepthScale = function () {
  33836. return 50.0;
  33837. };
  33838. /**
  33839. * Returns the light direction (Vector3) for any passed face index.
  33840. */
  33841. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33842. return this.transformedDirection ? this.transformedDirection : this.direction;
  33843. };
  33844. /**
  33845. * Returns the DirectionalLight absolute position in the World.
  33846. */
  33847. ShadowLight.prototype.getAbsolutePosition = function () {
  33848. return this.transformedPosition ? this.transformedPosition : this.position;
  33849. };
  33850. /**
  33851. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33852. * Returns the updated DirectionalLight direction (Vector3).
  33853. */
  33854. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33855. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33856. return this.direction;
  33857. };
  33858. /**
  33859. * Returns the light rotation (Vector3).
  33860. */
  33861. ShadowLight.prototype.getRotation = function () {
  33862. this.direction.normalize();
  33863. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33864. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33865. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33866. };
  33867. /**
  33868. * Boolean : false by default.
  33869. */
  33870. ShadowLight.prototype.needCube = function () {
  33871. return false;
  33872. };
  33873. /**
  33874. * Specifies wether or not the projection matrix should be recomputed this frame.
  33875. */
  33876. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33877. return this._needProjectionMatrixCompute;
  33878. };
  33879. /**
  33880. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33881. */
  33882. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33883. this._needProjectionMatrixCompute = true;
  33884. };
  33885. /**
  33886. * Get the world matrix of the sahdow lights.
  33887. */
  33888. ShadowLight.prototype._getWorldMatrix = function () {
  33889. if (!this._worldMatrix) {
  33890. this._worldMatrix = BABYLON.Matrix.Identity();
  33891. }
  33892. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33893. return this._worldMatrix;
  33894. };
  33895. /**
  33896. * Gets the minZ used for shadow according to both the scene and the light.
  33897. * @param activeCamera
  33898. */
  33899. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  33900. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  33901. };
  33902. /**
  33903. * Gets the maxZ used for shadow according to both the scene and the light.
  33904. * @param activeCamera
  33905. */
  33906. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  33907. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  33908. };
  33909. /**
  33910. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  33911. * Returns the light.
  33912. */
  33913. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33914. if (this.customProjectionMatrixBuilder) {
  33915. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  33916. }
  33917. else {
  33918. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33919. }
  33920. return this;
  33921. };
  33922. return ShadowLight;
  33923. }(BABYLON.Light));
  33924. __decorate([
  33925. BABYLON.serializeAsVector3()
  33926. ], ShadowLight.prototype, "position", void 0);
  33927. __decorate([
  33928. BABYLON.serializeAsVector3()
  33929. ], ShadowLight.prototype, "direction", null);
  33930. __decorate([
  33931. BABYLON.serialize()
  33932. ], ShadowLight.prototype, "shadowMinZ", null);
  33933. __decorate([
  33934. BABYLON.serialize()
  33935. ], ShadowLight.prototype, "shadowMaxZ", null);
  33936. BABYLON.ShadowLight = ShadowLight;
  33937. })(BABYLON || (BABYLON = {}));
  33938. //# sourceMappingURL=babylon.shadowLight.js.map
  33939. var BABYLON;
  33940. (function (BABYLON) {
  33941. var PointLight = (function (_super) {
  33942. __extends(PointLight, _super);
  33943. /**
  33944. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  33945. * A PointLight emits the light in every direction.
  33946. * It can cast shadows.
  33947. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  33948. * ```javascript
  33949. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  33950. * ```
  33951. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33952. */
  33953. function PointLight(name, position, scene) {
  33954. var _this = _super.call(this, name, scene) || this;
  33955. _this._shadowAngle = Math.PI / 2;
  33956. _this.position = position;
  33957. return _this;
  33958. }
  33959. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  33960. /**
  33961. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33962. * This specifies what angle the shadow will use to be created.
  33963. *
  33964. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33965. */
  33966. get: function () {
  33967. return this._shadowAngle;
  33968. },
  33969. /**
  33970. * Setter: 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. set: function (value) {
  33976. this._shadowAngle = value;
  33977. this.forceProjectionMatrixCompute();
  33978. },
  33979. enumerable: true,
  33980. configurable: true
  33981. });
  33982. Object.defineProperty(PointLight.prototype, "direction", {
  33983. get: function () {
  33984. return this._direction;
  33985. },
  33986. /**
  33987. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33988. */
  33989. set: function (value) {
  33990. var previousNeedCube = this.needCube();
  33991. this._direction = value;
  33992. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  33993. this._shadowGenerator.recreateShadowMap();
  33994. }
  33995. },
  33996. enumerable: true,
  33997. configurable: true
  33998. });
  33999. /**
  34000. * Returns the string "PointLight"
  34001. */
  34002. PointLight.prototype.getClassName = function () {
  34003. return "PointLight";
  34004. };
  34005. /**
  34006. * Returns the integer 0.
  34007. */
  34008. PointLight.prototype.getTypeID = function () {
  34009. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  34010. };
  34011. /**
  34012. * Specifies wether or not the shadowmap should be a cube texture.
  34013. */
  34014. PointLight.prototype.needCube = function () {
  34015. return !this.direction;
  34016. };
  34017. /**
  34018. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  34019. */
  34020. PointLight.prototype.getShadowDirection = function (faceIndex) {
  34021. if (this.direction) {
  34022. return _super.prototype.getShadowDirection.call(this, faceIndex);
  34023. }
  34024. else {
  34025. switch (faceIndex) {
  34026. case 0:
  34027. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  34028. case 1:
  34029. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  34030. case 2:
  34031. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  34032. case 3:
  34033. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  34034. case 4:
  34035. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  34036. case 5:
  34037. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  34038. }
  34039. }
  34040. return BABYLON.Vector3.Zero();
  34041. };
  34042. /**
  34043. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  34044. * - fov = PI / 2
  34045. * - aspect ratio : 1.0
  34046. * - z-near and far equal to the active camera minZ and maxZ.
  34047. * Returns the PointLight.
  34048. */
  34049. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34050. var activeCamera = this.getScene().activeCamera;
  34051. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34052. };
  34053. PointLight.prototype._buildUniformLayout = function () {
  34054. this._uniformBuffer.addUniform("vLightData", 4);
  34055. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34056. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34057. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34058. this._uniformBuffer.addUniform("depthValues", 2);
  34059. this._uniformBuffer.create();
  34060. };
  34061. /**
  34062. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  34063. * Returns the PointLight.
  34064. */
  34065. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  34066. if (this.computeTransformedInformation()) {
  34067. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  34068. return this;
  34069. }
  34070. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  34071. return this;
  34072. };
  34073. return PointLight;
  34074. }(BABYLON.ShadowLight));
  34075. __decorate([
  34076. BABYLON.serialize()
  34077. ], PointLight.prototype, "shadowAngle", null);
  34078. BABYLON.PointLight = PointLight;
  34079. })(BABYLON || (BABYLON = {}));
  34080. //# sourceMappingURL=babylon.pointLight.js.map
  34081. /// <reference path="babylon.light.ts" />
  34082. var BABYLON;
  34083. (function (BABYLON) {
  34084. var DirectionalLight = (function (_super) {
  34085. __extends(DirectionalLight, _super);
  34086. /**
  34087. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  34088. * The directional light is emitted from everywhere in the given direction.
  34089. * It can cast shawdows.
  34090. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34091. */
  34092. function DirectionalLight(name, direction, scene) {
  34093. var _this = _super.call(this, name, scene) || this;
  34094. _this._shadowFrustumSize = 0;
  34095. _this._shadowOrthoScale = 0.5;
  34096. _this.autoUpdateExtends = true;
  34097. // Cache
  34098. _this._orthoLeft = Number.MAX_VALUE;
  34099. _this._orthoRight = Number.MIN_VALUE;
  34100. _this._orthoTop = Number.MIN_VALUE;
  34101. _this._orthoBottom = Number.MAX_VALUE;
  34102. _this.position = direction.scale(-1.0);
  34103. _this.direction = direction;
  34104. return _this;
  34105. }
  34106. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  34107. /**
  34108. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  34109. */
  34110. get: function () {
  34111. return this._shadowFrustumSize;
  34112. },
  34113. /**
  34114. * Specifies a fix frustum size for the shadow generation.
  34115. */
  34116. set: function (value) {
  34117. this._shadowFrustumSize = value;
  34118. this.forceProjectionMatrixCompute();
  34119. },
  34120. enumerable: true,
  34121. configurable: true
  34122. });
  34123. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  34124. get: function () {
  34125. return this._shadowOrthoScale;
  34126. },
  34127. set: function (value) {
  34128. this._shadowOrthoScale = value;
  34129. this.forceProjectionMatrixCompute();
  34130. },
  34131. enumerable: true,
  34132. configurable: true
  34133. });
  34134. /**
  34135. * Returns the string "DirectionalLight".
  34136. */
  34137. DirectionalLight.prototype.getClassName = function () {
  34138. return "DirectionalLight";
  34139. };
  34140. /**
  34141. * Returns the integer 1.
  34142. */
  34143. DirectionalLight.prototype.getTypeID = function () {
  34144. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  34145. };
  34146. /**
  34147. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  34148. * Returns the DirectionalLight Shadow projection matrix.
  34149. */
  34150. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34151. if (this.shadowFrustumSize > 0) {
  34152. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  34153. }
  34154. else {
  34155. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34156. }
  34157. };
  34158. /**
  34159. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  34160. * Returns the DirectionalLight Shadow projection matrix.
  34161. */
  34162. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  34163. var activeCamera = this.getScene().activeCamera;
  34164. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  34165. };
  34166. /**
  34167. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  34168. * Returns the DirectionalLight Shadow projection matrix.
  34169. */
  34170. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34171. var activeCamera = this.getScene().activeCamera;
  34172. // Check extends
  34173. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  34174. var tempVector3 = BABYLON.Vector3.Zero();
  34175. this._orthoLeft = Number.MAX_VALUE;
  34176. this._orthoRight = Number.MIN_VALUE;
  34177. this._orthoTop = Number.MIN_VALUE;
  34178. this._orthoBottom = Number.MAX_VALUE;
  34179. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  34180. var mesh = renderList[meshIndex];
  34181. if (!mesh) {
  34182. continue;
  34183. }
  34184. var boundingInfo = mesh.getBoundingInfo();
  34185. if (!boundingInfo) {
  34186. continue;
  34187. }
  34188. var boundingBox = boundingInfo.boundingBox;
  34189. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  34190. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  34191. if (tempVector3.x < this._orthoLeft)
  34192. this._orthoLeft = tempVector3.x;
  34193. if (tempVector3.y < this._orthoBottom)
  34194. this._orthoBottom = tempVector3.y;
  34195. if (tempVector3.x > this._orthoRight)
  34196. this._orthoRight = tempVector3.x;
  34197. if (tempVector3.y > this._orthoTop)
  34198. this._orthoTop = tempVector3.y;
  34199. }
  34200. }
  34201. }
  34202. var xOffset = this._orthoRight - this._orthoLeft;
  34203. var yOffset = this._orthoTop - this._orthoBottom;
  34204. 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);
  34205. };
  34206. DirectionalLight.prototype._buildUniformLayout = function () {
  34207. this._uniformBuffer.addUniform("vLightData", 4);
  34208. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34209. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34210. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34211. this._uniformBuffer.addUniform("depthValues", 2);
  34212. this._uniformBuffer.create();
  34213. };
  34214. /**
  34215. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  34216. * Returns the DirectionalLight.
  34217. */
  34218. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  34219. if (this.computeTransformedInformation()) {
  34220. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  34221. return this;
  34222. }
  34223. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  34224. return this;
  34225. };
  34226. /**
  34227. * Gets the minZ used for shadow according to both the scene and the light.
  34228. *
  34229. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34230. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34231. * @param activeCamera
  34232. */
  34233. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  34234. return 1;
  34235. };
  34236. /**
  34237. * Gets the maxZ used for shadow according to both the scene and the light.
  34238. *
  34239. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34240. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34241. * @param activeCamera
  34242. */
  34243. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  34244. return 1;
  34245. };
  34246. return DirectionalLight;
  34247. }(BABYLON.ShadowLight));
  34248. __decorate([
  34249. BABYLON.serialize()
  34250. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  34251. __decorate([
  34252. BABYLON.serialize()
  34253. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  34254. __decorate([
  34255. BABYLON.serialize()
  34256. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  34257. BABYLON.DirectionalLight = DirectionalLight;
  34258. })(BABYLON || (BABYLON = {}));
  34259. //# sourceMappingURL=babylon.directionalLight.js.map
  34260. var BABYLON;
  34261. (function (BABYLON) {
  34262. var SpotLight = (function (_super) {
  34263. __extends(SpotLight, _super);
  34264. /**
  34265. * Creates a SpotLight object in the scene with the passed parameters :
  34266. * - `position` (Vector3) is the initial SpotLight position,
  34267. * - `direction` (Vector3) is the initial SpotLight direction,
  34268. * - `angle` (float, in radians) is the spot light cone angle,
  34269. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  34270. * A spot light is a simply light oriented cone.
  34271. * It can cast shadows.
  34272. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34273. */
  34274. function SpotLight(name, position, direction, angle, exponent, scene) {
  34275. var _this = _super.call(this, name, scene) || this;
  34276. _this.position = position;
  34277. _this.direction = direction;
  34278. _this.angle = angle;
  34279. _this.exponent = exponent;
  34280. return _this;
  34281. }
  34282. Object.defineProperty(SpotLight.prototype, "angle", {
  34283. get: function () {
  34284. return this._angle;
  34285. },
  34286. set: function (value) {
  34287. this._angle = value;
  34288. this.forceProjectionMatrixCompute();
  34289. },
  34290. enumerable: true,
  34291. configurable: true
  34292. });
  34293. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  34294. get: function () {
  34295. return this._shadowAngleScale;
  34296. },
  34297. /**
  34298. * Allows scaling the angle of the light for shadow generation only.
  34299. */
  34300. set: function (value) {
  34301. this._shadowAngleScale = value;
  34302. this.forceProjectionMatrixCompute();
  34303. },
  34304. enumerable: true,
  34305. configurable: true
  34306. });
  34307. /**
  34308. * Returns the string "SpotLight".
  34309. */
  34310. SpotLight.prototype.getClassName = function () {
  34311. return "SpotLight";
  34312. };
  34313. /**
  34314. * Returns the integer 2.
  34315. */
  34316. SpotLight.prototype.getTypeID = function () {
  34317. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  34318. };
  34319. /**
  34320. * 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.
  34321. * Returns the SpotLight.
  34322. */
  34323. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34324. var activeCamera = this.getScene().activeCamera;
  34325. this._shadowAngleScale = this._shadowAngleScale || 1;
  34326. var angle = this._shadowAngleScale * this._angle;
  34327. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34328. };
  34329. SpotLight.prototype._buildUniformLayout = function () {
  34330. this._uniformBuffer.addUniform("vLightData", 4);
  34331. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34332. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34333. this._uniformBuffer.addUniform("vLightDirection", 3);
  34334. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34335. this._uniformBuffer.addUniform("depthValues", 2);
  34336. this._uniformBuffer.create();
  34337. };
  34338. /**
  34339. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  34340. * Return the SpotLight.
  34341. */
  34342. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  34343. var normalizeDirection;
  34344. if (this.computeTransformedInformation()) {
  34345. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  34346. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  34347. }
  34348. else {
  34349. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  34350. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34351. }
  34352. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  34353. return this;
  34354. };
  34355. return SpotLight;
  34356. }(BABYLON.ShadowLight));
  34357. __decorate([
  34358. BABYLON.serialize()
  34359. ], SpotLight.prototype, "angle", null);
  34360. __decorate([
  34361. BABYLON.serialize()
  34362. /**
  34363. * Allows scaling the angle of the light for shadow generation only.
  34364. */
  34365. ], SpotLight.prototype, "shadowAngleScale", null);
  34366. __decorate([
  34367. BABYLON.serialize()
  34368. ], SpotLight.prototype, "exponent", void 0);
  34369. BABYLON.SpotLight = SpotLight;
  34370. })(BABYLON || (BABYLON = {}));
  34371. //# sourceMappingURL=babylon.spotLight.js.map
  34372. var BABYLON;
  34373. (function (BABYLON) {
  34374. var AnimationRange = (function () {
  34375. function AnimationRange(name, from, to) {
  34376. this.name = name;
  34377. this.from = from;
  34378. this.to = to;
  34379. }
  34380. AnimationRange.prototype.clone = function () {
  34381. return new AnimationRange(this.name, this.from, this.to);
  34382. };
  34383. return AnimationRange;
  34384. }());
  34385. BABYLON.AnimationRange = AnimationRange;
  34386. /**
  34387. * Composed of a frame, and an action function
  34388. */
  34389. var AnimationEvent = (function () {
  34390. function AnimationEvent(frame, action, onlyOnce) {
  34391. this.frame = frame;
  34392. this.action = action;
  34393. this.onlyOnce = onlyOnce;
  34394. this.isDone = false;
  34395. }
  34396. return AnimationEvent;
  34397. }());
  34398. BABYLON.AnimationEvent = AnimationEvent;
  34399. var PathCursor = (function () {
  34400. function PathCursor(path) {
  34401. this.path = path;
  34402. this._onchange = new Array();
  34403. this.value = 0;
  34404. this.animations = new Array();
  34405. }
  34406. PathCursor.prototype.getPoint = function () {
  34407. var point = this.path.getPointAtLengthPosition(this.value);
  34408. return new BABYLON.Vector3(point.x, 0, point.y);
  34409. };
  34410. PathCursor.prototype.moveAhead = function (step) {
  34411. if (step === void 0) { step = 0.002; }
  34412. this.move(step);
  34413. return this;
  34414. };
  34415. PathCursor.prototype.moveBack = function (step) {
  34416. if (step === void 0) { step = 0.002; }
  34417. this.move(-step);
  34418. return this;
  34419. };
  34420. PathCursor.prototype.move = function (step) {
  34421. if (Math.abs(step) > 1) {
  34422. throw "step size should be less than 1.";
  34423. }
  34424. this.value += step;
  34425. this.ensureLimits();
  34426. this.raiseOnChange();
  34427. return this;
  34428. };
  34429. PathCursor.prototype.ensureLimits = function () {
  34430. while (this.value > 1) {
  34431. this.value -= 1;
  34432. }
  34433. while (this.value < 0) {
  34434. this.value += 1;
  34435. }
  34436. return this;
  34437. };
  34438. // used by animation engine
  34439. PathCursor.prototype.markAsDirty = function (propertyName) {
  34440. this.ensureLimits();
  34441. this.raiseOnChange();
  34442. return this;
  34443. };
  34444. PathCursor.prototype.raiseOnChange = function () {
  34445. var _this = this;
  34446. this._onchange.forEach(function (f) { return f(_this); });
  34447. return this;
  34448. };
  34449. PathCursor.prototype.onchange = function (f) {
  34450. this._onchange.push(f);
  34451. return this;
  34452. };
  34453. return PathCursor;
  34454. }());
  34455. BABYLON.PathCursor = PathCursor;
  34456. var Animation = (function () {
  34457. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  34458. this.name = name;
  34459. this.targetProperty = targetProperty;
  34460. this.framePerSecond = framePerSecond;
  34461. this.dataType = dataType;
  34462. this.loopMode = loopMode;
  34463. this.enableBlending = enableBlending;
  34464. this._offsetsCache = {};
  34465. this._highLimitsCache = {};
  34466. this._stopped = false;
  34467. this._blendingFactor = 0;
  34468. // The set of event that will be linked to this animation
  34469. this._events = new Array();
  34470. this.allowMatricesInterpolation = false;
  34471. this.blendingSpeed = 0.01;
  34472. this._ranges = {};
  34473. this.targetPropertyPath = targetProperty.split(".");
  34474. this.dataType = dataType;
  34475. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  34476. }
  34477. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  34478. var dataType = undefined;
  34479. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  34480. dataType = Animation.ANIMATIONTYPE_FLOAT;
  34481. }
  34482. else if (from instanceof BABYLON.Quaternion) {
  34483. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  34484. }
  34485. else if (from instanceof BABYLON.Vector3) {
  34486. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  34487. }
  34488. else if (from instanceof BABYLON.Vector2) {
  34489. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  34490. }
  34491. else if (from instanceof BABYLON.Color3) {
  34492. dataType = Animation.ANIMATIONTYPE_COLOR3;
  34493. }
  34494. else if (from instanceof BABYLON.Size) {
  34495. dataType = Animation.ANIMATIONTYPE_SIZE;
  34496. }
  34497. if (dataType == undefined) {
  34498. return null;
  34499. }
  34500. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  34501. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  34502. animation.setKeys(keys);
  34503. if (easingFunction !== undefined) {
  34504. animation.setEasingFunction(easingFunction);
  34505. }
  34506. return animation;
  34507. };
  34508. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34509. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34510. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34511. };
  34512. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34513. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34514. node.animations.push(animation);
  34515. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34516. };
  34517. // Methods
  34518. /**
  34519. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34520. */
  34521. Animation.prototype.toString = function (fullDetails) {
  34522. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  34523. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  34524. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  34525. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34526. if (fullDetails) {
  34527. ret += ", Ranges: {";
  34528. var first = true;
  34529. for (var name in this._ranges) {
  34530. if (first) {
  34531. ret += ", ";
  34532. first = false;
  34533. }
  34534. ret += name;
  34535. }
  34536. ret += "}";
  34537. }
  34538. return ret;
  34539. };
  34540. /**
  34541. * Add an event to this animation.
  34542. */
  34543. Animation.prototype.addEvent = function (event) {
  34544. this._events.push(event);
  34545. };
  34546. /**
  34547. * Remove all events found at the given frame
  34548. * @param frame
  34549. */
  34550. Animation.prototype.removeEvents = function (frame) {
  34551. for (var index = 0; index < this._events.length; index++) {
  34552. if (this._events[index].frame === frame) {
  34553. this._events.splice(index, 1);
  34554. index--;
  34555. }
  34556. }
  34557. };
  34558. Animation.prototype.createRange = function (name, from, to) {
  34559. // check name not already in use; could happen for bones after serialized
  34560. if (!this._ranges[name]) {
  34561. this._ranges[name] = new AnimationRange(name, from, to);
  34562. }
  34563. };
  34564. Animation.prototype.deleteRange = function (name, deleteFrames) {
  34565. if (deleteFrames === void 0) { deleteFrames = true; }
  34566. if (this._ranges[name]) {
  34567. if (deleteFrames) {
  34568. var from = this._ranges[name].from;
  34569. var to = this._ranges[name].to;
  34570. // this loop MUST go high to low for multiple splices to work
  34571. for (var key = this._keys.length - 1; key >= 0; key--) {
  34572. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  34573. this._keys.splice(key, 1);
  34574. }
  34575. }
  34576. }
  34577. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34578. }
  34579. };
  34580. Animation.prototype.getRange = function (name) {
  34581. return this._ranges[name];
  34582. };
  34583. Animation.prototype.reset = function () {
  34584. this._offsetsCache = {};
  34585. this._highLimitsCache = {};
  34586. this.currentFrame = 0;
  34587. this._blendingFactor = 0;
  34588. this._originalBlendValue = null;
  34589. };
  34590. Animation.prototype.isStopped = function () {
  34591. return this._stopped;
  34592. };
  34593. Animation.prototype.getKeys = function () {
  34594. return this._keys;
  34595. };
  34596. Animation.prototype.getHighestFrame = function () {
  34597. var ret = 0;
  34598. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  34599. if (ret < this._keys[key].frame) {
  34600. ret = this._keys[key].frame;
  34601. }
  34602. }
  34603. return ret;
  34604. };
  34605. Animation.prototype.getEasingFunction = function () {
  34606. return this._easingFunction;
  34607. };
  34608. Animation.prototype.setEasingFunction = function (easingFunction) {
  34609. this._easingFunction = easingFunction;
  34610. };
  34611. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  34612. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  34613. };
  34614. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34615. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34616. };
  34617. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  34618. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  34619. };
  34620. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34621. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  34622. };
  34623. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  34624. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  34625. };
  34626. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34627. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34628. };
  34629. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  34630. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  34631. };
  34632. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34633. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34634. };
  34635. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  34636. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  34637. };
  34638. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  34639. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  34640. };
  34641. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  34642. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  34643. };
  34644. Animation.prototype.clone = function () {
  34645. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  34646. clone.enableBlending = this.enableBlending;
  34647. clone.blendingSpeed = this.blendingSpeed;
  34648. if (this._keys) {
  34649. clone.setKeys(this._keys);
  34650. }
  34651. if (this._ranges) {
  34652. clone._ranges = {};
  34653. for (var name in this._ranges) {
  34654. clone._ranges[name] = this._ranges[name].clone();
  34655. }
  34656. }
  34657. return clone;
  34658. };
  34659. Animation.prototype.setKeys = function (values) {
  34660. this._keys = values.slice(0);
  34661. this._offsetsCache = {};
  34662. this._highLimitsCache = {};
  34663. };
  34664. Animation.prototype._getKeyValue = function (value) {
  34665. if (typeof value === "function") {
  34666. return value();
  34667. }
  34668. return value;
  34669. };
  34670. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  34671. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  34672. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  34673. }
  34674. this.currentFrame = currentFrame;
  34675. // Try to get a hash to find the right key
  34676. 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));
  34677. if (this._keys[startKeyIndex].frame >= currentFrame) {
  34678. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  34679. startKeyIndex--;
  34680. }
  34681. }
  34682. for (var key = startKeyIndex; key < this._keys.length; key++) {
  34683. var endKey = this._keys[key + 1];
  34684. if (endKey.frame >= currentFrame) {
  34685. var startKey = this._keys[key];
  34686. var startValue = this._getKeyValue(startKey.value);
  34687. var endValue = this._getKeyValue(endKey.value);
  34688. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  34689. var frameDelta = endKey.frame - startKey.frame;
  34690. // gradient : percent of currentFrame between the frame inf and the frame sup
  34691. var gradient = (currentFrame - startKey.frame) / frameDelta;
  34692. // check for easingFunction and correction of gradient
  34693. if (this._easingFunction != null) {
  34694. gradient = this._easingFunction.ease(gradient);
  34695. }
  34696. switch (this.dataType) {
  34697. // Float
  34698. case Animation.ANIMATIONTYPE_FLOAT:
  34699. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  34700. switch (loopMode) {
  34701. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34702. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34703. return floatValue;
  34704. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34705. return offsetValue * repeatCount + floatValue;
  34706. }
  34707. break;
  34708. // Quaternion
  34709. case Animation.ANIMATIONTYPE_QUATERNION:
  34710. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  34711. switch (loopMode) {
  34712. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34713. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34714. return quatValue;
  34715. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34716. return quatValue.add(offsetValue.scale(repeatCount));
  34717. }
  34718. return quatValue;
  34719. // Vector3
  34720. case Animation.ANIMATIONTYPE_VECTOR3:
  34721. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  34722. switch (loopMode) {
  34723. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34724. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34725. return vec3Value;
  34726. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34727. return vec3Value.add(offsetValue.scale(repeatCount));
  34728. }
  34729. // Vector2
  34730. case Animation.ANIMATIONTYPE_VECTOR2:
  34731. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  34732. switch (loopMode) {
  34733. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34734. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34735. return vec2Value;
  34736. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34737. return vec2Value.add(offsetValue.scale(repeatCount));
  34738. }
  34739. // Size
  34740. case Animation.ANIMATIONTYPE_SIZE:
  34741. switch (loopMode) {
  34742. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34743. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34744. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  34745. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34746. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34747. }
  34748. // Color3
  34749. case Animation.ANIMATIONTYPE_COLOR3:
  34750. switch (loopMode) {
  34751. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34752. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34753. return this.color3InterpolateFunction(startValue, endValue, gradient);
  34754. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34755. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34756. }
  34757. // Matrix
  34758. case Animation.ANIMATIONTYPE_MATRIX:
  34759. switch (loopMode) {
  34760. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34761. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34762. if (this.allowMatricesInterpolation) {
  34763. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  34764. }
  34765. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34766. return startValue;
  34767. }
  34768. default:
  34769. break;
  34770. }
  34771. break;
  34772. }
  34773. }
  34774. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  34775. };
  34776. Animation.prototype.setValue = function (currentValue, blend) {
  34777. if (blend === void 0) { blend = false; }
  34778. // Set value
  34779. var path;
  34780. var destination;
  34781. if (this.targetPropertyPath.length > 1) {
  34782. var property = this._target[this.targetPropertyPath[0]];
  34783. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  34784. property = property[this.targetPropertyPath[index]];
  34785. }
  34786. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  34787. destination = property;
  34788. }
  34789. else {
  34790. path = this.targetPropertyPath[0];
  34791. destination = this._target;
  34792. }
  34793. // Blending
  34794. if (this.enableBlending && this._blendingFactor <= 1.0) {
  34795. if (!this._originalBlendValue) {
  34796. if (destination[path].clone) {
  34797. this._originalBlendValue = destination[path].clone();
  34798. }
  34799. else {
  34800. this._originalBlendValue = destination[path];
  34801. }
  34802. }
  34803. if (this._originalBlendValue.prototype) {
  34804. if (this._originalBlendValue.prototype.Lerp) {
  34805. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  34806. }
  34807. else {
  34808. destination[path] = currentValue;
  34809. }
  34810. }
  34811. else if (this._originalBlendValue.m) {
  34812. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  34813. }
  34814. else {
  34815. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  34816. }
  34817. this._blendingFactor += this.blendingSpeed;
  34818. }
  34819. else {
  34820. destination[path] = currentValue;
  34821. }
  34822. if (this._target.markAsDirty) {
  34823. this._target.markAsDirty(this.targetProperty);
  34824. }
  34825. };
  34826. Animation.prototype.goToFrame = function (frame) {
  34827. if (frame < this._keys[0].frame) {
  34828. frame = this._keys[0].frame;
  34829. }
  34830. else if (frame > this._keys[this._keys.length - 1].frame) {
  34831. frame = this._keys[this._keys.length - 1].frame;
  34832. }
  34833. var currentValue = this._interpolate(frame, 0, this.loopMode);
  34834. this.setValue(currentValue);
  34835. };
  34836. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  34837. if (blend === void 0) { blend = false; }
  34838. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  34839. this._stopped = true;
  34840. return false;
  34841. }
  34842. var returnValue = true;
  34843. // Adding a start key at frame 0 if missing
  34844. if (this._keys[0].frame !== 0) {
  34845. var newKey = { frame: 0, value: this._keys[0].value };
  34846. this._keys.splice(0, 0, newKey);
  34847. }
  34848. // Check limits
  34849. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  34850. from = this._keys[0].frame;
  34851. }
  34852. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  34853. to = this._keys[this._keys.length - 1].frame;
  34854. }
  34855. //to and from cannot be the same key
  34856. if (from === to) {
  34857. from++;
  34858. }
  34859. // Compute ratio
  34860. var range = to - from;
  34861. var offsetValue;
  34862. // ratio represents the frame delta between from and to
  34863. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  34864. var highLimitValue = 0;
  34865. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  34866. returnValue = false;
  34867. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  34868. }
  34869. else {
  34870. // Get max value if required
  34871. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  34872. var keyOffset = to.toString() + from.toString();
  34873. if (!this._offsetsCache[keyOffset]) {
  34874. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34875. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34876. switch (this.dataType) {
  34877. // Float
  34878. case Animation.ANIMATIONTYPE_FLOAT:
  34879. this._offsetsCache[keyOffset] = toValue - fromValue;
  34880. break;
  34881. // Quaternion
  34882. case Animation.ANIMATIONTYPE_QUATERNION:
  34883. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34884. break;
  34885. // Vector3
  34886. case Animation.ANIMATIONTYPE_VECTOR3:
  34887. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34888. // Vector2
  34889. case Animation.ANIMATIONTYPE_VECTOR2:
  34890. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34891. // Size
  34892. case Animation.ANIMATIONTYPE_SIZE:
  34893. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34894. // Color3
  34895. case Animation.ANIMATIONTYPE_COLOR3:
  34896. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34897. default:
  34898. break;
  34899. }
  34900. this._highLimitsCache[keyOffset] = toValue;
  34901. }
  34902. highLimitValue = this._highLimitsCache[keyOffset];
  34903. offsetValue = this._offsetsCache[keyOffset];
  34904. }
  34905. }
  34906. if (offsetValue === undefined) {
  34907. switch (this.dataType) {
  34908. // Float
  34909. case Animation.ANIMATIONTYPE_FLOAT:
  34910. offsetValue = 0;
  34911. break;
  34912. // Quaternion
  34913. case Animation.ANIMATIONTYPE_QUATERNION:
  34914. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  34915. break;
  34916. // Vector3
  34917. case Animation.ANIMATIONTYPE_VECTOR3:
  34918. offsetValue = BABYLON.Vector3.Zero();
  34919. break;
  34920. // Vector2
  34921. case Animation.ANIMATIONTYPE_VECTOR2:
  34922. offsetValue = BABYLON.Vector2.Zero();
  34923. break;
  34924. // Size
  34925. case Animation.ANIMATIONTYPE_SIZE:
  34926. offsetValue = BABYLON.Size.Zero();
  34927. break;
  34928. // Color3
  34929. case Animation.ANIMATIONTYPE_COLOR3:
  34930. offsetValue = BABYLON.Color3.Black();
  34931. }
  34932. }
  34933. // Compute value
  34934. var repeatCount = (ratio / range) >> 0;
  34935. var currentFrame = returnValue ? from + ratio % range : to;
  34936. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  34937. // Set value
  34938. this.setValue(currentValue);
  34939. // Check events
  34940. for (var index = 0; index < this._events.length; index++) {
  34941. // Make sure current frame has passed event frame and that event frame is within the current range
  34942. // Also, handle both forward and reverse animations
  34943. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  34944. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  34945. var event = this._events[index];
  34946. if (!event.isDone) {
  34947. // If event should be done only once, remove it.
  34948. if (event.onlyOnce) {
  34949. this._events.splice(index, 1);
  34950. index--;
  34951. }
  34952. event.isDone = true;
  34953. event.action();
  34954. } // Don't do anything if the event has already be done.
  34955. }
  34956. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  34957. // reset event, the animation is looping
  34958. this._events[index].isDone = false;
  34959. }
  34960. }
  34961. if (!returnValue) {
  34962. this._stopped = true;
  34963. }
  34964. return returnValue;
  34965. };
  34966. Animation.prototype.serialize = function () {
  34967. var serializationObject = {};
  34968. serializationObject.name = this.name;
  34969. serializationObject.property = this.targetProperty;
  34970. serializationObject.framePerSecond = this.framePerSecond;
  34971. serializationObject.dataType = this.dataType;
  34972. serializationObject.loopBehavior = this.loopMode;
  34973. serializationObject.enableBlending = this.enableBlending;
  34974. serializationObject.blendingSpeed = this.blendingSpeed;
  34975. var dataType = this.dataType;
  34976. serializationObject.keys = [];
  34977. var keys = this.getKeys();
  34978. for (var index = 0; index < keys.length; index++) {
  34979. var animationKey = keys[index];
  34980. var key = {};
  34981. key.frame = animationKey.frame;
  34982. switch (dataType) {
  34983. case Animation.ANIMATIONTYPE_FLOAT:
  34984. key.values = [animationKey.value];
  34985. break;
  34986. case Animation.ANIMATIONTYPE_QUATERNION:
  34987. case Animation.ANIMATIONTYPE_MATRIX:
  34988. case Animation.ANIMATIONTYPE_VECTOR3:
  34989. case Animation.ANIMATIONTYPE_COLOR3:
  34990. key.values = animationKey.value.asArray();
  34991. break;
  34992. }
  34993. serializationObject.keys.push(key);
  34994. }
  34995. serializationObject.ranges = [];
  34996. for (var name in this._ranges) {
  34997. var range = {};
  34998. range.name = name;
  34999. range.from = this._ranges[name].from;
  35000. range.to = this._ranges[name].to;
  35001. serializationObject.ranges.push(range);
  35002. }
  35003. return serializationObject;
  35004. };
  35005. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  35006. get: function () {
  35007. return Animation._ANIMATIONTYPE_FLOAT;
  35008. },
  35009. enumerable: true,
  35010. configurable: true
  35011. });
  35012. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  35013. get: function () {
  35014. return Animation._ANIMATIONTYPE_VECTOR3;
  35015. },
  35016. enumerable: true,
  35017. configurable: true
  35018. });
  35019. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  35020. get: function () {
  35021. return Animation._ANIMATIONTYPE_VECTOR2;
  35022. },
  35023. enumerable: true,
  35024. configurable: true
  35025. });
  35026. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  35027. get: function () {
  35028. return Animation._ANIMATIONTYPE_SIZE;
  35029. },
  35030. enumerable: true,
  35031. configurable: true
  35032. });
  35033. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  35034. get: function () {
  35035. return Animation._ANIMATIONTYPE_QUATERNION;
  35036. },
  35037. enumerable: true,
  35038. configurable: true
  35039. });
  35040. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  35041. get: function () {
  35042. return Animation._ANIMATIONTYPE_MATRIX;
  35043. },
  35044. enumerable: true,
  35045. configurable: true
  35046. });
  35047. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  35048. get: function () {
  35049. return Animation._ANIMATIONTYPE_COLOR3;
  35050. },
  35051. enumerable: true,
  35052. configurable: true
  35053. });
  35054. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  35055. get: function () {
  35056. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  35057. },
  35058. enumerable: true,
  35059. configurable: true
  35060. });
  35061. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  35062. get: function () {
  35063. return Animation._ANIMATIONLOOPMODE_CYCLE;
  35064. },
  35065. enumerable: true,
  35066. configurable: true
  35067. });
  35068. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  35069. get: function () {
  35070. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  35071. },
  35072. enumerable: true,
  35073. configurable: true
  35074. });
  35075. Animation.Parse = function (parsedAnimation) {
  35076. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  35077. var dataType = parsedAnimation.dataType;
  35078. var keys = [];
  35079. var data;
  35080. var index;
  35081. if (parsedAnimation.enableBlending) {
  35082. animation.enableBlending = parsedAnimation.enableBlending;
  35083. }
  35084. if (parsedAnimation.blendingSpeed) {
  35085. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  35086. }
  35087. for (index = 0; index < parsedAnimation.keys.length; index++) {
  35088. var key = parsedAnimation.keys[index];
  35089. switch (dataType) {
  35090. case Animation.ANIMATIONTYPE_FLOAT:
  35091. data = key.values[0];
  35092. break;
  35093. case Animation.ANIMATIONTYPE_QUATERNION:
  35094. data = BABYLON.Quaternion.FromArray(key.values);
  35095. break;
  35096. case Animation.ANIMATIONTYPE_MATRIX:
  35097. data = BABYLON.Matrix.FromArray(key.values);
  35098. break;
  35099. case Animation.ANIMATIONTYPE_COLOR3:
  35100. data = BABYLON.Color3.FromArray(key.values);
  35101. break;
  35102. case Animation.ANIMATIONTYPE_VECTOR3:
  35103. default:
  35104. data = BABYLON.Vector3.FromArray(key.values);
  35105. break;
  35106. }
  35107. keys.push({
  35108. frame: key.frame,
  35109. value: data
  35110. });
  35111. }
  35112. animation.setKeys(keys);
  35113. if (parsedAnimation.ranges) {
  35114. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  35115. data = parsedAnimation.ranges[index];
  35116. animation.createRange(data.name, data.from, data.to);
  35117. }
  35118. }
  35119. return animation;
  35120. };
  35121. Animation.AppendSerializedAnimations = function (source, destination) {
  35122. if (source.animations) {
  35123. destination.animations = [];
  35124. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  35125. var animation = source.animations[animationIndex];
  35126. destination.animations.push(animation.serialize());
  35127. }
  35128. }
  35129. };
  35130. return Animation;
  35131. }());
  35132. // Statics
  35133. Animation._ANIMATIONTYPE_FLOAT = 0;
  35134. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  35135. Animation._ANIMATIONTYPE_QUATERNION = 2;
  35136. Animation._ANIMATIONTYPE_MATRIX = 3;
  35137. Animation._ANIMATIONTYPE_COLOR3 = 4;
  35138. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  35139. Animation._ANIMATIONTYPE_SIZE = 6;
  35140. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  35141. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  35142. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  35143. BABYLON.Animation = Animation;
  35144. })(BABYLON || (BABYLON = {}));
  35145. //# sourceMappingURL=babylon.animation.js.map
  35146. var BABYLON;
  35147. (function (BABYLON) {
  35148. var Animatable = (function () {
  35149. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  35150. if (fromFrame === void 0) { fromFrame = 0; }
  35151. if (toFrame === void 0) { toFrame = 100; }
  35152. if (loopAnimation === void 0) { loopAnimation = false; }
  35153. if (speedRatio === void 0) { speedRatio = 1.0; }
  35154. this.target = target;
  35155. this.fromFrame = fromFrame;
  35156. this.toFrame = toFrame;
  35157. this.loopAnimation = loopAnimation;
  35158. this.speedRatio = speedRatio;
  35159. this.onAnimationEnd = onAnimationEnd;
  35160. this._localDelayOffset = null;
  35161. this._pausedDelay = null;
  35162. this._animations = new Array();
  35163. this._paused = false;
  35164. this.animationStarted = false;
  35165. if (animations) {
  35166. this.appendAnimations(target, animations);
  35167. }
  35168. this._scene = scene;
  35169. scene._activeAnimatables.push(this);
  35170. }
  35171. // Methods
  35172. Animatable.prototype.getAnimations = function () {
  35173. return this._animations;
  35174. };
  35175. Animatable.prototype.appendAnimations = function (target, animations) {
  35176. for (var index = 0; index < animations.length; index++) {
  35177. var animation = animations[index];
  35178. animation._target = target;
  35179. this._animations.push(animation);
  35180. }
  35181. };
  35182. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  35183. var animations = this._animations;
  35184. for (var index = 0; index < animations.length; index++) {
  35185. if (animations[index].targetProperty === property) {
  35186. return animations[index];
  35187. }
  35188. }
  35189. return null;
  35190. };
  35191. Animatable.prototype.reset = function () {
  35192. var animations = this._animations;
  35193. for (var index = 0; index < animations.length; index++) {
  35194. animations[index].reset();
  35195. }
  35196. this._localDelayOffset = null;
  35197. this._pausedDelay = null;
  35198. };
  35199. Animatable.prototype.enableBlending = function (blendingSpeed) {
  35200. var animations = this._animations;
  35201. for (var index = 0; index < animations.length; index++) {
  35202. animations[index].enableBlending = true;
  35203. animations[index].blendingSpeed = blendingSpeed;
  35204. }
  35205. };
  35206. Animatable.prototype.disableBlending = function () {
  35207. var animations = this._animations;
  35208. for (var index = 0; index < animations.length; index++) {
  35209. animations[index].enableBlending = false;
  35210. }
  35211. };
  35212. Animatable.prototype.goToFrame = function (frame) {
  35213. var animations = this._animations;
  35214. if (animations[0]) {
  35215. var fps = animations[0].framePerSecond;
  35216. var currentFrame = animations[0].currentFrame;
  35217. var adjustTime = frame - currentFrame;
  35218. var delay = adjustTime * 1000 / fps;
  35219. this._localDelayOffset -= delay;
  35220. }
  35221. for (var index = 0; index < animations.length; index++) {
  35222. animations[index].goToFrame(frame);
  35223. }
  35224. };
  35225. Animatable.prototype.pause = function () {
  35226. if (this._paused) {
  35227. return;
  35228. }
  35229. this._paused = true;
  35230. };
  35231. Animatable.prototype.restart = function () {
  35232. this._paused = false;
  35233. };
  35234. Animatable.prototype.stop = function (animationName) {
  35235. if (animationName) {
  35236. var idx = this._scene._activeAnimatables.indexOf(this);
  35237. if (idx > -1) {
  35238. var animations = this._animations;
  35239. for (var index = animations.length - 1; index >= 0; index--) {
  35240. if (typeof animationName === "string" && animations[index].name != animationName) {
  35241. continue;
  35242. }
  35243. animations[index].reset();
  35244. animations.splice(index, 1);
  35245. }
  35246. if (animations.length == 0) {
  35247. this._scene._activeAnimatables.splice(idx, 1);
  35248. if (this.onAnimationEnd) {
  35249. this.onAnimationEnd();
  35250. }
  35251. }
  35252. }
  35253. }
  35254. else {
  35255. var index = this._scene._activeAnimatables.indexOf(this);
  35256. if (index > -1) {
  35257. this._scene._activeAnimatables.splice(index, 1);
  35258. var animations = this._animations;
  35259. for (var index = 0; index < animations.length; index++) {
  35260. animations[index].reset();
  35261. }
  35262. if (this.onAnimationEnd) {
  35263. this.onAnimationEnd();
  35264. }
  35265. }
  35266. }
  35267. };
  35268. Animatable.prototype._animate = function (delay) {
  35269. if (this._paused) {
  35270. this.animationStarted = false;
  35271. if (this._pausedDelay === null) {
  35272. this._pausedDelay = delay;
  35273. }
  35274. return true;
  35275. }
  35276. if (this._localDelayOffset === null) {
  35277. this._localDelayOffset = delay;
  35278. }
  35279. else if (this._pausedDelay !== null) {
  35280. this._localDelayOffset += delay - this._pausedDelay;
  35281. this._pausedDelay = null;
  35282. }
  35283. // Animating
  35284. var running = false;
  35285. var animations = this._animations;
  35286. var index;
  35287. for (index = 0; index < animations.length; index++) {
  35288. var animation = animations[index];
  35289. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  35290. running = running || isRunning;
  35291. }
  35292. this.animationStarted = running;
  35293. if (!running) {
  35294. // Remove from active animatables
  35295. index = this._scene._activeAnimatables.indexOf(this);
  35296. this._scene._activeAnimatables.splice(index, 1);
  35297. }
  35298. if (!running && this.onAnimationEnd) {
  35299. this.onAnimationEnd();
  35300. this.onAnimationEnd = null;
  35301. }
  35302. return running;
  35303. };
  35304. return Animatable;
  35305. }());
  35306. BABYLON.Animatable = Animatable;
  35307. })(BABYLON || (BABYLON = {}));
  35308. //# sourceMappingURL=babylon.animatable.js.map
  35309. var BABYLON;
  35310. (function (BABYLON) {
  35311. var EasingFunction = (function () {
  35312. function EasingFunction() {
  35313. // Properties
  35314. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  35315. }
  35316. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  35317. get: function () {
  35318. return EasingFunction._EASINGMODE_EASEIN;
  35319. },
  35320. enumerable: true,
  35321. configurable: true
  35322. });
  35323. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  35324. get: function () {
  35325. return EasingFunction._EASINGMODE_EASEOUT;
  35326. },
  35327. enumerable: true,
  35328. configurable: true
  35329. });
  35330. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  35331. get: function () {
  35332. return EasingFunction._EASINGMODE_EASEINOUT;
  35333. },
  35334. enumerable: true,
  35335. configurable: true
  35336. });
  35337. EasingFunction.prototype.setEasingMode = function (easingMode) {
  35338. var n = Math.min(Math.max(easingMode, 0), 2);
  35339. this._easingMode = n;
  35340. };
  35341. EasingFunction.prototype.getEasingMode = function () {
  35342. return this._easingMode;
  35343. };
  35344. EasingFunction.prototype.easeInCore = function (gradient) {
  35345. throw new Error('You must implement this method');
  35346. };
  35347. EasingFunction.prototype.ease = function (gradient) {
  35348. switch (this._easingMode) {
  35349. case EasingFunction.EASINGMODE_EASEIN:
  35350. return this.easeInCore(gradient);
  35351. case EasingFunction.EASINGMODE_EASEOUT:
  35352. return (1 - this.easeInCore(1 - gradient));
  35353. }
  35354. if (gradient >= 0.5) {
  35355. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  35356. }
  35357. return (this.easeInCore(gradient * 2) * 0.5);
  35358. };
  35359. return EasingFunction;
  35360. }());
  35361. //Statics
  35362. EasingFunction._EASINGMODE_EASEIN = 0;
  35363. EasingFunction._EASINGMODE_EASEOUT = 1;
  35364. EasingFunction._EASINGMODE_EASEINOUT = 2;
  35365. BABYLON.EasingFunction = EasingFunction;
  35366. var CircleEase = (function (_super) {
  35367. __extends(CircleEase, _super);
  35368. function CircleEase() {
  35369. return _super !== null && _super.apply(this, arguments) || this;
  35370. }
  35371. CircleEase.prototype.easeInCore = function (gradient) {
  35372. gradient = Math.max(0, Math.min(1, gradient));
  35373. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  35374. };
  35375. return CircleEase;
  35376. }(EasingFunction));
  35377. BABYLON.CircleEase = CircleEase;
  35378. var BackEase = (function (_super) {
  35379. __extends(BackEase, _super);
  35380. function BackEase(amplitude) {
  35381. if (amplitude === void 0) { amplitude = 1; }
  35382. var _this = _super.call(this) || this;
  35383. _this.amplitude = amplitude;
  35384. return _this;
  35385. }
  35386. BackEase.prototype.easeInCore = function (gradient) {
  35387. var num = Math.max(0, this.amplitude);
  35388. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  35389. };
  35390. return BackEase;
  35391. }(EasingFunction));
  35392. BABYLON.BackEase = BackEase;
  35393. var BounceEase = (function (_super) {
  35394. __extends(BounceEase, _super);
  35395. function BounceEase(bounces, bounciness) {
  35396. if (bounces === void 0) { bounces = 3; }
  35397. if (bounciness === void 0) { bounciness = 2; }
  35398. var _this = _super.call(this) || this;
  35399. _this.bounces = bounces;
  35400. _this.bounciness = bounciness;
  35401. return _this;
  35402. }
  35403. BounceEase.prototype.easeInCore = function (gradient) {
  35404. var y = Math.max(0.0, this.bounces);
  35405. var bounciness = this.bounciness;
  35406. if (bounciness <= 1.0) {
  35407. bounciness = 1.001;
  35408. }
  35409. var num9 = Math.pow(bounciness, y);
  35410. var num5 = 1.0 - bounciness;
  35411. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  35412. var num15 = gradient * num4;
  35413. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  35414. var num3 = Math.floor(num65);
  35415. var num13 = num3 + 1.0;
  35416. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  35417. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  35418. var num7 = (num8 + num12) * 0.5;
  35419. var num6 = gradient - num7;
  35420. var num2 = num7 - num8;
  35421. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  35422. };
  35423. return BounceEase;
  35424. }(EasingFunction));
  35425. BABYLON.BounceEase = BounceEase;
  35426. var CubicEase = (function (_super) {
  35427. __extends(CubicEase, _super);
  35428. function CubicEase() {
  35429. return _super !== null && _super.apply(this, arguments) || this;
  35430. }
  35431. CubicEase.prototype.easeInCore = function (gradient) {
  35432. return (gradient * gradient * gradient);
  35433. };
  35434. return CubicEase;
  35435. }(EasingFunction));
  35436. BABYLON.CubicEase = CubicEase;
  35437. var ElasticEase = (function (_super) {
  35438. __extends(ElasticEase, _super);
  35439. function ElasticEase(oscillations, springiness) {
  35440. if (oscillations === void 0) { oscillations = 3; }
  35441. if (springiness === void 0) { springiness = 3; }
  35442. var _this = _super.call(this) || this;
  35443. _this.oscillations = oscillations;
  35444. _this.springiness = springiness;
  35445. return _this;
  35446. }
  35447. ElasticEase.prototype.easeInCore = function (gradient) {
  35448. var num2;
  35449. var num3 = Math.max(0.0, this.oscillations);
  35450. var num = Math.max(0.0, this.springiness);
  35451. if (num == 0) {
  35452. num2 = gradient;
  35453. }
  35454. else {
  35455. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  35456. }
  35457. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  35458. };
  35459. return ElasticEase;
  35460. }(EasingFunction));
  35461. BABYLON.ElasticEase = ElasticEase;
  35462. var ExponentialEase = (function (_super) {
  35463. __extends(ExponentialEase, _super);
  35464. function ExponentialEase(exponent) {
  35465. if (exponent === void 0) { exponent = 2; }
  35466. var _this = _super.call(this) || this;
  35467. _this.exponent = exponent;
  35468. return _this;
  35469. }
  35470. ExponentialEase.prototype.easeInCore = function (gradient) {
  35471. if (this.exponent <= 0) {
  35472. return gradient;
  35473. }
  35474. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  35475. };
  35476. return ExponentialEase;
  35477. }(EasingFunction));
  35478. BABYLON.ExponentialEase = ExponentialEase;
  35479. var PowerEase = (function (_super) {
  35480. __extends(PowerEase, _super);
  35481. function PowerEase(power) {
  35482. if (power === void 0) { power = 2; }
  35483. var _this = _super.call(this) || this;
  35484. _this.power = power;
  35485. return _this;
  35486. }
  35487. PowerEase.prototype.easeInCore = function (gradient) {
  35488. var y = Math.max(0.0, this.power);
  35489. return Math.pow(gradient, y);
  35490. };
  35491. return PowerEase;
  35492. }(EasingFunction));
  35493. BABYLON.PowerEase = PowerEase;
  35494. var QuadraticEase = (function (_super) {
  35495. __extends(QuadraticEase, _super);
  35496. function QuadraticEase() {
  35497. return _super !== null && _super.apply(this, arguments) || this;
  35498. }
  35499. QuadraticEase.prototype.easeInCore = function (gradient) {
  35500. return (gradient * gradient);
  35501. };
  35502. return QuadraticEase;
  35503. }(EasingFunction));
  35504. BABYLON.QuadraticEase = QuadraticEase;
  35505. var QuarticEase = (function (_super) {
  35506. __extends(QuarticEase, _super);
  35507. function QuarticEase() {
  35508. return _super !== null && _super.apply(this, arguments) || this;
  35509. }
  35510. QuarticEase.prototype.easeInCore = function (gradient) {
  35511. return (gradient * gradient * gradient * gradient);
  35512. };
  35513. return QuarticEase;
  35514. }(EasingFunction));
  35515. BABYLON.QuarticEase = QuarticEase;
  35516. var QuinticEase = (function (_super) {
  35517. __extends(QuinticEase, _super);
  35518. function QuinticEase() {
  35519. return _super !== null && _super.apply(this, arguments) || this;
  35520. }
  35521. QuinticEase.prototype.easeInCore = function (gradient) {
  35522. return (gradient * gradient * gradient * gradient * gradient);
  35523. };
  35524. return QuinticEase;
  35525. }(EasingFunction));
  35526. BABYLON.QuinticEase = QuinticEase;
  35527. var SineEase = (function (_super) {
  35528. __extends(SineEase, _super);
  35529. function SineEase() {
  35530. return _super !== null && _super.apply(this, arguments) || this;
  35531. }
  35532. SineEase.prototype.easeInCore = function (gradient) {
  35533. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  35534. };
  35535. return SineEase;
  35536. }(EasingFunction));
  35537. BABYLON.SineEase = SineEase;
  35538. var BezierCurveEase = (function (_super) {
  35539. __extends(BezierCurveEase, _super);
  35540. function BezierCurveEase(x1, y1, x2, y2) {
  35541. if (x1 === void 0) { x1 = 0; }
  35542. if (y1 === void 0) { y1 = 0; }
  35543. if (x2 === void 0) { x2 = 1; }
  35544. if (y2 === void 0) { y2 = 1; }
  35545. var _this = _super.call(this) || this;
  35546. _this.x1 = x1;
  35547. _this.y1 = y1;
  35548. _this.x2 = x2;
  35549. _this.y2 = y2;
  35550. return _this;
  35551. }
  35552. BezierCurveEase.prototype.easeInCore = function (gradient) {
  35553. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  35554. };
  35555. return BezierCurveEase;
  35556. }(EasingFunction));
  35557. BABYLON.BezierCurveEase = BezierCurveEase;
  35558. })(BABYLON || (BABYLON = {}));
  35559. //# sourceMappingURL=babylon.easing.js.map
  35560. var BABYLON;
  35561. (function (BABYLON) {
  35562. var Condition = (function () {
  35563. function Condition(actionManager) {
  35564. this._actionManager = actionManager;
  35565. }
  35566. Condition.prototype.isValid = function () {
  35567. return true;
  35568. };
  35569. Condition.prototype._getProperty = function (propertyPath) {
  35570. return this._actionManager._getProperty(propertyPath);
  35571. };
  35572. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  35573. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35574. };
  35575. Condition.prototype.serialize = function () {
  35576. };
  35577. Condition.prototype._serialize = function (serializedCondition) {
  35578. return {
  35579. type: 2,
  35580. children: [],
  35581. name: serializedCondition.name,
  35582. properties: serializedCondition.properties
  35583. };
  35584. };
  35585. return Condition;
  35586. }());
  35587. BABYLON.Condition = Condition;
  35588. var ValueCondition = (function (_super) {
  35589. __extends(ValueCondition, _super);
  35590. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35591. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35592. var _this = _super.call(this, actionManager) || this;
  35593. _this.propertyPath = propertyPath;
  35594. _this.value = value;
  35595. _this.operator = operator;
  35596. _this._target = target;
  35597. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35598. _this._property = _this._getProperty(_this.propertyPath);
  35599. return _this;
  35600. }
  35601. Object.defineProperty(ValueCondition, "IsEqual", {
  35602. get: function () {
  35603. return ValueCondition._IsEqual;
  35604. },
  35605. enumerable: true,
  35606. configurable: true
  35607. });
  35608. Object.defineProperty(ValueCondition, "IsDifferent", {
  35609. get: function () {
  35610. return ValueCondition._IsDifferent;
  35611. },
  35612. enumerable: true,
  35613. configurable: true
  35614. });
  35615. Object.defineProperty(ValueCondition, "IsGreater", {
  35616. get: function () {
  35617. return ValueCondition._IsGreater;
  35618. },
  35619. enumerable: true,
  35620. configurable: true
  35621. });
  35622. Object.defineProperty(ValueCondition, "IsLesser", {
  35623. get: function () {
  35624. return ValueCondition._IsLesser;
  35625. },
  35626. enumerable: true,
  35627. configurable: true
  35628. });
  35629. // Methods
  35630. ValueCondition.prototype.isValid = function () {
  35631. switch (this.operator) {
  35632. case ValueCondition.IsGreater:
  35633. return this._effectiveTarget[this._property] > this.value;
  35634. case ValueCondition.IsLesser:
  35635. return this._effectiveTarget[this._property] < this.value;
  35636. case ValueCondition.IsEqual:
  35637. case ValueCondition.IsDifferent:
  35638. var check;
  35639. if (this.value.equals) {
  35640. check = this.value.equals(this._effectiveTarget[this._property]);
  35641. }
  35642. else {
  35643. check = this.value === this._effectiveTarget[this._property];
  35644. }
  35645. return this.operator === ValueCondition.IsEqual ? check : !check;
  35646. }
  35647. return false;
  35648. };
  35649. ValueCondition.prototype.serialize = function () {
  35650. return this._serialize({
  35651. name: "ValueCondition",
  35652. properties: [
  35653. BABYLON.Action._GetTargetProperty(this._target),
  35654. { name: "propertyPath", value: this.propertyPath },
  35655. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35656. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35657. ]
  35658. });
  35659. };
  35660. ValueCondition.GetOperatorName = function (operator) {
  35661. switch (operator) {
  35662. case ValueCondition._IsEqual: return "IsEqual";
  35663. case ValueCondition._IsDifferent: return "IsDifferent";
  35664. case ValueCondition._IsGreater: return "IsGreater";
  35665. case ValueCondition._IsLesser: return "IsLesser";
  35666. default: return "";
  35667. }
  35668. };
  35669. return ValueCondition;
  35670. }(Condition));
  35671. // Statics
  35672. ValueCondition._IsEqual = 0;
  35673. ValueCondition._IsDifferent = 1;
  35674. ValueCondition._IsGreater = 2;
  35675. ValueCondition._IsLesser = 3;
  35676. BABYLON.ValueCondition = ValueCondition;
  35677. var PredicateCondition = (function (_super) {
  35678. __extends(PredicateCondition, _super);
  35679. function PredicateCondition(actionManager, predicate) {
  35680. var _this = _super.call(this, actionManager) || this;
  35681. _this.predicate = predicate;
  35682. return _this;
  35683. }
  35684. PredicateCondition.prototype.isValid = function () {
  35685. return this.predicate();
  35686. };
  35687. return PredicateCondition;
  35688. }(Condition));
  35689. BABYLON.PredicateCondition = PredicateCondition;
  35690. var StateCondition = (function (_super) {
  35691. __extends(StateCondition, _super);
  35692. function StateCondition(actionManager, target, value) {
  35693. var _this = _super.call(this, actionManager) || this;
  35694. _this.value = value;
  35695. _this._target = target;
  35696. return _this;
  35697. }
  35698. // Methods
  35699. StateCondition.prototype.isValid = function () {
  35700. return this._target.state === this.value;
  35701. };
  35702. StateCondition.prototype.serialize = function () {
  35703. return this._serialize({
  35704. name: "StateCondition",
  35705. properties: [
  35706. BABYLON.Action._GetTargetProperty(this._target),
  35707. { name: "value", value: this.value }
  35708. ]
  35709. });
  35710. };
  35711. return StateCondition;
  35712. }(Condition));
  35713. BABYLON.StateCondition = StateCondition;
  35714. })(BABYLON || (BABYLON = {}));
  35715. //# sourceMappingURL=babylon.condition.js.map
  35716. var BABYLON;
  35717. (function (BABYLON) {
  35718. var Action = (function () {
  35719. function Action(triggerOptions, condition) {
  35720. this.triggerOptions = triggerOptions;
  35721. if (triggerOptions.parameter) {
  35722. this.trigger = triggerOptions.trigger;
  35723. this._triggerParameter = triggerOptions.parameter;
  35724. }
  35725. else {
  35726. this.trigger = triggerOptions;
  35727. }
  35728. this._nextActiveAction = this;
  35729. this._condition = condition;
  35730. }
  35731. // Methods
  35732. Action.prototype._prepare = function () {
  35733. };
  35734. Action.prototype.getTriggerParameter = function () {
  35735. return this._triggerParameter;
  35736. };
  35737. Action.prototype._executeCurrent = function (evt) {
  35738. if (this._nextActiveAction._condition) {
  35739. var condition = this._nextActiveAction._condition;
  35740. var currentRenderId = this._actionManager.getScene().getRenderId();
  35741. // We cache the current evaluation for the current frame
  35742. if (condition._evaluationId === currentRenderId) {
  35743. if (!condition._currentResult) {
  35744. return;
  35745. }
  35746. }
  35747. else {
  35748. condition._evaluationId = currentRenderId;
  35749. if (!condition.isValid()) {
  35750. condition._currentResult = false;
  35751. return;
  35752. }
  35753. condition._currentResult = true;
  35754. }
  35755. }
  35756. this._nextActiveAction.execute(evt);
  35757. this.skipToNextActiveAction();
  35758. };
  35759. Action.prototype.execute = function (evt) {
  35760. };
  35761. Action.prototype.skipToNextActiveAction = function () {
  35762. if (this._nextActiveAction._child) {
  35763. if (!this._nextActiveAction._child._actionManager) {
  35764. this._nextActiveAction._child._actionManager = this._actionManager;
  35765. }
  35766. this._nextActiveAction = this._nextActiveAction._child;
  35767. }
  35768. else {
  35769. this._nextActiveAction = this;
  35770. }
  35771. };
  35772. Action.prototype.then = function (action) {
  35773. this._child = action;
  35774. action._actionManager = this._actionManager;
  35775. action._prepare();
  35776. return action;
  35777. };
  35778. Action.prototype._getProperty = function (propertyPath) {
  35779. return this._actionManager._getProperty(propertyPath);
  35780. };
  35781. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35782. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35783. };
  35784. Action.prototype.serialize = function (parent) {
  35785. };
  35786. // Called by BABYLON.Action objects in serialize(...). Internal use
  35787. Action.prototype._serialize = function (serializedAction, parent) {
  35788. var serializationObject = {
  35789. type: 1,
  35790. children: [],
  35791. name: serializedAction.name,
  35792. properties: serializedAction.properties || []
  35793. };
  35794. // Serialize child
  35795. if (this._child) {
  35796. this._child.serialize(serializationObject);
  35797. }
  35798. // Check if "this" has a condition
  35799. if (this._condition) {
  35800. var serializedCondition = this._condition.serialize();
  35801. serializedCondition.children.push(serializationObject);
  35802. if (parent) {
  35803. parent.children.push(serializedCondition);
  35804. }
  35805. return serializedCondition;
  35806. }
  35807. if (parent) {
  35808. parent.children.push(serializationObject);
  35809. }
  35810. return serializationObject;
  35811. };
  35812. return Action;
  35813. }());
  35814. Action._SerializeValueAsString = function (value) {
  35815. if (typeof value === "number") {
  35816. return value.toString();
  35817. }
  35818. if (typeof value === "boolean") {
  35819. return value ? "true" : "false";
  35820. }
  35821. if (value instanceof BABYLON.Vector2) {
  35822. return value.x + ", " + value.y;
  35823. }
  35824. if (value instanceof BABYLON.Vector3) {
  35825. return value.x + ", " + value.y + ", " + value.z;
  35826. }
  35827. if (value instanceof BABYLON.Color3) {
  35828. return value.r + ", " + value.g + ", " + value.b;
  35829. }
  35830. if (value instanceof BABYLON.Color4) {
  35831. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35832. }
  35833. return value; // string
  35834. };
  35835. Action._GetTargetProperty = function (target) {
  35836. return {
  35837. name: "target",
  35838. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35839. : target instanceof BABYLON.Light ? "LightProperties"
  35840. : target instanceof BABYLON.Camera ? "CameraProperties"
  35841. : "SceneProperties",
  35842. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35843. };
  35844. };
  35845. BABYLON.Action = Action;
  35846. })(BABYLON || (BABYLON = {}));
  35847. //# sourceMappingURL=babylon.action.js.map
  35848. var BABYLON;
  35849. (function (BABYLON) {
  35850. /**
  35851. * ActionEvent is the event beint sent when an action is triggered.
  35852. */
  35853. var ActionEvent = (function () {
  35854. /**
  35855. * @constructor
  35856. * @param source The mesh or sprite that triggered the action.
  35857. * @param pointerX The X mouse cursor position at the time of the event
  35858. * @param pointerY The Y mouse cursor position at the time of the event
  35859. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35860. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35861. */
  35862. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35863. this.source = source;
  35864. this.pointerX = pointerX;
  35865. this.pointerY = pointerY;
  35866. this.meshUnderPointer = meshUnderPointer;
  35867. this.sourceEvent = sourceEvent;
  35868. this.additionalData = additionalData;
  35869. }
  35870. /**
  35871. * Helper function to auto-create an ActionEvent from a source mesh.
  35872. * @param source The source mesh that triggered the event
  35873. * @param evt {Event} The original (browser) event
  35874. */
  35875. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35876. var scene = source.getScene();
  35877. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35878. };
  35879. /**
  35880. * Helper function to auto-create an ActionEvent from a source mesh.
  35881. * @param source The source sprite that triggered the event
  35882. * @param scene Scene associated with the sprite
  35883. * @param evt {Event} The original (browser) event
  35884. */
  35885. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  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 scene. If triggered by a mesh use ActionEvent.CreateNew
  35890. * @param scene the scene where the event occurred
  35891. * @param evt {Event} The original (browser) event
  35892. */
  35893. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35894. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35895. };
  35896. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35897. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35898. };
  35899. return ActionEvent;
  35900. }());
  35901. BABYLON.ActionEvent = ActionEvent;
  35902. /**
  35903. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35904. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35905. */
  35906. var ActionManager = (function () {
  35907. function ActionManager(scene) {
  35908. // Members
  35909. this.actions = new Array();
  35910. this.hoverCursor = '';
  35911. this._scene = scene;
  35912. scene._actionManagers.push(this);
  35913. }
  35914. Object.defineProperty(ActionManager, "NothingTrigger", {
  35915. get: function () {
  35916. return ActionManager._NothingTrigger;
  35917. },
  35918. enumerable: true,
  35919. configurable: true
  35920. });
  35921. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35922. get: function () {
  35923. return ActionManager._OnPickTrigger;
  35924. },
  35925. enumerable: true,
  35926. configurable: true
  35927. });
  35928. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35929. get: function () {
  35930. return ActionManager._OnLeftPickTrigger;
  35931. },
  35932. enumerable: true,
  35933. configurable: true
  35934. });
  35935. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35936. get: function () {
  35937. return ActionManager._OnRightPickTrigger;
  35938. },
  35939. enumerable: true,
  35940. configurable: true
  35941. });
  35942. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35943. get: function () {
  35944. return ActionManager._OnCenterPickTrigger;
  35945. },
  35946. enumerable: true,
  35947. configurable: true
  35948. });
  35949. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35950. get: function () {
  35951. return ActionManager._OnPickDownTrigger;
  35952. },
  35953. enumerable: true,
  35954. configurable: true
  35955. });
  35956. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  35957. get: function () {
  35958. return ActionManager._OnDoublePickTrigger;
  35959. },
  35960. enumerable: true,
  35961. configurable: true
  35962. });
  35963. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35964. get: function () {
  35965. return ActionManager._OnPickUpTrigger;
  35966. },
  35967. enumerable: true,
  35968. configurable: true
  35969. });
  35970. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35971. /// This trigger will only be raised if you also declared a OnPickDown
  35972. get: function () {
  35973. return ActionManager._OnPickOutTrigger;
  35974. },
  35975. enumerable: true,
  35976. configurable: true
  35977. });
  35978. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35979. get: function () {
  35980. return ActionManager._OnLongPressTrigger;
  35981. },
  35982. enumerable: true,
  35983. configurable: true
  35984. });
  35985. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35986. get: function () {
  35987. return ActionManager._OnPointerOverTrigger;
  35988. },
  35989. enumerable: true,
  35990. configurable: true
  35991. });
  35992. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35993. get: function () {
  35994. return ActionManager._OnPointerOutTrigger;
  35995. },
  35996. enumerable: true,
  35997. configurable: true
  35998. });
  35999. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36000. get: function () {
  36001. return ActionManager._OnEveryFrameTrigger;
  36002. },
  36003. enumerable: true,
  36004. configurable: true
  36005. });
  36006. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36007. get: function () {
  36008. return ActionManager._OnIntersectionEnterTrigger;
  36009. },
  36010. enumerable: true,
  36011. configurable: true
  36012. });
  36013. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36014. get: function () {
  36015. return ActionManager._OnIntersectionExitTrigger;
  36016. },
  36017. enumerable: true,
  36018. configurable: true
  36019. });
  36020. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36021. get: function () {
  36022. return ActionManager._OnKeyDownTrigger;
  36023. },
  36024. enumerable: true,
  36025. configurable: true
  36026. });
  36027. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36028. get: function () {
  36029. return ActionManager._OnKeyUpTrigger;
  36030. },
  36031. enumerable: true,
  36032. configurable: true
  36033. });
  36034. // Methods
  36035. ActionManager.prototype.dispose = function () {
  36036. var index = this._scene._actionManagers.indexOf(this);
  36037. for (var i = 0; i < this.actions.length; i++) {
  36038. var action = this.actions[i];
  36039. ActionManager.Triggers[action.trigger]--;
  36040. if (ActionManager.Triggers[action.trigger] === 0) {
  36041. delete ActionManager.Triggers[action.trigger];
  36042. }
  36043. }
  36044. if (index > -1) {
  36045. this._scene._actionManagers.splice(index, 1);
  36046. }
  36047. };
  36048. ActionManager.prototype.getScene = function () {
  36049. return this._scene;
  36050. };
  36051. /**
  36052. * Does this action manager handles actions of any of the given triggers
  36053. * @param {number[]} triggers - the triggers to be tested
  36054. * @return {boolean} whether one (or more) of the triggers is handeled
  36055. */
  36056. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36057. for (var index = 0; index < this.actions.length; index++) {
  36058. var action = this.actions[index];
  36059. if (triggers.indexOf(action.trigger) > -1) {
  36060. return true;
  36061. }
  36062. }
  36063. return false;
  36064. };
  36065. /**
  36066. * Does this action manager handles actions of a given trigger
  36067. * @param {number} trigger - the trigger to be tested
  36068. * @return {boolean} whether the trigger is handeled
  36069. */
  36070. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36071. for (var index = 0; index < this.actions.length; index++) {
  36072. var action = this.actions[index];
  36073. if (action.trigger === trigger) {
  36074. return true;
  36075. }
  36076. }
  36077. return false;
  36078. };
  36079. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36080. /**
  36081. * Does this action manager has pointer triggers
  36082. * @return {boolean} whether or not it has pointer triggers
  36083. */
  36084. get: function () {
  36085. for (var index = 0; index < this.actions.length; index++) {
  36086. var action = this.actions[index];
  36087. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36088. return true;
  36089. }
  36090. }
  36091. return false;
  36092. },
  36093. enumerable: true,
  36094. configurable: true
  36095. });
  36096. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36097. /**
  36098. * Does this action manager has pick triggers
  36099. * @return {boolean} whether or not it has pick triggers
  36100. */
  36101. get: function () {
  36102. for (var index = 0; index < this.actions.length; index++) {
  36103. var action = this.actions[index];
  36104. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36105. return true;
  36106. }
  36107. }
  36108. return false;
  36109. },
  36110. enumerable: true,
  36111. configurable: true
  36112. });
  36113. Object.defineProperty(ActionManager, "HasTriggers", {
  36114. /**
  36115. * Does exist one action manager with at least one trigger
  36116. * @return {boolean} whether or not it exists one action manager with one trigger
  36117. **/
  36118. get: function () {
  36119. for (var t in ActionManager.Triggers) {
  36120. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36121. return true;
  36122. }
  36123. }
  36124. return false;
  36125. },
  36126. enumerable: true,
  36127. configurable: true
  36128. });
  36129. Object.defineProperty(ActionManager, "HasPickTriggers", {
  36130. /**
  36131. * Does exist one action manager with at least one pick trigger
  36132. * @return {boolean} whether or not it exists one action manager with one pick trigger
  36133. **/
  36134. get: function () {
  36135. for (var t in ActionManager.Triggers) {
  36136. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36137. var t_int = parseInt(t);
  36138. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  36139. return true;
  36140. }
  36141. }
  36142. }
  36143. return false;
  36144. },
  36145. enumerable: true,
  36146. configurable: true
  36147. });
  36148. /**
  36149. * Does exist one action manager that handles actions of a given trigger
  36150. * @param {number} trigger - the trigger to be tested
  36151. * @return {boolean} whether the trigger is handeled by at least one action manager
  36152. **/
  36153. ActionManager.HasSpecificTrigger = function (trigger) {
  36154. for (var t in ActionManager.Triggers) {
  36155. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36156. var t_int = parseInt(t);
  36157. if (t_int === trigger) {
  36158. return true;
  36159. }
  36160. }
  36161. }
  36162. return false;
  36163. };
  36164. /**
  36165. * Registers an action to this action manager
  36166. * @param {BABYLON.Action} action - the action to be registered
  36167. * @return {BABYLON.Action} the action amended (prepared) after registration
  36168. */
  36169. ActionManager.prototype.registerAction = function (action) {
  36170. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36171. if (this.getScene().actionManager !== this) {
  36172. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36173. return null;
  36174. }
  36175. }
  36176. this.actions.push(action);
  36177. if (ActionManager.Triggers[action.trigger]) {
  36178. ActionManager.Triggers[action.trigger]++;
  36179. }
  36180. else {
  36181. ActionManager.Triggers[action.trigger] = 1;
  36182. }
  36183. action._actionManager = this;
  36184. action._prepare();
  36185. return action;
  36186. };
  36187. /**
  36188. * Process a specific trigger
  36189. * @param {number} trigger - the trigger to process
  36190. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36191. */
  36192. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36193. for (var index = 0; index < this.actions.length; index++) {
  36194. var action = this.actions[index];
  36195. if (action.trigger === trigger) {
  36196. if (trigger === ActionManager.OnKeyUpTrigger
  36197. || trigger === ActionManager.OnKeyDownTrigger) {
  36198. var parameter = action.getTriggerParameter();
  36199. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  36200. if (!parameter.toLowerCase) {
  36201. continue;
  36202. }
  36203. var lowerCase = parameter.toLowerCase();
  36204. if (lowerCase !== evt.sourceEvent.key) {
  36205. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  36206. var actualkey = String.fromCharCode(unicode).toLowerCase();
  36207. if (actualkey !== lowerCase) {
  36208. continue;
  36209. }
  36210. }
  36211. }
  36212. }
  36213. action._executeCurrent(evt);
  36214. }
  36215. }
  36216. };
  36217. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  36218. var properties = propertyPath.split(".");
  36219. for (var index = 0; index < properties.length - 1; index++) {
  36220. target = target[properties[index]];
  36221. }
  36222. return target;
  36223. };
  36224. ActionManager.prototype._getProperty = function (propertyPath) {
  36225. var properties = propertyPath.split(".");
  36226. return properties[properties.length - 1];
  36227. };
  36228. ActionManager.prototype.serialize = function (name) {
  36229. var root = {
  36230. children: [],
  36231. name: name,
  36232. type: 3,
  36233. properties: [] // Empty for root but required
  36234. };
  36235. for (var i = 0; i < this.actions.length; i++) {
  36236. var triggerObject = {
  36237. type: 0,
  36238. children: [],
  36239. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  36240. properties: []
  36241. };
  36242. var triggerOptions = this.actions[i].triggerOptions;
  36243. if (triggerOptions && typeof triggerOptions !== "number") {
  36244. if (triggerOptions.parameter instanceof BABYLON.Node) {
  36245. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  36246. }
  36247. else {
  36248. var parameter = {};
  36249. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  36250. if (triggerOptions.parameter.mesh) {
  36251. parameter._meshId = triggerOptions.parameter.mesh.id;
  36252. }
  36253. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  36254. }
  36255. }
  36256. // Serialize child action, recursively
  36257. this.actions[i].serialize(triggerObject);
  36258. // Add serialized trigger
  36259. root.children.push(triggerObject);
  36260. }
  36261. return root;
  36262. };
  36263. ActionManager.Parse = function (parsedActions, object, scene) {
  36264. var actionManager = new BABYLON.ActionManager(scene);
  36265. if (object === null)
  36266. scene.actionManager = actionManager;
  36267. else
  36268. object.actionManager = actionManager;
  36269. // instanciate a new object
  36270. var instanciate = function (name, params) {
  36271. var newInstance = Object.create(BABYLON[name].prototype);
  36272. newInstance.constructor.apply(newInstance, params);
  36273. return newInstance;
  36274. };
  36275. var parseParameter = function (name, value, target, propertyPath) {
  36276. if (propertyPath === null) {
  36277. // String, boolean or float
  36278. var floatValue = parseFloat(value);
  36279. if (value === "true" || value === "false")
  36280. return value === "true";
  36281. else
  36282. return isNaN(floatValue) ? value : floatValue;
  36283. }
  36284. var effectiveTarget = propertyPath.split(".");
  36285. var values = value.split(",");
  36286. // Get effective Target
  36287. for (var i = 0; i < effectiveTarget.length; i++) {
  36288. target = target[effectiveTarget[i]];
  36289. }
  36290. // Return appropriate value with its type
  36291. if (typeof (target) === "boolean")
  36292. return values[0] === "true";
  36293. if (typeof (target) === "string")
  36294. return values[0];
  36295. // Parameters with multiple values such as Vector3 etc.
  36296. var split = new Array();
  36297. for (var i = 0; i < values.length; i++)
  36298. split.push(parseFloat(values[i]));
  36299. if (target instanceof BABYLON.Vector3)
  36300. return BABYLON.Vector3.FromArray(split);
  36301. if (target instanceof BABYLON.Vector4)
  36302. return BABYLON.Vector4.FromArray(split);
  36303. if (target instanceof BABYLON.Color3)
  36304. return BABYLON.Color3.FromArray(split);
  36305. if (target instanceof BABYLON.Color4)
  36306. return BABYLON.Color4.FromArray(split);
  36307. return parseFloat(values[0]);
  36308. };
  36309. // traverse graph per trigger
  36310. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  36311. if (combineArray === void 0) { combineArray = null; }
  36312. if (parsedAction.detached)
  36313. return;
  36314. var parameters = new Array();
  36315. var target = null;
  36316. var propertyPath = null;
  36317. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  36318. // Parameters
  36319. if (parsedAction.type === 2)
  36320. parameters.push(actionManager);
  36321. else
  36322. parameters.push(trigger);
  36323. if (combine) {
  36324. var actions = new Array();
  36325. for (var j = 0; j < parsedAction.combine.length; j++) {
  36326. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  36327. }
  36328. parameters.push(actions);
  36329. }
  36330. else {
  36331. for (var i = 0; i < parsedAction.properties.length; i++) {
  36332. var value = parsedAction.properties[i].value;
  36333. var name = parsedAction.properties[i].name;
  36334. var targetType = parsedAction.properties[i].targetType;
  36335. if (name === "target")
  36336. if (targetType !== null && targetType === "SceneProperties")
  36337. value = target = scene;
  36338. else
  36339. value = target = scene.getNodeByName(value);
  36340. else if (name === "parent")
  36341. value = scene.getNodeByName(value);
  36342. else if (name === "sound")
  36343. value = scene.getSoundByName(value);
  36344. else if (name !== "propertyPath") {
  36345. if (parsedAction.type === 2 && name === "operator")
  36346. value = BABYLON.ValueCondition[value];
  36347. else
  36348. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  36349. }
  36350. else {
  36351. propertyPath = value;
  36352. }
  36353. parameters.push(value);
  36354. }
  36355. }
  36356. if (combineArray === null) {
  36357. parameters.push(condition);
  36358. }
  36359. else {
  36360. parameters.push(null);
  36361. }
  36362. // If interpolate value action
  36363. if (parsedAction.name === "InterpolateValueAction") {
  36364. var param = parameters[parameters.length - 2];
  36365. parameters[parameters.length - 1] = param;
  36366. parameters[parameters.length - 2] = condition;
  36367. }
  36368. // Action or condition(s) and not CombineAction
  36369. var newAction = instanciate(parsedAction.name, parameters);
  36370. if (newAction instanceof BABYLON.Condition && condition !== null) {
  36371. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  36372. if (action)
  36373. action.then(nothing);
  36374. else
  36375. actionManager.registerAction(nothing);
  36376. action = nothing;
  36377. }
  36378. if (combineArray === null) {
  36379. if (newAction instanceof BABYLON.Condition) {
  36380. condition = newAction;
  36381. newAction = action;
  36382. }
  36383. else {
  36384. condition = null;
  36385. if (action)
  36386. action.then(newAction);
  36387. else
  36388. actionManager.registerAction(newAction);
  36389. }
  36390. }
  36391. else {
  36392. combineArray.push(newAction);
  36393. }
  36394. for (var i = 0; i < parsedAction.children.length; i++)
  36395. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  36396. };
  36397. // triggers
  36398. for (var i = 0; i < parsedActions.children.length; i++) {
  36399. var triggerParams;
  36400. var trigger = parsedActions.children[i];
  36401. if (trigger.properties.length > 0) {
  36402. var param = trigger.properties[0].value;
  36403. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  36404. if (value._meshId) {
  36405. value.mesh = scene.getMeshByID(value._meshId);
  36406. }
  36407. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  36408. }
  36409. else
  36410. triggerParams = BABYLON.ActionManager[trigger.name];
  36411. for (var j = 0; j < trigger.children.length; j++) {
  36412. if (!trigger.detached)
  36413. traverse(trigger.children[j], triggerParams, null, null);
  36414. }
  36415. }
  36416. };
  36417. ActionManager.GetTriggerName = function (trigger) {
  36418. switch (trigger) {
  36419. case 0: return "NothingTrigger";
  36420. case 1: return "OnPickTrigger";
  36421. case 2: return "OnLeftPickTrigger";
  36422. case 3: return "OnRightPickTrigger";
  36423. case 4: return "OnCenterPickTrigger";
  36424. case 5: return "OnPickDownTrigger";
  36425. case 6: return "OnPickUpTrigger";
  36426. case 7: return "OnLongPressTrigger";
  36427. case 8: return "OnPointerOverTrigger";
  36428. case 9: return "OnPointerOutTrigger";
  36429. case 10: return "OnEveryFrameTrigger";
  36430. case 11: return "OnIntersectionEnterTrigger";
  36431. case 12: return "OnIntersectionExitTrigger";
  36432. case 13: return "OnKeyDownTrigger";
  36433. case 14: return "OnKeyUpTrigger";
  36434. case 15: return "OnPickOutTrigger";
  36435. default: return "";
  36436. }
  36437. };
  36438. return ActionManager;
  36439. }());
  36440. // Statics
  36441. ActionManager._NothingTrigger = 0;
  36442. ActionManager._OnPickTrigger = 1;
  36443. ActionManager._OnLeftPickTrigger = 2;
  36444. ActionManager._OnRightPickTrigger = 3;
  36445. ActionManager._OnCenterPickTrigger = 4;
  36446. ActionManager._OnPickDownTrigger = 5;
  36447. ActionManager._OnDoublePickTrigger = 6;
  36448. ActionManager._OnPickUpTrigger = 7;
  36449. ActionManager._OnLongPressTrigger = 8;
  36450. ActionManager._OnPointerOverTrigger = 9;
  36451. ActionManager._OnPointerOutTrigger = 10;
  36452. ActionManager._OnEveryFrameTrigger = 11;
  36453. ActionManager._OnIntersectionEnterTrigger = 12;
  36454. ActionManager._OnIntersectionExitTrigger = 13;
  36455. ActionManager._OnKeyDownTrigger = 14;
  36456. ActionManager._OnKeyUpTrigger = 15;
  36457. ActionManager._OnPickOutTrigger = 16;
  36458. ActionManager.Triggers = {};
  36459. BABYLON.ActionManager = ActionManager;
  36460. })(BABYLON || (BABYLON = {}));
  36461. //# sourceMappingURL=babylon.actionManager.js.map
  36462. var BABYLON;
  36463. (function (BABYLON) {
  36464. var InterpolateValueAction = (function (_super) {
  36465. __extends(InterpolateValueAction, _super);
  36466. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  36467. if (duration === void 0) { duration = 1000; }
  36468. var _this = _super.call(this, triggerOptions, condition) || this;
  36469. _this.propertyPath = propertyPath;
  36470. _this.value = value;
  36471. _this.duration = duration;
  36472. _this.stopOtherAnimations = stopOtherAnimations;
  36473. _this.onInterpolationDone = onInterpolationDone;
  36474. _this._target = _this._effectiveTarget = target;
  36475. return _this;
  36476. }
  36477. InterpolateValueAction.prototype._prepare = function () {
  36478. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36479. this._property = this._getProperty(this.propertyPath);
  36480. };
  36481. InterpolateValueAction.prototype.execute = function () {
  36482. var scene = this._actionManager.getScene();
  36483. var keys = [
  36484. {
  36485. frame: 0,
  36486. value: this._effectiveTarget[this._property]
  36487. }, {
  36488. frame: 100,
  36489. value: this.value
  36490. }
  36491. ];
  36492. var dataType;
  36493. if (typeof this.value === "number") {
  36494. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  36495. }
  36496. else if (this.value instanceof BABYLON.Color3) {
  36497. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  36498. }
  36499. else if (this.value instanceof BABYLON.Vector3) {
  36500. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  36501. }
  36502. else if (this.value instanceof BABYLON.Matrix) {
  36503. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  36504. }
  36505. else if (this.value instanceof BABYLON.Quaternion) {
  36506. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  36507. }
  36508. else {
  36509. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  36510. return;
  36511. }
  36512. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36513. animation.setKeys(keys);
  36514. if (this.stopOtherAnimations) {
  36515. scene.stopAnimation(this._effectiveTarget);
  36516. }
  36517. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  36518. };
  36519. InterpolateValueAction.prototype.serialize = function (parent) {
  36520. return _super.prototype._serialize.call(this, {
  36521. name: "InterpolateValueAction",
  36522. properties: [
  36523. BABYLON.Action._GetTargetProperty(this._target),
  36524. { name: "propertyPath", value: this.propertyPath },
  36525. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36526. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  36527. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  36528. ]
  36529. }, parent);
  36530. };
  36531. return InterpolateValueAction;
  36532. }(BABYLON.Action));
  36533. BABYLON.InterpolateValueAction = InterpolateValueAction;
  36534. })(BABYLON || (BABYLON = {}));
  36535. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  36536. var BABYLON;
  36537. (function (BABYLON) {
  36538. var SwitchBooleanAction = (function (_super) {
  36539. __extends(SwitchBooleanAction, _super);
  36540. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  36541. var _this = _super.call(this, triggerOptions, condition) || this;
  36542. _this.propertyPath = propertyPath;
  36543. _this._target = _this._effectiveTarget = target;
  36544. return _this;
  36545. }
  36546. SwitchBooleanAction.prototype._prepare = function () {
  36547. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36548. this._property = this._getProperty(this.propertyPath);
  36549. };
  36550. SwitchBooleanAction.prototype.execute = function () {
  36551. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  36552. };
  36553. SwitchBooleanAction.prototype.serialize = function (parent) {
  36554. return _super.prototype._serialize.call(this, {
  36555. name: "SwitchBooleanAction",
  36556. properties: [
  36557. BABYLON.Action._GetTargetProperty(this._target),
  36558. { name: "propertyPath", value: this.propertyPath }
  36559. ]
  36560. }, parent);
  36561. };
  36562. return SwitchBooleanAction;
  36563. }(BABYLON.Action));
  36564. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  36565. var SetStateAction = (function (_super) {
  36566. __extends(SetStateAction, _super);
  36567. function SetStateAction(triggerOptions, target, value, condition) {
  36568. var _this = _super.call(this, triggerOptions, condition) || this;
  36569. _this.value = value;
  36570. _this._target = target;
  36571. return _this;
  36572. }
  36573. SetStateAction.prototype.execute = function () {
  36574. this._target.state = this.value;
  36575. };
  36576. SetStateAction.prototype.serialize = function (parent) {
  36577. return _super.prototype._serialize.call(this, {
  36578. name: "SetStateAction",
  36579. properties: [
  36580. BABYLON.Action._GetTargetProperty(this._target),
  36581. { name: "value", value: this.value }
  36582. ]
  36583. }, parent);
  36584. };
  36585. return SetStateAction;
  36586. }(BABYLON.Action));
  36587. BABYLON.SetStateAction = SetStateAction;
  36588. var SetValueAction = (function (_super) {
  36589. __extends(SetValueAction, _super);
  36590. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  36591. var _this = _super.call(this, triggerOptions, condition) || this;
  36592. _this.propertyPath = propertyPath;
  36593. _this.value = value;
  36594. _this._target = _this._effectiveTarget = target;
  36595. return _this;
  36596. }
  36597. SetValueAction.prototype._prepare = function () {
  36598. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36599. this._property = this._getProperty(this.propertyPath);
  36600. };
  36601. SetValueAction.prototype.execute = function () {
  36602. this._effectiveTarget[this._property] = this.value;
  36603. if (this._target.markAsDirty) {
  36604. this._target.markAsDirty(this._property);
  36605. }
  36606. };
  36607. SetValueAction.prototype.serialize = function (parent) {
  36608. return _super.prototype._serialize.call(this, {
  36609. name: "SetValueAction",
  36610. properties: [
  36611. BABYLON.Action._GetTargetProperty(this._target),
  36612. { name: "propertyPath", value: this.propertyPath },
  36613. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36614. ]
  36615. }, parent);
  36616. };
  36617. return SetValueAction;
  36618. }(BABYLON.Action));
  36619. BABYLON.SetValueAction = SetValueAction;
  36620. var IncrementValueAction = (function (_super) {
  36621. __extends(IncrementValueAction, _super);
  36622. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36623. var _this = _super.call(this, triggerOptions, condition) || this;
  36624. _this.propertyPath = propertyPath;
  36625. _this.value = value;
  36626. _this._target = _this._effectiveTarget = target;
  36627. return _this;
  36628. }
  36629. IncrementValueAction.prototype._prepare = function () {
  36630. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36631. this._property = this._getProperty(this.propertyPath);
  36632. if (typeof this._effectiveTarget[this._property] !== "number") {
  36633. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36634. }
  36635. };
  36636. IncrementValueAction.prototype.execute = function () {
  36637. this._effectiveTarget[this._property] += this.value;
  36638. if (this._target.markAsDirty) {
  36639. this._target.markAsDirty(this._property);
  36640. }
  36641. };
  36642. IncrementValueAction.prototype.serialize = function (parent) {
  36643. return _super.prototype._serialize.call(this, {
  36644. name: "IncrementValueAction",
  36645. properties: [
  36646. BABYLON.Action._GetTargetProperty(this._target),
  36647. { name: "propertyPath", value: this.propertyPath },
  36648. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36649. ]
  36650. }, parent);
  36651. };
  36652. return IncrementValueAction;
  36653. }(BABYLON.Action));
  36654. BABYLON.IncrementValueAction = IncrementValueAction;
  36655. var PlayAnimationAction = (function (_super) {
  36656. __extends(PlayAnimationAction, _super);
  36657. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36658. var _this = _super.call(this, triggerOptions, condition) || this;
  36659. _this.from = from;
  36660. _this.to = to;
  36661. _this.loop = loop;
  36662. _this._target = target;
  36663. return _this;
  36664. }
  36665. PlayAnimationAction.prototype._prepare = function () {
  36666. };
  36667. PlayAnimationAction.prototype.execute = function () {
  36668. var scene = this._actionManager.getScene();
  36669. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36670. };
  36671. PlayAnimationAction.prototype.serialize = function (parent) {
  36672. return _super.prototype._serialize.call(this, {
  36673. name: "PlayAnimationAction",
  36674. properties: [
  36675. BABYLON.Action._GetTargetProperty(this._target),
  36676. { name: "from", value: String(this.from) },
  36677. { name: "to", value: String(this.to) },
  36678. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36679. ]
  36680. }, parent);
  36681. };
  36682. return PlayAnimationAction;
  36683. }(BABYLON.Action));
  36684. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36685. var StopAnimationAction = (function (_super) {
  36686. __extends(StopAnimationAction, _super);
  36687. function StopAnimationAction(triggerOptions, target, condition) {
  36688. var _this = _super.call(this, triggerOptions, condition) || this;
  36689. _this._target = target;
  36690. return _this;
  36691. }
  36692. StopAnimationAction.prototype._prepare = function () {
  36693. };
  36694. StopAnimationAction.prototype.execute = function () {
  36695. var scene = this._actionManager.getScene();
  36696. scene.stopAnimation(this._target);
  36697. };
  36698. StopAnimationAction.prototype.serialize = function (parent) {
  36699. return _super.prototype._serialize.call(this, {
  36700. name: "StopAnimationAction",
  36701. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36702. }, parent);
  36703. };
  36704. return StopAnimationAction;
  36705. }(BABYLON.Action));
  36706. BABYLON.StopAnimationAction = StopAnimationAction;
  36707. var DoNothingAction = (function (_super) {
  36708. __extends(DoNothingAction, _super);
  36709. function DoNothingAction(triggerOptions, condition) {
  36710. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36711. return _super.call(this, triggerOptions, condition) || this;
  36712. }
  36713. DoNothingAction.prototype.execute = function () {
  36714. };
  36715. DoNothingAction.prototype.serialize = function (parent) {
  36716. return _super.prototype._serialize.call(this, {
  36717. name: "DoNothingAction",
  36718. properties: []
  36719. }, parent);
  36720. };
  36721. return DoNothingAction;
  36722. }(BABYLON.Action));
  36723. BABYLON.DoNothingAction = DoNothingAction;
  36724. var CombineAction = (function (_super) {
  36725. __extends(CombineAction, _super);
  36726. function CombineAction(triggerOptions, children, condition) {
  36727. var _this = _super.call(this, triggerOptions, condition) || this;
  36728. _this.children = children;
  36729. return _this;
  36730. }
  36731. CombineAction.prototype._prepare = function () {
  36732. for (var index = 0; index < this.children.length; index++) {
  36733. this.children[index]._actionManager = this._actionManager;
  36734. this.children[index]._prepare();
  36735. }
  36736. };
  36737. CombineAction.prototype.execute = function (evt) {
  36738. for (var index = 0; index < this.children.length; index++) {
  36739. this.children[index].execute(evt);
  36740. }
  36741. };
  36742. CombineAction.prototype.serialize = function (parent) {
  36743. var serializationObject = _super.prototype._serialize.call(this, {
  36744. name: "CombineAction",
  36745. properties: [],
  36746. combine: []
  36747. }, parent);
  36748. for (var i = 0; i < this.children.length; i++) {
  36749. serializationObject.combine.push(this.children[i].serialize(null));
  36750. }
  36751. return serializationObject;
  36752. };
  36753. return CombineAction;
  36754. }(BABYLON.Action));
  36755. BABYLON.CombineAction = CombineAction;
  36756. var ExecuteCodeAction = (function (_super) {
  36757. __extends(ExecuteCodeAction, _super);
  36758. function ExecuteCodeAction(triggerOptions, func, condition) {
  36759. var _this = _super.call(this, triggerOptions, condition) || this;
  36760. _this.func = func;
  36761. return _this;
  36762. }
  36763. ExecuteCodeAction.prototype.execute = function (evt) {
  36764. this.func(evt);
  36765. };
  36766. return ExecuteCodeAction;
  36767. }(BABYLON.Action));
  36768. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36769. var SetParentAction = (function (_super) {
  36770. __extends(SetParentAction, _super);
  36771. function SetParentAction(triggerOptions, target, parent, condition) {
  36772. var _this = _super.call(this, triggerOptions, condition) || this;
  36773. _this._target = target;
  36774. _this._parent = parent;
  36775. return _this;
  36776. }
  36777. SetParentAction.prototype._prepare = function () {
  36778. };
  36779. SetParentAction.prototype.execute = function () {
  36780. if (this._target.parent === this._parent) {
  36781. return;
  36782. }
  36783. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36784. invertParentWorldMatrix.invert();
  36785. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36786. this._target.parent = this._parent;
  36787. };
  36788. SetParentAction.prototype.serialize = function (parent) {
  36789. return _super.prototype._serialize.call(this, {
  36790. name: "SetParentAction",
  36791. properties: [
  36792. BABYLON.Action._GetTargetProperty(this._target),
  36793. BABYLON.Action._GetTargetProperty(this._parent),
  36794. ]
  36795. }, parent);
  36796. };
  36797. return SetParentAction;
  36798. }(BABYLON.Action));
  36799. BABYLON.SetParentAction = SetParentAction;
  36800. var PlaySoundAction = (function (_super) {
  36801. __extends(PlaySoundAction, _super);
  36802. function PlaySoundAction(triggerOptions, sound, condition) {
  36803. var _this = _super.call(this, triggerOptions, condition) || this;
  36804. _this._sound = sound;
  36805. return _this;
  36806. }
  36807. PlaySoundAction.prototype._prepare = function () {
  36808. };
  36809. PlaySoundAction.prototype.execute = function () {
  36810. if (this._sound !== undefined)
  36811. this._sound.play();
  36812. };
  36813. PlaySoundAction.prototype.serialize = function (parent) {
  36814. return _super.prototype._serialize.call(this, {
  36815. name: "PlaySoundAction",
  36816. properties: [{ name: "sound", value: this._sound.name }]
  36817. }, parent);
  36818. };
  36819. return PlaySoundAction;
  36820. }(BABYLON.Action));
  36821. BABYLON.PlaySoundAction = PlaySoundAction;
  36822. var StopSoundAction = (function (_super) {
  36823. __extends(StopSoundAction, _super);
  36824. function StopSoundAction(triggerOptions, sound, condition) {
  36825. var _this = _super.call(this, triggerOptions, condition) || this;
  36826. _this._sound = sound;
  36827. return _this;
  36828. }
  36829. StopSoundAction.prototype._prepare = function () {
  36830. };
  36831. StopSoundAction.prototype.execute = function () {
  36832. if (this._sound !== undefined)
  36833. this._sound.stop();
  36834. };
  36835. StopSoundAction.prototype.serialize = function (parent) {
  36836. return _super.prototype._serialize.call(this, {
  36837. name: "StopSoundAction",
  36838. properties: [{ name: "sound", value: this._sound.name }]
  36839. }, parent);
  36840. };
  36841. return StopSoundAction;
  36842. }(BABYLON.Action));
  36843. BABYLON.StopSoundAction = StopSoundAction;
  36844. })(BABYLON || (BABYLON = {}));
  36845. //# sourceMappingURL=babylon.directActions.js.map
  36846. var BABYLON;
  36847. (function (BABYLON) {
  36848. var SpriteManager = (function () {
  36849. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  36850. if (epsilon === void 0) { epsilon = 0.01; }
  36851. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36852. this.name = name;
  36853. this.sprites = new Array();
  36854. this.renderingGroupId = 0;
  36855. this.layerMask = 0x0FFFFFFF;
  36856. this.fogEnabled = true;
  36857. this.isPickable = false;
  36858. /**
  36859. * An event triggered when the manager is disposed.
  36860. * @type {BABYLON.Observable}
  36861. */
  36862. this.onDisposeObservable = new BABYLON.Observable();
  36863. this._vertexBuffers = {};
  36864. this._capacity = capacity;
  36865. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  36866. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36867. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36868. if (cellSize.width && cellSize.height) {
  36869. this.cellWidth = cellSize.width;
  36870. this.cellHeight = cellSize.height;
  36871. }
  36872. else if (cellSize !== undefined) {
  36873. this.cellWidth = cellSize;
  36874. this.cellHeight = cellSize;
  36875. }
  36876. else {
  36877. return;
  36878. }
  36879. this._epsilon = epsilon;
  36880. this._scene = scene;
  36881. this._scene.spriteManagers.push(this);
  36882. var indices = [];
  36883. var index = 0;
  36884. for (var count = 0; count < capacity; count++) {
  36885. indices.push(index);
  36886. indices.push(index + 1);
  36887. indices.push(index + 2);
  36888. indices.push(index);
  36889. indices.push(index + 2);
  36890. indices.push(index + 3);
  36891. index += 4;
  36892. }
  36893. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36894. // VBO
  36895. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  36896. this._vertexData = new Float32Array(capacity * 16 * 4);
  36897. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  36898. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  36899. var options = this._buffer.createVertexBuffer("options", 4, 4);
  36900. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  36901. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  36902. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36903. this._vertexBuffers["options"] = options;
  36904. this._vertexBuffers["cellInfo"] = cellInfo;
  36905. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36906. // Effects
  36907. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  36908. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  36909. }
  36910. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  36911. set: function (callback) {
  36912. if (this._onDisposeObserver) {
  36913. this.onDisposeObservable.remove(this._onDisposeObserver);
  36914. }
  36915. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36916. },
  36917. enumerable: true,
  36918. configurable: true
  36919. });
  36920. Object.defineProperty(SpriteManager.prototype, "texture", {
  36921. get: function () {
  36922. return this._spriteTexture;
  36923. },
  36924. set: function (value) {
  36925. this._spriteTexture = value;
  36926. },
  36927. enumerable: true,
  36928. configurable: true
  36929. });
  36930. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  36931. var arrayOffset = index * 16;
  36932. if (offsetX === 0)
  36933. offsetX = this._epsilon;
  36934. else if (offsetX === 1)
  36935. offsetX = 1 - this._epsilon;
  36936. if (offsetY === 0)
  36937. offsetY = this._epsilon;
  36938. else if (offsetY === 1)
  36939. offsetY = 1 - this._epsilon;
  36940. this._vertexData[arrayOffset] = sprite.position.x;
  36941. this._vertexData[arrayOffset + 1] = sprite.position.y;
  36942. this._vertexData[arrayOffset + 2] = sprite.position.z;
  36943. this._vertexData[arrayOffset + 3] = sprite.angle;
  36944. this._vertexData[arrayOffset + 4] = sprite.width;
  36945. this._vertexData[arrayOffset + 5] = sprite.height;
  36946. this._vertexData[arrayOffset + 6] = offsetX;
  36947. this._vertexData[arrayOffset + 7] = offsetY;
  36948. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  36949. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  36950. var offset = (sprite.cellIndex / rowSize) >> 0;
  36951. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  36952. this._vertexData[arrayOffset + 11] = offset;
  36953. // Color
  36954. this._vertexData[arrayOffset + 12] = sprite.color.r;
  36955. this._vertexData[arrayOffset + 13] = sprite.color.g;
  36956. this._vertexData[arrayOffset + 14] = sprite.color.b;
  36957. this._vertexData[arrayOffset + 15] = sprite.color.a;
  36958. };
  36959. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  36960. var count = Math.min(this._capacity, this.sprites.length);
  36961. var min = BABYLON.Vector3.Zero();
  36962. var max = BABYLON.Vector3.Zero();
  36963. var distance = Number.MAX_VALUE;
  36964. var currentSprite;
  36965. var cameraSpacePosition = BABYLON.Vector3.Zero();
  36966. var cameraView = camera.getViewMatrix();
  36967. for (var index = 0; index < count; index++) {
  36968. var sprite = this.sprites[index];
  36969. if (!sprite) {
  36970. continue;
  36971. }
  36972. if (predicate) {
  36973. if (!predicate(sprite)) {
  36974. continue;
  36975. }
  36976. }
  36977. else if (!sprite.isPickable) {
  36978. continue;
  36979. }
  36980. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  36981. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  36982. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  36983. if (ray.intersectsBoxMinMax(min, max)) {
  36984. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  36985. if (distance > currentDistance) {
  36986. distance = currentDistance;
  36987. currentSprite = sprite;
  36988. if (fastCheck) {
  36989. break;
  36990. }
  36991. }
  36992. }
  36993. }
  36994. if (currentSprite) {
  36995. var result = new BABYLON.PickingInfo();
  36996. result.hit = true;
  36997. result.pickedSprite = currentSprite;
  36998. result.distance = distance;
  36999. return result;
  37000. }
  37001. return null;
  37002. };
  37003. SpriteManager.prototype.render = function () {
  37004. // Check
  37005. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  37006. return;
  37007. var engine = this._scene.getEngine();
  37008. var baseSize = this._spriteTexture.getBaseSize();
  37009. // Sprites
  37010. var deltaTime = engine.getDeltaTime();
  37011. var max = Math.min(this._capacity, this.sprites.length);
  37012. var rowSize = baseSize.width / this.cellWidth;
  37013. var offset = 0;
  37014. for (var index = 0; index < max; index++) {
  37015. var sprite = this.sprites[index];
  37016. if (!sprite) {
  37017. continue;
  37018. }
  37019. sprite._animate(deltaTime);
  37020. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  37021. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  37022. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  37023. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  37024. }
  37025. this._buffer.update(this._vertexData);
  37026. // Render
  37027. var effect = this._effectBase;
  37028. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  37029. effect = this._effectFog;
  37030. }
  37031. engine.enableEffect(effect);
  37032. var viewMatrix = this._scene.getViewMatrix();
  37033. effect.setTexture("diffuseSampler", this._spriteTexture);
  37034. effect.setMatrix("view", viewMatrix);
  37035. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  37036. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  37037. // Fog
  37038. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  37039. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  37040. effect.setColor3("vFogColor", this._scene.fogColor);
  37041. }
  37042. // VBOs
  37043. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37044. // Draw order
  37045. engine.setDepthFunctionToLessOrEqual();
  37046. effect.setBool("alphaTest", true);
  37047. engine.setColorWrite(false);
  37048. engine.draw(true, 0, max * 6);
  37049. engine.setColorWrite(true);
  37050. effect.setBool("alphaTest", false);
  37051. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  37052. engine.draw(true, 0, max * 6);
  37053. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37054. };
  37055. SpriteManager.prototype.dispose = function () {
  37056. if (this._buffer) {
  37057. this._buffer.dispose();
  37058. this._buffer = null;
  37059. }
  37060. if (this._indexBuffer) {
  37061. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37062. this._indexBuffer = null;
  37063. }
  37064. if (this._spriteTexture) {
  37065. this._spriteTexture.dispose();
  37066. this._spriteTexture = null;
  37067. }
  37068. // Remove from scene
  37069. var index = this._scene.spriteManagers.indexOf(this);
  37070. this._scene.spriteManagers.splice(index, 1);
  37071. // Callback
  37072. this.onDisposeObservable.notifyObservers(this);
  37073. this.onDisposeObservable.clear();
  37074. };
  37075. return SpriteManager;
  37076. }());
  37077. BABYLON.SpriteManager = SpriteManager;
  37078. })(BABYLON || (BABYLON = {}));
  37079. //# sourceMappingURL=babylon.spriteManager.js.map
  37080. var BABYLON;
  37081. (function (BABYLON) {
  37082. var Sprite = (function () {
  37083. function Sprite(name, manager) {
  37084. this.name = name;
  37085. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37086. this.width = 1.0;
  37087. this.height = 1.0;
  37088. this.angle = 0;
  37089. this.cellIndex = 0;
  37090. this.invertU = 0;
  37091. this.invertV = 0;
  37092. this.animations = new Array();
  37093. this.isPickable = false;
  37094. this._animationStarted = false;
  37095. this._loopAnimation = false;
  37096. this._fromIndex = 0;
  37097. this._toIndex = 0;
  37098. this._delay = 0;
  37099. this._direction = 1;
  37100. this._frameCount = 0;
  37101. this._time = 0;
  37102. this._manager = manager;
  37103. this._manager.sprites.push(this);
  37104. this.position = BABYLON.Vector3.Zero();
  37105. }
  37106. Object.defineProperty(Sprite.prototype, "size", {
  37107. get: function () {
  37108. return this.width;
  37109. },
  37110. set: function (value) {
  37111. this.width = value;
  37112. this.height = value;
  37113. },
  37114. enumerable: true,
  37115. configurable: true
  37116. });
  37117. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  37118. this._fromIndex = from;
  37119. this._toIndex = to;
  37120. this._loopAnimation = loop;
  37121. this._delay = delay;
  37122. this._animationStarted = true;
  37123. this._direction = from < to ? 1 : -1;
  37124. this.cellIndex = from;
  37125. this._time = 0;
  37126. this._onAnimationEnd = onAnimationEnd;
  37127. };
  37128. Sprite.prototype.stopAnimation = function () {
  37129. this._animationStarted = false;
  37130. };
  37131. Sprite.prototype._animate = function (deltaTime) {
  37132. if (!this._animationStarted)
  37133. return;
  37134. this._time += deltaTime;
  37135. if (this._time > this._delay) {
  37136. this._time = this._time % this._delay;
  37137. this.cellIndex += this._direction;
  37138. if (this.cellIndex === this._toIndex) {
  37139. if (this._loopAnimation) {
  37140. this.cellIndex = this._fromIndex;
  37141. }
  37142. else {
  37143. this._animationStarted = false;
  37144. if (this._onAnimationEnd) {
  37145. this._onAnimationEnd();
  37146. }
  37147. if (this.disposeWhenFinishedAnimating) {
  37148. this.dispose();
  37149. }
  37150. }
  37151. }
  37152. }
  37153. };
  37154. Sprite.prototype.dispose = function () {
  37155. for (var i = 0; i < this._manager.sprites.length; i++) {
  37156. if (this._manager.sprites[i] == this) {
  37157. this._manager.sprites.splice(i, 1);
  37158. }
  37159. }
  37160. };
  37161. return Sprite;
  37162. }());
  37163. BABYLON.Sprite = Sprite;
  37164. })(BABYLON || (BABYLON = {}));
  37165. //# sourceMappingURL=babylon.sprite.js.map
  37166. var BABYLON;
  37167. (function (BABYLON) {
  37168. var IntersectionInfo = (function () {
  37169. function IntersectionInfo(bu, bv, distance) {
  37170. this.bu = bu;
  37171. this.bv = bv;
  37172. this.distance = distance;
  37173. this.faceId = 0;
  37174. this.subMeshId = 0;
  37175. }
  37176. return IntersectionInfo;
  37177. }());
  37178. BABYLON.IntersectionInfo = IntersectionInfo;
  37179. var PickingInfo = (function () {
  37180. function PickingInfo() {
  37181. this.hit = false;
  37182. this.distance = 0;
  37183. this.pickedPoint = null;
  37184. this.pickedMesh = null;
  37185. this.bu = 0;
  37186. this.bv = 0;
  37187. this.faceId = -1;
  37188. this.subMeshId = 0;
  37189. this.pickedSprite = null;
  37190. }
  37191. // Methods
  37192. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  37193. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  37194. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  37195. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37196. return null;
  37197. }
  37198. var indices = this.pickedMesh.getIndices();
  37199. var result;
  37200. if (useVerticesNormals) {
  37201. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37202. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  37203. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  37204. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  37205. normal0 = normal0.scale(this.bu);
  37206. normal1 = normal1.scale(this.bv);
  37207. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  37208. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  37209. }
  37210. else {
  37211. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37212. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  37213. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  37214. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  37215. var p1p2 = vertex1.subtract(vertex2);
  37216. var p3p2 = vertex3.subtract(vertex2);
  37217. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  37218. }
  37219. if (useWorldCoordinates) {
  37220. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  37221. }
  37222. return BABYLON.Vector3.Normalize(result);
  37223. };
  37224. PickingInfo.prototype.getTextureCoordinates = function () {
  37225. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37226. return null;
  37227. }
  37228. var indices = this.pickedMesh.getIndices();
  37229. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37230. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  37231. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  37232. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  37233. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  37234. uv1 = uv1.scale(this.bu);
  37235. uv2 = uv2.scale(this.bv);
  37236. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  37237. };
  37238. return PickingInfo;
  37239. }());
  37240. BABYLON.PickingInfo = PickingInfo;
  37241. })(BABYLON || (BABYLON = {}));
  37242. //# sourceMappingURL=babylon.pickingInfo.js.map
  37243. var BABYLON;
  37244. (function (BABYLON) {
  37245. var Ray = (function () {
  37246. function Ray(origin, direction, length) {
  37247. if (length === void 0) { length = Number.MAX_VALUE; }
  37248. this.origin = origin;
  37249. this.direction = direction;
  37250. this.length = length;
  37251. }
  37252. // Methods
  37253. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  37254. var d = 0.0;
  37255. var maxValue = Number.MAX_VALUE;
  37256. var inv;
  37257. var min;
  37258. var max;
  37259. var temp;
  37260. if (Math.abs(this.direction.x) < 0.0000001) {
  37261. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  37262. return false;
  37263. }
  37264. }
  37265. else {
  37266. inv = 1.0 / this.direction.x;
  37267. min = (minimum.x - this.origin.x) * inv;
  37268. max = (maximum.x - this.origin.x) * inv;
  37269. if (max === -Infinity) {
  37270. max = Infinity;
  37271. }
  37272. if (min > max) {
  37273. temp = min;
  37274. min = max;
  37275. max = temp;
  37276. }
  37277. d = Math.max(min, d);
  37278. maxValue = Math.min(max, maxValue);
  37279. if (d > maxValue) {
  37280. return false;
  37281. }
  37282. }
  37283. if (Math.abs(this.direction.y) < 0.0000001) {
  37284. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  37285. return false;
  37286. }
  37287. }
  37288. else {
  37289. inv = 1.0 / this.direction.y;
  37290. min = (minimum.y - this.origin.y) * inv;
  37291. max = (maximum.y - this.origin.y) * inv;
  37292. if (max === -Infinity) {
  37293. max = Infinity;
  37294. }
  37295. if (min > max) {
  37296. temp = min;
  37297. min = max;
  37298. max = temp;
  37299. }
  37300. d = Math.max(min, d);
  37301. maxValue = Math.min(max, maxValue);
  37302. if (d > maxValue) {
  37303. return false;
  37304. }
  37305. }
  37306. if (Math.abs(this.direction.z) < 0.0000001) {
  37307. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  37308. return false;
  37309. }
  37310. }
  37311. else {
  37312. inv = 1.0 / this.direction.z;
  37313. min = (minimum.z - this.origin.z) * inv;
  37314. max = (maximum.z - this.origin.z) * inv;
  37315. if (max === -Infinity) {
  37316. max = Infinity;
  37317. }
  37318. if (min > max) {
  37319. temp = min;
  37320. min = max;
  37321. max = temp;
  37322. }
  37323. d = Math.max(min, d);
  37324. maxValue = Math.min(max, maxValue);
  37325. if (d > maxValue) {
  37326. return false;
  37327. }
  37328. }
  37329. return true;
  37330. };
  37331. Ray.prototype.intersectsBox = function (box) {
  37332. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  37333. };
  37334. Ray.prototype.intersectsSphere = function (sphere) {
  37335. var x = sphere.center.x - this.origin.x;
  37336. var y = sphere.center.y - this.origin.y;
  37337. var z = sphere.center.z - this.origin.z;
  37338. var pyth = (x * x) + (y * y) + (z * z);
  37339. var rr = sphere.radius * sphere.radius;
  37340. if (pyth <= rr) {
  37341. return true;
  37342. }
  37343. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  37344. if (dot < 0.0) {
  37345. return false;
  37346. }
  37347. var temp = pyth - (dot * dot);
  37348. return temp <= rr;
  37349. };
  37350. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  37351. if (!this._edge1) {
  37352. this._edge1 = BABYLON.Vector3.Zero();
  37353. this._edge2 = BABYLON.Vector3.Zero();
  37354. this._pvec = BABYLON.Vector3.Zero();
  37355. this._tvec = BABYLON.Vector3.Zero();
  37356. this._qvec = BABYLON.Vector3.Zero();
  37357. }
  37358. vertex1.subtractToRef(vertex0, this._edge1);
  37359. vertex2.subtractToRef(vertex0, this._edge2);
  37360. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  37361. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  37362. if (det === 0) {
  37363. return null;
  37364. }
  37365. var invdet = 1 / det;
  37366. this.origin.subtractToRef(vertex0, this._tvec);
  37367. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  37368. if (bu < 0 || bu > 1.0) {
  37369. return null;
  37370. }
  37371. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  37372. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  37373. if (bv < 0 || bu + bv > 1.0) {
  37374. return null;
  37375. }
  37376. //check if the distance is longer than the predefined length.
  37377. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  37378. if (distance > this.length) {
  37379. return null;
  37380. }
  37381. return new BABYLON.IntersectionInfo(bu, bv, distance);
  37382. };
  37383. Ray.prototype.intersectsPlane = function (plane) {
  37384. var distance;
  37385. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  37386. if (Math.abs(result1) < 9.99999997475243E-07) {
  37387. return null;
  37388. }
  37389. else {
  37390. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  37391. distance = (-plane.d - result2) / result1;
  37392. if (distance < 0.0) {
  37393. if (distance < -9.99999997475243E-07) {
  37394. return null;
  37395. }
  37396. else {
  37397. return 0;
  37398. }
  37399. }
  37400. return distance;
  37401. }
  37402. };
  37403. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  37404. var tm = BABYLON.Tmp.Matrix[0];
  37405. mesh.getWorldMatrix().invertToRef(tm);
  37406. if (this._tmpRay) {
  37407. Ray.TransformToRef(this, tm, this._tmpRay);
  37408. }
  37409. else {
  37410. this._tmpRay = Ray.Transform(this, tm);
  37411. }
  37412. return mesh.intersects(this._tmpRay, fastCheck);
  37413. };
  37414. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  37415. if (results) {
  37416. results.length = 0;
  37417. }
  37418. else {
  37419. results = [];
  37420. }
  37421. for (var i = 0; i < meshes.length; i++) {
  37422. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  37423. if (pickInfo.hit) {
  37424. results.push(pickInfo);
  37425. }
  37426. }
  37427. results.sort(this._comparePickingInfo);
  37428. return results;
  37429. };
  37430. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  37431. if (pickingInfoA.distance < pickingInfoB.distance) {
  37432. return -1;
  37433. }
  37434. else if (pickingInfoA.distance > pickingInfoB.distance) {
  37435. return 1;
  37436. }
  37437. else {
  37438. return 0;
  37439. }
  37440. };
  37441. /**
  37442. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  37443. * @param sega the first point of the segment to test the intersection against
  37444. * @param segb the second point of the segment to test the intersection against
  37445. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  37446. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  37447. */
  37448. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  37449. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  37450. var u = segb.subtract(sega);
  37451. var v = rsegb.subtract(this.origin);
  37452. var w = sega.subtract(this.origin);
  37453. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  37454. var b = BABYLON.Vector3.Dot(u, v);
  37455. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  37456. var d = BABYLON.Vector3.Dot(u, w);
  37457. var e = BABYLON.Vector3.Dot(v, w);
  37458. var D = a * c - b * b; // always >= 0
  37459. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  37460. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  37461. // compute the line parameters of the two closest points
  37462. if (D < Ray.smallnum) {
  37463. sN = 0.0; // force using point P0 on segment S1
  37464. sD = 1.0; // to prevent possible division by 0.0 later
  37465. tN = e;
  37466. tD = c;
  37467. }
  37468. else {
  37469. sN = (b * e - c * d);
  37470. tN = (a * e - b * d);
  37471. if (sN < 0.0) {
  37472. sN = 0.0;
  37473. tN = e;
  37474. tD = c;
  37475. }
  37476. else if (sN > sD) {
  37477. sN = sD;
  37478. tN = e + b;
  37479. tD = c;
  37480. }
  37481. }
  37482. if (tN < 0.0) {
  37483. tN = 0.0;
  37484. // recompute sc for this edge
  37485. if (-d < 0.0) {
  37486. sN = 0.0;
  37487. }
  37488. else if (-d > a)
  37489. sN = sD;
  37490. else {
  37491. sN = -d;
  37492. sD = a;
  37493. }
  37494. }
  37495. else if (tN > tD) {
  37496. tN = tD;
  37497. // recompute sc for this edge
  37498. if ((-d + b) < 0.0) {
  37499. sN = 0;
  37500. }
  37501. else if ((-d + b) > a) {
  37502. sN = sD;
  37503. }
  37504. else {
  37505. sN = (-d + b);
  37506. sD = a;
  37507. }
  37508. }
  37509. // finally do the division to get sc and tc
  37510. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  37511. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  37512. // get the difference of the two closest points
  37513. var qtc = v.multiplyByFloats(tc, tc, tc);
  37514. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  37515. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  37516. if (isIntersected) {
  37517. return qtc.length();
  37518. }
  37519. return -1;
  37520. };
  37521. // Statics
  37522. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  37523. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  37524. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  37525. var direction = end.subtract(start);
  37526. direction.normalize();
  37527. return new Ray(start, direction);
  37528. };
  37529. /**
  37530. * 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
  37531. * transformed to the given world matrix.
  37532. * @param origin The origin point
  37533. * @param end The end point
  37534. * @param world a matrix to transform the ray to. Default is the identity matrix.
  37535. */
  37536. Ray.CreateNewFromTo = function (origin, end, world) {
  37537. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  37538. var direction = end.subtract(origin);
  37539. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  37540. direction.normalize();
  37541. return Ray.Transform(new Ray(origin, direction, length), world);
  37542. };
  37543. Ray.Transform = function (ray, matrix) {
  37544. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  37545. Ray.TransformToRef(ray, matrix, result);
  37546. return result;
  37547. };
  37548. Ray.TransformToRef = function (ray, matrix, result) {
  37549. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  37550. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  37551. result.length = ray.length;
  37552. var dir = result.direction;
  37553. var len = dir.length();
  37554. if (!(len === 0 || len === 1)) {
  37555. var num = 1.0 / len;
  37556. dir.x *= num;
  37557. dir.y *= num;
  37558. dir.z *= num;
  37559. result.length *= len;
  37560. }
  37561. };
  37562. return Ray;
  37563. }());
  37564. Ray.smallnum = 0.00000001;
  37565. Ray.rayl = 10e8;
  37566. BABYLON.Ray = Ray;
  37567. })(BABYLON || (BABYLON = {}));
  37568. //# sourceMappingURL=babylon.ray.js.map
  37569. var BABYLON;
  37570. (function (BABYLON) {
  37571. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  37572. if (boxMin.x > sphereCenter.x + sphereRadius)
  37573. return false;
  37574. if (sphereCenter.x - sphereRadius > boxMax.x)
  37575. return false;
  37576. if (boxMin.y > sphereCenter.y + sphereRadius)
  37577. return false;
  37578. if (sphereCenter.y - sphereRadius > boxMax.y)
  37579. return false;
  37580. if (boxMin.z > sphereCenter.z + sphereRadius)
  37581. return false;
  37582. if (sphereCenter.z - sphereRadius > boxMax.z)
  37583. return false;
  37584. return true;
  37585. };
  37586. var getLowestRoot = (function () {
  37587. var result = { root: 0, found: false };
  37588. return function (a, b, c, maxR) {
  37589. result.root = 0;
  37590. result.found = false;
  37591. var determinant = b * b - 4.0 * a * c;
  37592. if (determinant < 0)
  37593. return result;
  37594. var sqrtD = Math.sqrt(determinant);
  37595. var r1 = (-b - sqrtD) / (2.0 * a);
  37596. var r2 = (-b + sqrtD) / (2.0 * a);
  37597. if (r1 > r2) {
  37598. var temp = r2;
  37599. r2 = r1;
  37600. r1 = temp;
  37601. }
  37602. if (r1 > 0 && r1 < maxR) {
  37603. result.root = r1;
  37604. result.found = true;
  37605. return result;
  37606. }
  37607. if (r2 > 0 && r2 < maxR) {
  37608. result.root = r2;
  37609. result.found = true;
  37610. return result;
  37611. }
  37612. return result;
  37613. };
  37614. })();
  37615. var Collider = (function () {
  37616. function Collider() {
  37617. this.radius = BABYLON.Vector3.One();
  37618. this.retry = 0;
  37619. this.basePointWorld = BABYLON.Vector3.Zero();
  37620. this.velocityWorld = BABYLON.Vector3.Zero();
  37621. this.normalizedVelocity = BABYLON.Vector3.Zero();
  37622. this._collisionPoint = BABYLON.Vector3.Zero();
  37623. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  37624. this._tempVector = BABYLON.Vector3.Zero();
  37625. this._tempVector2 = BABYLON.Vector3.Zero();
  37626. this._tempVector3 = BABYLON.Vector3.Zero();
  37627. this._tempVector4 = BABYLON.Vector3.Zero();
  37628. this._edge = BABYLON.Vector3.Zero();
  37629. this._baseToVertex = BABYLON.Vector3.Zero();
  37630. this._destinationPoint = BABYLON.Vector3.Zero();
  37631. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  37632. this._displacementVector = BABYLON.Vector3.Zero();
  37633. this._collisionMask = -1;
  37634. }
  37635. Object.defineProperty(Collider.prototype, "collisionMask", {
  37636. get: function () {
  37637. return this._collisionMask;
  37638. },
  37639. set: function (mask) {
  37640. this._collisionMask = !isNaN(mask) ? mask : -1;
  37641. },
  37642. enumerable: true,
  37643. configurable: true
  37644. });
  37645. // Methods
  37646. Collider.prototype._initialize = function (source, dir, e) {
  37647. this.velocity = dir;
  37648. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  37649. this.basePoint = source;
  37650. source.multiplyToRef(this.radius, this.basePointWorld);
  37651. dir.multiplyToRef(this.radius, this.velocityWorld);
  37652. this.velocityWorldLength = this.velocityWorld.length();
  37653. this.epsilon = e;
  37654. this.collisionFound = false;
  37655. };
  37656. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  37657. pa.subtractToRef(point, this._tempVector);
  37658. pb.subtractToRef(point, this._tempVector2);
  37659. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  37660. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37661. if (d < 0)
  37662. return false;
  37663. pc.subtractToRef(point, this._tempVector3);
  37664. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  37665. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37666. if (d < 0)
  37667. return false;
  37668. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  37669. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37670. return d >= 0;
  37671. };
  37672. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  37673. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  37674. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  37675. if (distance > this.velocityWorldLength + max + sphereRadius) {
  37676. return false;
  37677. }
  37678. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  37679. return false;
  37680. return true;
  37681. };
  37682. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  37683. var t0;
  37684. var embeddedInPlane = false;
  37685. //defensive programming, actually not needed.
  37686. if (!trianglePlaneArray) {
  37687. trianglePlaneArray = [];
  37688. }
  37689. if (!trianglePlaneArray[faceIndex]) {
  37690. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  37691. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  37692. }
  37693. var trianglePlane = trianglePlaneArray[faceIndex];
  37694. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  37695. return;
  37696. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  37697. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  37698. if (normalDotVelocity == 0) {
  37699. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  37700. return;
  37701. embeddedInPlane = true;
  37702. t0 = 0;
  37703. }
  37704. else {
  37705. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37706. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37707. if (t0 > t1) {
  37708. var temp = t1;
  37709. t1 = t0;
  37710. t0 = temp;
  37711. }
  37712. if (t0 > 1.0 || t1 < 0.0)
  37713. return;
  37714. if (t0 < 0)
  37715. t0 = 0;
  37716. if (t0 > 1.0)
  37717. t0 = 1.0;
  37718. }
  37719. this._collisionPoint.copyFromFloats(0, 0, 0);
  37720. var found = false;
  37721. var t = 1.0;
  37722. if (!embeddedInPlane) {
  37723. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  37724. this.velocity.scaleToRef(t0, this._tempVector);
  37725. this._planeIntersectionPoint.addInPlace(this._tempVector);
  37726. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  37727. found = true;
  37728. t = t0;
  37729. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  37730. }
  37731. }
  37732. if (!found) {
  37733. var velocitySquaredLength = this.velocity.lengthSquared();
  37734. var a = velocitySquaredLength;
  37735. this.basePoint.subtractToRef(p1, this._tempVector);
  37736. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37737. var c = this._tempVector.lengthSquared() - 1.0;
  37738. var lowestRoot = getLowestRoot(a, b, c, t);
  37739. if (lowestRoot.found) {
  37740. t = lowestRoot.root;
  37741. found = true;
  37742. this._collisionPoint.copyFrom(p1);
  37743. }
  37744. this.basePoint.subtractToRef(p2, this._tempVector);
  37745. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37746. c = this._tempVector.lengthSquared() - 1.0;
  37747. lowestRoot = getLowestRoot(a, b, c, t);
  37748. if (lowestRoot.found) {
  37749. t = lowestRoot.root;
  37750. found = true;
  37751. this._collisionPoint.copyFrom(p2);
  37752. }
  37753. this.basePoint.subtractToRef(p3, 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(p3);
  37761. }
  37762. p2.subtractToRef(p1, this._edge);
  37763. p1.subtractToRef(this.basePoint, this._baseToVertex);
  37764. var edgeSquaredLength = this._edge.lengthSquared();
  37765. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37766. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37767. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37768. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37769. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37770. lowestRoot = getLowestRoot(a, b, c, t);
  37771. if (lowestRoot.found) {
  37772. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37773. if (f >= 0.0 && f <= 1.0) {
  37774. t = lowestRoot.root;
  37775. found = true;
  37776. this._edge.scaleInPlace(f);
  37777. p1.addToRef(this._edge, this._collisionPoint);
  37778. }
  37779. }
  37780. p3.subtractToRef(p2, this._edge);
  37781. p2.subtractToRef(this.basePoint, this._baseToVertex);
  37782. edgeSquaredLength = this._edge.lengthSquared();
  37783. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37784. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37785. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37786. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37787. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37788. lowestRoot = getLowestRoot(a, b, c, t);
  37789. if (lowestRoot.found) {
  37790. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37791. if (f >= 0.0 && f <= 1.0) {
  37792. t = lowestRoot.root;
  37793. found = true;
  37794. this._edge.scaleInPlace(f);
  37795. p2.addToRef(this._edge, this._collisionPoint);
  37796. }
  37797. }
  37798. p1.subtractToRef(p3, this._edge);
  37799. p3.subtractToRef(this.basePoint, this._baseToVertex);
  37800. edgeSquaredLength = this._edge.lengthSquared();
  37801. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37802. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37803. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37804. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37805. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37806. lowestRoot = getLowestRoot(a, b, c, t);
  37807. if (lowestRoot.found) {
  37808. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37809. if (f >= 0.0 && f <= 1.0) {
  37810. t = lowestRoot.root;
  37811. found = true;
  37812. this._edge.scaleInPlace(f);
  37813. p3.addToRef(this._edge, this._collisionPoint);
  37814. }
  37815. }
  37816. }
  37817. if (found) {
  37818. var distToCollision = t * this.velocity.length();
  37819. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  37820. if (!this.intersectionPoint) {
  37821. this.intersectionPoint = this._collisionPoint.clone();
  37822. }
  37823. else {
  37824. this.intersectionPoint.copyFrom(this._collisionPoint);
  37825. }
  37826. this.nearestDistance = distToCollision;
  37827. this.collisionFound = true;
  37828. }
  37829. }
  37830. };
  37831. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  37832. for (var i = indexStart; i < indexEnd; i += 3) {
  37833. var p1 = pts[indices[i] - decal];
  37834. var p2 = pts[indices[i + 1] - decal];
  37835. var p3 = pts[indices[i + 2] - decal];
  37836. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  37837. }
  37838. };
  37839. Collider.prototype._getResponse = function (pos, vel) {
  37840. pos.addToRef(vel, this._destinationPoint);
  37841. vel.scaleInPlace((this.nearestDistance / vel.length()));
  37842. this.basePoint.addToRef(vel, pos);
  37843. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  37844. this._slidePlaneNormal.normalize();
  37845. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  37846. pos.addInPlace(this._displacementVector);
  37847. this.intersectionPoint.addInPlace(this._displacementVector);
  37848. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  37849. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  37850. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  37851. };
  37852. return Collider;
  37853. }());
  37854. BABYLON.Collider = Collider;
  37855. })(BABYLON || (BABYLON = {}));
  37856. //# sourceMappingURL=babylon.collider.js.map
  37857. var BABYLON;
  37858. (function (BABYLON) {
  37859. //WebWorker code will be inserted to this variable.
  37860. BABYLON.CollisionWorker = "";
  37861. var WorkerTaskType;
  37862. (function (WorkerTaskType) {
  37863. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  37864. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  37865. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  37866. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  37867. var WorkerReplyType;
  37868. (function (WorkerReplyType) {
  37869. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  37870. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  37871. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  37872. var CollisionCoordinatorWorker = (function () {
  37873. function CollisionCoordinatorWorker() {
  37874. var _this = this;
  37875. this._scaledPosition = BABYLON.Vector3.Zero();
  37876. this._scaledVelocity = BABYLON.Vector3.Zero();
  37877. this.onMeshUpdated = function (mesh) {
  37878. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  37879. };
  37880. this.onGeometryUpdated = function (geometry) {
  37881. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  37882. };
  37883. this._afterRender = function () {
  37884. if (!_this._init)
  37885. return;
  37886. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  37887. return;
  37888. }
  37889. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  37890. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  37891. if (_this._runningUpdated > 4) {
  37892. return;
  37893. }
  37894. ++_this._runningUpdated;
  37895. var payload = {
  37896. updatedMeshes: _this._addUpdateMeshesList,
  37897. updatedGeometries: _this._addUpdateGeometriesList,
  37898. removedGeometries: _this._toRemoveGeometryArray,
  37899. removedMeshes: _this._toRemoveMeshesArray
  37900. };
  37901. var message = {
  37902. payload: payload,
  37903. taskType: WorkerTaskType.UPDATE
  37904. };
  37905. var serializable = [];
  37906. for (var id in payload.updatedGeometries) {
  37907. if (payload.updatedGeometries.hasOwnProperty(id)) {
  37908. //prepare transferables
  37909. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  37910. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  37911. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  37912. }
  37913. }
  37914. _this._worker.postMessage(message, serializable);
  37915. _this._addUpdateMeshesList = {};
  37916. _this._addUpdateGeometriesList = {};
  37917. _this._toRemoveGeometryArray = [];
  37918. _this._toRemoveMeshesArray = [];
  37919. };
  37920. this._onMessageFromWorker = function (e) {
  37921. var returnData = e.data;
  37922. if (returnData.error != WorkerReplyType.SUCCESS) {
  37923. //TODO what errors can be returned from the worker?
  37924. BABYLON.Tools.Warn("error returned from worker!");
  37925. return;
  37926. }
  37927. switch (returnData.taskType) {
  37928. case WorkerTaskType.INIT:
  37929. _this._init = true;
  37930. //Update the worked with ALL of the scene's current state
  37931. _this._scene.meshes.forEach(function (mesh) {
  37932. _this.onMeshAdded(mesh);
  37933. });
  37934. _this._scene.getGeometries().forEach(function (geometry) {
  37935. _this.onGeometryAdded(geometry);
  37936. });
  37937. break;
  37938. case WorkerTaskType.UPDATE:
  37939. _this._runningUpdated--;
  37940. break;
  37941. case WorkerTaskType.COLLIDE:
  37942. _this._runningCollisionTask = false;
  37943. var returnPayload = returnData.payload;
  37944. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  37945. return;
  37946. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  37947. //cleanup
  37948. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  37949. break;
  37950. }
  37951. };
  37952. this._collisionsCallbackArray = [];
  37953. this._init = false;
  37954. this._runningUpdated = 0;
  37955. this._runningCollisionTask = false;
  37956. this._addUpdateMeshesList = {};
  37957. this._addUpdateGeometriesList = {};
  37958. this._toRemoveGeometryArray = [];
  37959. this._toRemoveMeshesArray = [];
  37960. }
  37961. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37962. if (!this._init)
  37963. return;
  37964. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  37965. return;
  37966. position.divideToRef(collider.radius, this._scaledPosition);
  37967. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37968. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  37969. var payload = {
  37970. collider: {
  37971. position: this._scaledPosition.asArray(),
  37972. velocity: this._scaledVelocity.asArray(),
  37973. radius: collider.radius.asArray()
  37974. },
  37975. collisionId: collisionIndex,
  37976. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  37977. maximumRetry: maximumRetry
  37978. };
  37979. var message = {
  37980. payload: payload,
  37981. taskType: WorkerTaskType.COLLIDE
  37982. };
  37983. this._worker.postMessage(message);
  37984. };
  37985. CollisionCoordinatorWorker.prototype.init = function (scene) {
  37986. this._scene = scene;
  37987. this._scene.registerAfterRender(this._afterRender);
  37988. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  37989. this._worker = new Worker(workerUrl);
  37990. this._worker.onmessage = this._onMessageFromWorker;
  37991. var message = {
  37992. payload: {},
  37993. taskType: WorkerTaskType.INIT
  37994. };
  37995. this._worker.postMessage(message);
  37996. };
  37997. CollisionCoordinatorWorker.prototype.destroy = function () {
  37998. this._scene.unregisterAfterRender(this._afterRender);
  37999. this._worker.terminate();
  38000. };
  38001. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  38002. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  38003. this.onMeshUpdated(mesh);
  38004. };
  38005. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  38006. this._toRemoveMeshesArray.push(mesh.uniqueId);
  38007. };
  38008. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  38009. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  38010. geometry.onGeometryUpdated = this.onGeometryUpdated;
  38011. this.onGeometryUpdated(geometry);
  38012. };
  38013. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  38014. this._toRemoveGeometryArray.push(geometry.id);
  38015. };
  38016. return CollisionCoordinatorWorker;
  38017. }());
  38018. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  38019. var submeshes = [];
  38020. if (mesh.subMeshes) {
  38021. submeshes = mesh.subMeshes.map(function (sm, idx) {
  38022. return {
  38023. position: idx,
  38024. verticesStart: sm.verticesStart,
  38025. verticesCount: sm.verticesCount,
  38026. indexStart: sm.indexStart,
  38027. indexCount: sm.indexCount,
  38028. hasMaterial: !!sm.getMaterial(),
  38029. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  38030. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  38031. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  38032. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  38033. };
  38034. });
  38035. }
  38036. var geometryId = null;
  38037. if (mesh instanceof BABYLON.Mesh) {
  38038. geometryId = mesh.geometry ? mesh.geometry.id : null;
  38039. }
  38040. else if (mesh instanceof BABYLON.InstancedMesh) {
  38041. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  38042. }
  38043. return {
  38044. uniqueId: mesh.uniqueId,
  38045. id: mesh.id,
  38046. name: mesh.name,
  38047. geometryId: geometryId,
  38048. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  38049. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  38050. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  38051. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  38052. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  38053. subMeshes: submeshes,
  38054. checkCollisions: mesh.checkCollisions
  38055. };
  38056. };
  38057. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  38058. return {
  38059. id: geometry.id,
  38060. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  38061. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  38062. indices: new Uint32Array(geometry.getIndices() || []),
  38063. };
  38064. };
  38065. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  38066. var CollisionCoordinatorLegacy = (function () {
  38067. function CollisionCoordinatorLegacy() {
  38068. this._scaledPosition = BABYLON.Vector3.Zero();
  38069. this._scaledVelocity = BABYLON.Vector3.Zero();
  38070. this._finalPosition = BABYLON.Vector3.Zero();
  38071. }
  38072. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  38073. position.divideToRef(collider.radius, this._scaledPosition);
  38074. velocity.divideToRef(collider.radius, this._scaledVelocity);
  38075. collider.collidedMesh = null;
  38076. collider.retry = 0;
  38077. collider.initialVelocity = this._scaledVelocity;
  38078. collider.initialPosition = this._scaledPosition;
  38079. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  38080. this._finalPosition.multiplyInPlace(collider.radius);
  38081. //run the callback
  38082. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  38083. };
  38084. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  38085. this._scene = scene;
  38086. };
  38087. CollisionCoordinatorLegacy.prototype.destroy = function () {
  38088. //Legacy need no destruction method.
  38089. };
  38090. //No update in legacy mode
  38091. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  38092. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  38093. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  38094. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  38095. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  38096. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  38097. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  38098. if (excludedMesh === void 0) { excludedMesh = null; }
  38099. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  38100. if (collider.retry >= maximumRetry) {
  38101. finalPosition.copyFrom(position);
  38102. return;
  38103. }
  38104. // Check if this is a mesh else camera or -1
  38105. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  38106. collider._initialize(position, velocity, closeDistance);
  38107. // Check all meshes
  38108. for (var index = 0; index < this._scene.meshes.length; index++) {
  38109. var mesh = this._scene.meshes[index];
  38110. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  38111. mesh._checkCollision(collider);
  38112. }
  38113. }
  38114. if (!collider.collisionFound) {
  38115. position.addToRef(velocity, finalPosition);
  38116. return;
  38117. }
  38118. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  38119. collider._getResponse(position, velocity);
  38120. }
  38121. if (velocity.length() <= closeDistance) {
  38122. finalPosition.copyFrom(position);
  38123. return;
  38124. }
  38125. collider.retry++;
  38126. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  38127. };
  38128. return CollisionCoordinatorLegacy;
  38129. }());
  38130. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  38131. })(BABYLON || (BABYLON = {}));
  38132. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  38133. var BABYLON;
  38134. (function (BABYLON) {
  38135. var Particle = (function () {
  38136. function Particle() {
  38137. this.position = BABYLON.Vector3.Zero();
  38138. this.direction = BABYLON.Vector3.Zero();
  38139. this.color = new BABYLON.Color4(0, 0, 0, 0);
  38140. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  38141. this.lifeTime = 1.0;
  38142. this.age = 0;
  38143. this.size = 0;
  38144. this.angle = 0;
  38145. this.angularSpeed = 0;
  38146. }
  38147. Particle.prototype.copyTo = function (other) {
  38148. other.position.copyFrom(this.position);
  38149. other.direction.copyFrom(this.direction);
  38150. other.color.copyFrom(this.color);
  38151. other.colorStep.copyFrom(this.colorStep);
  38152. other.lifeTime = this.lifeTime;
  38153. other.age = this.age;
  38154. other.size = this.size;
  38155. other.angle = this.angle;
  38156. other.angularSpeed = this.angularSpeed;
  38157. };
  38158. return Particle;
  38159. }());
  38160. BABYLON.Particle = Particle;
  38161. })(BABYLON || (BABYLON = {}));
  38162. //# sourceMappingURL=babylon.particle.js.map
  38163. var BABYLON;
  38164. (function (BABYLON) {
  38165. var randomNumber = function (min, max) {
  38166. if (min === max) {
  38167. return (min);
  38168. }
  38169. var random = Math.random();
  38170. return ((random * (max - min)) + min);
  38171. };
  38172. var ParticleSystem = (function () {
  38173. function ParticleSystem(name, capacity, scene, customEffect) {
  38174. var _this = this;
  38175. this.name = name;
  38176. // Members
  38177. this.animations = [];
  38178. this.renderingGroupId = 0;
  38179. this.emitter = null;
  38180. this.emitRate = 10;
  38181. this.manualEmitCount = -1;
  38182. this.updateSpeed = 0.01;
  38183. this.targetStopDuration = 0;
  38184. this.disposeOnStop = false;
  38185. this.minEmitPower = 1;
  38186. this.maxEmitPower = 1;
  38187. this.minLifeTime = 1;
  38188. this.maxLifeTime = 1;
  38189. this.minSize = 1;
  38190. this.maxSize = 1;
  38191. this.minAngularSpeed = 0;
  38192. this.maxAngularSpeed = 0;
  38193. this.layerMask = 0x0FFFFFFF;
  38194. this.customShader = null;
  38195. this.preventAutoStart = false;
  38196. /**
  38197. * An event triggered when the system is disposed.
  38198. * @type {BABYLON.Observable}
  38199. */
  38200. this.onDisposeObservable = new BABYLON.Observable();
  38201. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  38202. this.forceDepthWrite = false;
  38203. this.gravity = BABYLON.Vector3.Zero();
  38204. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  38205. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  38206. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  38207. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38208. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38209. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38210. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  38211. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38212. this.particles = new Array();
  38213. this._stockParticles = new Array();
  38214. this._newPartsExcess = 0;
  38215. this._vertexBuffers = {};
  38216. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  38217. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  38218. this._scaledDirection = BABYLON.Vector3.Zero();
  38219. this._scaledGravity = BABYLON.Vector3.Zero();
  38220. this._currentRenderId = -1;
  38221. this._started = false;
  38222. this._stopped = false;
  38223. this._actualFrame = 0;
  38224. this.id = name;
  38225. this._capacity = capacity;
  38226. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38227. this._customEffect = customEffect;
  38228. scene.particleSystems.push(this);
  38229. var indices = [];
  38230. var index = 0;
  38231. for (var count = 0; count < capacity; count++) {
  38232. indices.push(index);
  38233. indices.push(index + 1);
  38234. indices.push(index + 2);
  38235. indices.push(index);
  38236. indices.push(index + 2);
  38237. indices.push(index + 3);
  38238. index += 4;
  38239. }
  38240. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38241. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  38242. this._vertexData = new Float32Array(capacity * 11 * 4);
  38243. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  38244. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  38245. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  38246. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  38247. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  38248. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  38249. this._vertexBuffers["options"] = options;
  38250. // Default behaviors
  38251. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  38252. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  38253. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  38254. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  38255. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  38256. };
  38257. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  38258. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  38259. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  38260. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  38261. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  38262. };
  38263. this.updateFunction = function (particles) {
  38264. for (var index = 0; index < particles.length; index++) {
  38265. var particle = particles[index];
  38266. particle.age += _this._scaledUpdateSpeed;
  38267. if (particle.age >= particle.lifeTime) {
  38268. _this.recycleParticle(particle);
  38269. index--;
  38270. continue;
  38271. }
  38272. else {
  38273. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  38274. particle.color.addInPlace(_this._scaledColorStep);
  38275. if (particle.color.a < 0)
  38276. particle.color.a = 0;
  38277. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  38278. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  38279. particle.position.addInPlace(_this._scaledDirection);
  38280. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  38281. particle.direction.addInPlace(_this._scaledGravity);
  38282. }
  38283. }
  38284. };
  38285. }
  38286. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  38287. set: function (callback) {
  38288. if (this._onDisposeObserver) {
  38289. this.onDisposeObservable.remove(this._onDisposeObserver);
  38290. }
  38291. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38292. },
  38293. enumerable: true,
  38294. configurable: true
  38295. });
  38296. ParticleSystem.prototype.recycleParticle = function (particle) {
  38297. var lastParticle = this.particles.pop();
  38298. if (lastParticle !== particle) {
  38299. lastParticle.copyTo(particle);
  38300. this._stockParticles.push(lastParticle);
  38301. }
  38302. };
  38303. ParticleSystem.prototype.getCapacity = function () {
  38304. return this._capacity;
  38305. };
  38306. ParticleSystem.prototype.isAlive = function () {
  38307. return this._alive;
  38308. };
  38309. ParticleSystem.prototype.isStarted = function () {
  38310. return this._started;
  38311. };
  38312. ParticleSystem.prototype.start = function () {
  38313. this._started = true;
  38314. this._stopped = false;
  38315. this._actualFrame = 0;
  38316. };
  38317. ParticleSystem.prototype.stop = function () {
  38318. this._stopped = true;
  38319. };
  38320. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  38321. var offset = index * 11;
  38322. this._vertexData[offset] = particle.position.x;
  38323. this._vertexData[offset + 1] = particle.position.y;
  38324. this._vertexData[offset + 2] = particle.position.z;
  38325. this._vertexData[offset + 3] = particle.color.r;
  38326. this._vertexData[offset + 4] = particle.color.g;
  38327. this._vertexData[offset + 5] = particle.color.b;
  38328. this._vertexData[offset + 6] = particle.color.a;
  38329. this._vertexData[offset + 7] = particle.angle;
  38330. this._vertexData[offset + 8] = particle.size;
  38331. this._vertexData[offset + 9] = offsetX;
  38332. this._vertexData[offset + 10] = offsetY;
  38333. };
  38334. ParticleSystem.prototype._update = function (newParticles) {
  38335. // Update current
  38336. this._alive = this.particles.length > 0;
  38337. this.updateFunction(this.particles);
  38338. // Add new ones
  38339. var worldMatrix;
  38340. if (this.emitter.position) {
  38341. worldMatrix = this.emitter.getWorldMatrix();
  38342. }
  38343. else {
  38344. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  38345. }
  38346. var particle;
  38347. for (var index = 0; index < newParticles; index++) {
  38348. if (this.particles.length === this._capacity) {
  38349. break;
  38350. }
  38351. if (this._stockParticles.length !== 0) {
  38352. particle = this._stockParticles.pop();
  38353. particle.age = 0;
  38354. }
  38355. else {
  38356. particle = new BABYLON.Particle();
  38357. }
  38358. this.particles.push(particle);
  38359. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  38360. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  38361. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  38362. particle.size = randomNumber(this.minSize, this.maxSize);
  38363. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  38364. this.startPositionFunction(worldMatrix, particle.position, particle);
  38365. var step = randomNumber(0, 1.0);
  38366. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  38367. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  38368. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  38369. }
  38370. };
  38371. ParticleSystem.prototype._getEffect = function () {
  38372. if (this._customEffect) {
  38373. return this._customEffect;
  38374. }
  38375. ;
  38376. var defines = [];
  38377. if (this._scene.clipPlane) {
  38378. defines.push("#define CLIPPLANE");
  38379. }
  38380. // Effect
  38381. var join = defines.join("\n");
  38382. if (this._cachedDefines !== join) {
  38383. this._cachedDefines = join;
  38384. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  38385. }
  38386. return this._effect;
  38387. };
  38388. ParticleSystem.prototype.animate = function () {
  38389. if (!this._started)
  38390. return;
  38391. var effect = this._getEffect();
  38392. // Check
  38393. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  38394. return;
  38395. if (this._currentRenderId === this._scene.getRenderId()) {
  38396. return;
  38397. }
  38398. this._currentRenderId = this._scene.getRenderId();
  38399. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  38400. // determine the number of particles we need to create
  38401. var newParticles;
  38402. if (this.manualEmitCount > -1) {
  38403. newParticles = this.manualEmitCount;
  38404. this._newPartsExcess = 0;
  38405. this.manualEmitCount = 0;
  38406. }
  38407. else {
  38408. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  38409. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  38410. }
  38411. if (this._newPartsExcess > 1.0) {
  38412. newParticles += this._newPartsExcess >> 0;
  38413. this._newPartsExcess -= this._newPartsExcess >> 0;
  38414. }
  38415. this._alive = false;
  38416. if (!this._stopped) {
  38417. this._actualFrame += this._scaledUpdateSpeed;
  38418. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  38419. this.stop();
  38420. }
  38421. else {
  38422. newParticles = 0;
  38423. }
  38424. this._update(newParticles);
  38425. // Stopped?
  38426. if (this._stopped) {
  38427. if (!this._alive) {
  38428. this._started = false;
  38429. if (this.disposeOnStop) {
  38430. this._scene._toBeDisposed.push(this);
  38431. }
  38432. }
  38433. }
  38434. // Update VBO
  38435. var offset = 0;
  38436. for (var index = 0; index < this.particles.length; index++) {
  38437. var particle = this.particles[index];
  38438. this._appendParticleVertex(offset++, particle, 0, 0);
  38439. this._appendParticleVertex(offset++, particle, 1, 0);
  38440. this._appendParticleVertex(offset++, particle, 1, 1);
  38441. this._appendParticleVertex(offset++, particle, 0, 1);
  38442. }
  38443. this._vertexBuffer.update(this._vertexData);
  38444. };
  38445. ParticleSystem.prototype.render = function () {
  38446. var effect = this._getEffect();
  38447. // Check
  38448. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  38449. return 0;
  38450. var engine = this._scene.getEngine();
  38451. // Render
  38452. engine.enableEffect(effect);
  38453. engine.setState(false);
  38454. var viewMatrix = this._scene.getViewMatrix();
  38455. effect.setTexture("diffuseSampler", this.particleTexture);
  38456. effect.setMatrix("view", viewMatrix);
  38457. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  38458. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  38459. if (this._scene.clipPlane) {
  38460. var clipPlane = this._scene.clipPlane;
  38461. var invView = viewMatrix.clone();
  38462. invView.invert();
  38463. effect.setMatrix("invView", invView);
  38464. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38465. }
  38466. // VBOs
  38467. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  38468. // Draw order
  38469. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  38470. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38471. }
  38472. else {
  38473. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38474. }
  38475. if (this.forceDepthWrite) {
  38476. engine.setDepthWrite(true);
  38477. }
  38478. engine.draw(true, 0, this.particles.length * 6);
  38479. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38480. return this.particles.length;
  38481. };
  38482. ParticleSystem.prototype.dispose = function () {
  38483. if (this._vertexBuffer) {
  38484. this._vertexBuffer.dispose();
  38485. this._vertexBuffer = null;
  38486. }
  38487. if (this._indexBuffer) {
  38488. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38489. this._indexBuffer = null;
  38490. }
  38491. if (this.particleTexture) {
  38492. this.particleTexture.dispose();
  38493. this.particleTexture = null;
  38494. }
  38495. // Remove from scene
  38496. var index = this._scene.particleSystems.indexOf(this);
  38497. this._scene.particleSystems.splice(index, 1);
  38498. // Callback
  38499. this.onDisposeObservable.notifyObservers(this);
  38500. this.onDisposeObservable.clear();
  38501. };
  38502. // Clone
  38503. ParticleSystem.prototype.clone = function (name, newEmitter) {
  38504. var custom = null;
  38505. var program = null;
  38506. if (this.customShader != null) {
  38507. program = this.customShader;
  38508. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  38509. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  38510. }
  38511. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  38512. result.customShader = program;
  38513. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  38514. if (newEmitter === undefined) {
  38515. newEmitter = this.emitter;
  38516. }
  38517. result.emitter = newEmitter;
  38518. if (this.particleTexture) {
  38519. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  38520. }
  38521. if (!this.preventAutoStart) {
  38522. result.start();
  38523. }
  38524. return result;
  38525. };
  38526. ParticleSystem.prototype.serialize = function () {
  38527. var serializationObject = {};
  38528. serializationObject.name = this.name;
  38529. serializationObject.id = this.id;
  38530. // Emitter
  38531. if (this.emitter.position) {
  38532. serializationObject.emitterId = this.emitter.id;
  38533. }
  38534. else {
  38535. serializationObject.emitter = this.emitter.asArray();
  38536. }
  38537. serializationObject.capacity = this.getCapacity();
  38538. if (this.particleTexture) {
  38539. serializationObject.textureName = this.particleTexture.name;
  38540. }
  38541. // Animations
  38542. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  38543. // Particle system
  38544. serializationObject.minAngularSpeed = this.minAngularSpeed;
  38545. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  38546. serializationObject.minSize = this.minSize;
  38547. serializationObject.maxSize = this.maxSize;
  38548. serializationObject.minEmitPower = this.minEmitPower;
  38549. serializationObject.maxEmitPower = this.maxEmitPower;
  38550. serializationObject.minLifeTime = this.minLifeTime;
  38551. serializationObject.maxLifeTime = this.maxLifeTime;
  38552. serializationObject.emitRate = this.emitRate;
  38553. serializationObject.minEmitBox = this.minEmitBox.asArray();
  38554. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  38555. serializationObject.gravity = this.gravity.asArray();
  38556. serializationObject.direction1 = this.direction1.asArray();
  38557. serializationObject.direction2 = this.direction2.asArray();
  38558. serializationObject.color1 = this.color1.asArray();
  38559. serializationObject.color2 = this.color2.asArray();
  38560. serializationObject.colorDead = this.colorDead.asArray();
  38561. serializationObject.updateSpeed = this.updateSpeed;
  38562. serializationObject.targetStopDuration = this.targetStopDuration;
  38563. serializationObject.textureMask = this.textureMask.asArray();
  38564. serializationObject.blendMode = this.blendMode;
  38565. serializationObject.customShader = this.customShader;
  38566. serializationObject.preventAutoStart = this.preventAutoStart;
  38567. return serializationObject;
  38568. };
  38569. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  38570. var name = parsedParticleSystem.name;
  38571. var custom = null;
  38572. var program = null;
  38573. if (parsedParticleSystem.customShader) {
  38574. program = parsedParticleSystem.customShader;
  38575. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  38576. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  38577. }
  38578. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  38579. particleSystem.customShader = program;
  38580. if (parsedParticleSystem.id) {
  38581. particleSystem.id = parsedParticleSystem.id;
  38582. }
  38583. // Auto start
  38584. if (parsedParticleSystem.preventAutoStart) {
  38585. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  38586. }
  38587. // Texture
  38588. if (parsedParticleSystem.textureName) {
  38589. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  38590. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  38591. }
  38592. // Emitter
  38593. if (parsedParticleSystem.emitterId) {
  38594. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  38595. }
  38596. else {
  38597. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  38598. }
  38599. // Animations
  38600. if (parsedParticleSystem.animations) {
  38601. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  38602. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  38603. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  38604. }
  38605. }
  38606. if (parsedParticleSystem.autoAnimate) {
  38607. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  38608. }
  38609. // Particle system
  38610. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  38611. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  38612. particleSystem.minSize = parsedParticleSystem.minSize;
  38613. particleSystem.maxSize = parsedParticleSystem.maxSize;
  38614. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  38615. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  38616. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  38617. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  38618. particleSystem.emitRate = parsedParticleSystem.emitRate;
  38619. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  38620. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  38621. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  38622. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  38623. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  38624. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  38625. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  38626. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  38627. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  38628. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  38629. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  38630. particleSystem.blendMode = parsedParticleSystem.blendMode;
  38631. if (!particleSystem.preventAutoStart) {
  38632. particleSystem.start();
  38633. }
  38634. return particleSystem;
  38635. };
  38636. return ParticleSystem;
  38637. }());
  38638. // Statics
  38639. ParticleSystem.BLENDMODE_ONEONE = 0;
  38640. ParticleSystem.BLENDMODE_STANDARD = 1;
  38641. BABYLON.ParticleSystem = ParticleSystem;
  38642. })(BABYLON || (BABYLON = {}));
  38643. //# sourceMappingURL=babylon.particleSystem.js.map
  38644. var BABYLON;
  38645. (function (BABYLON) {
  38646. var SolidParticle = (function () {
  38647. /**
  38648. * Creates a Solid Particle object.
  38649. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  38650. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  38651. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  38652. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  38653. * `shapeId` (integer) is the model shape identifier in the SPS.
  38654. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  38655. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  38656. */
  38657. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  38658. this.idx = 0; // particle global index
  38659. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  38660. this.position = BABYLON.Vector3.Zero(); // position
  38661. this.rotation = BABYLON.Vector3.Zero(); // rotation
  38662. this.scaling = BABYLON.Vector3.One(); // scaling
  38663. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  38664. this.velocity = BABYLON.Vector3.Zero(); // velocity
  38665. this.alive = true; // alive
  38666. this.isVisible = true; // visibility
  38667. this._pos = 0; // index of this particle in the global "positions" array
  38668. this.shapeId = 0; // model shape id
  38669. this.idxInShape = 0; // index of the particle in its shape id
  38670. this.idx = particleIndex;
  38671. this._pos = positionIndex;
  38672. this._model = model;
  38673. this.shapeId = shapeId;
  38674. this.idxInShape = idxInShape;
  38675. this._sps = sps;
  38676. if (modelBoundingInfo) {
  38677. this._modelBoundingInfo = modelBoundingInfo;
  38678. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  38679. }
  38680. }
  38681. Object.defineProperty(SolidParticle.prototype, "scale", {
  38682. /**
  38683. * legacy support, changed scale to scaling
  38684. */
  38685. get: function () {
  38686. return this.scaling;
  38687. },
  38688. set: function (scale) {
  38689. this.scaling = scale;
  38690. },
  38691. enumerable: true,
  38692. configurable: true
  38693. });
  38694. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  38695. /**
  38696. * legacy support, changed quaternion to rotationQuaternion
  38697. */
  38698. get: function () {
  38699. return this.rotationQuaternion;
  38700. },
  38701. set: function (q) {
  38702. this.rotationQuaternion = q;
  38703. },
  38704. enumerable: true,
  38705. configurable: true
  38706. });
  38707. /**
  38708. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  38709. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  38710. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  38711. */
  38712. SolidParticle.prototype.intersectsMesh = function (target) {
  38713. if (!this._boundingInfo || !target._boundingInfo) {
  38714. return false;
  38715. }
  38716. if (this._sps._bSphereOnly) {
  38717. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  38718. }
  38719. return this._boundingInfo.intersects(target._boundingInfo, false);
  38720. };
  38721. return SolidParticle;
  38722. }());
  38723. BABYLON.SolidParticle = SolidParticle;
  38724. var ModelShape = (function () {
  38725. /**
  38726. * 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.
  38727. * SPS internal tool, don't use it manually.
  38728. */
  38729. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  38730. this.shapeID = id;
  38731. this._shape = shape;
  38732. this._shapeUV = shapeUV;
  38733. this._positionFunction = posFunction;
  38734. this._vertexFunction = vtxFunction;
  38735. }
  38736. return ModelShape;
  38737. }());
  38738. BABYLON.ModelShape = ModelShape;
  38739. })(BABYLON || (BABYLON = {}));
  38740. //# sourceMappingURL=babylon.solidParticle.js.map
  38741. var BABYLON;
  38742. (function (BABYLON) {
  38743. /**
  38744. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  38745. */
  38746. var SolidParticleSystem = (function () {
  38747. /**
  38748. * Creates a SPS (Solid Particle System) object.
  38749. * `name` (String) is the SPS name, this will be the underlying mesh name.
  38750. * `scene` (Scene) is the scene in which the SPS is added.
  38751. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  38752. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  38753. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  38754. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  38755. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  38756. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  38757. */
  38758. function SolidParticleSystem(name, scene, options) {
  38759. // public members
  38760. /**
  38761. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  38762. * Example : var p = SPS.particles[i];
  38763. */
  38764. this.particles = new Array();
  38765. /**
  38766. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  38767. */
  38768. this.nbParticles = 0;
  38769. /**
  38770. * If the particles must ever face the camera (default false). Useful for planar particles.
  38771. */
  38772. this.billboard = false;
  38773. /**
  38774. * Recompute normals when adding a shape
  38775. */
  38776. this.recomputeNormals = true;
  38777. /**
  38778. * This a counter ofr your own usage. It's not set by any SPS functions.
  38779. */
  38780. this.counter = 0;
  38781. /**
  38782. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  38783. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  38784. */
  38785. this.vars = {};
  38786. this._positions = new Array();
  38787. this._indices = new Array();
  38788. this._normals = new Array();
  38789. this._colors = new Array();
  38790. this._uvs = new Array();
  38791. this._index = 0; // indices index
  38792. this._updatable = true;
  38793. this._pickable = false;
  38794. this._isVisibilityBoxLocked = false;
  38795. this._alwaysVisible = false;
  38796. this._shapeCounter = 0;
  38797. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  38798. this._color = new BABYLON.Color4(0, 0, 0, 0);
  38799. this._computeParticleColor = true;
  38800. this._computeParticleTexture = true;
  38801. this._computeParticleRotation = true;
  38802. this._computeParticleVertex = false;
  38803. this._computeBoundingBox = false;
  38804. this._cam_axisZ = BABYLON.Vector3.Zero();
  38805. this._cam_axisY = BABYLON.Vector3.Zero();
  38806. this._cam_axisX = BABYLON.Vector3.Zero();
  38807. this._axisX = BABYLON.Axis.X;
  38808. this._axisY = BABYLON.Axis.Y;
  38809. this._axisZ = BABYLON.Axis.Z;
  38810. this._camDir = BABYLON.Vector3.Zero();
  38811. this._rotMatrix = new BABYLON.Matrix();
  38812. this._invertMatrix = new BABYLON.Matrix();
  38813. this._rotated = BABYLON.Vector3.Zero();
  38814. this._quaternion = new BABYLON.Quaternion();
  38815. this._vertex = BABYLON.Vector3.Zero();
  38816. this._normal = BABYLON.Vector3.Zero();
  38817. this._yaw = 0.0;
  38818. this._pitch = 0.0;
  38819. this._roll = 0.0;
  38820. this._halfroll = 0.0;
  38821. this._halfpitch = 0.0;
  38822. this._halfyaw = 0.0;
  38823. this._sinRoll = 0.0;
  38824. this._cosRoll = 0.0;
  38825. this._sinPitch = 0.0;
  38826. this._cosPitch = 0.0;
  38827. this._sinYaw = 0.0;
  38828. this._cosYaw = 0.0;
  38829. this._w = 0.0;
  38830. this._mustUnrotateFixedNormals = false;
  38831. this._minimum = BABYLON.Tmp.Vector3[0];
  38832. this._maximum = BABYLON.Tmp.Vector3[1];
  38833. this._scale = BABYLON.Tmp.Vector3[2];
  38834. this._translation = BABYLON.Tmp.Vector3[3];
  38835. this._minBbox = BABYLON.Tmp.Vector3[4];
  38836. this._maxBbox = BABYLON.Tmp.Vector3[5];
  38837. this._particlesIntersect = false;
  38838. this._bSphereOnly = false;
  38839. this._bSphereRadiusFactor = 1.0;
  38840. this.name = name;
  38841. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38842. this._camera = scene.activeCamera;
  38843. this._pickable = options ? options.isPickable : false;
  38844. this._particlesIntersect = options ? options.particleIntersection : false;
  38845. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  38846. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  38847. if (options && options.updatable) {
  38848. this._updatable = options.updatable;
  38849. }
  38850. else {
  38851. this._updatable = true;
  38852. }
  38853. if (this._pickable) {
  38854. this.pickedParticles = [];
  38855. }
  38856. }
  38857. /**
  38858. * Builds the SPS underlying mesh. Returns a standard Mesh.
  38859. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  38860. */
  38861. SolidParticleSystem.prototype.buildMesh = function () {
  38862. if (this.nbParticles === 0) {
  38863. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  38864. this.addShape(triangle, 1);
  38865. triangle.dispose();
  38866. }
  38867. this._positions32 = new Float32Array(this._positions);
  38868. this._uvs32 = new Float32Array(this._uvs);
  38869. this._colors32 = new Float32Array(this._colors);
  38870. if (this.recomputeNormals) {
  38871. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  38872. }
  38873. this._normals32 = new Float32Array(this._normals);
  38874. this._fixedNormal32 = new Float32Array(this._normals);
  38875. if (this._mustUnrotateFixedNormals) {
  38876. this._unrotateFixedNormals();
  38877. }
  38878. var vertexData = new BABYLON.VertexData();
  38879. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  38880. vertexData.indices = this._indices;
  38881. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  38882. if (this._uvs32) {
  38883. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  38884. ;
  38885. }
  38886. if (this._colors32) {
  38887. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  38888. }
  38889. var mesh = new BABYLON.Mesh(this.name, this._scene);
  38890. vertexData.applyToMesh(mesh, this._updatable);
  38891. this.mesh = mesh;
  38892. this.mesh.isPickable = this._pickable;
  38893. // free memory
  38894. this._positions = null;
  38895. this._normals = null;
  38896. this._uvs = null;
  38897. this._colors = null;
  38898. if (!this._updatable) {
  38899. this.particles.length = 0;
  38900. }
  38901. return mesh;
  38902. };
  38903. /**
  38904. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  38905. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  38906. * Thus the particles generated from `digest()` have their property `position` set yet.
  38907. * `mesh` ( Mesh ) is the mesh to be digested
  38908. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  38909. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  38910. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  38911. */
  38912. SolidParticleSystem.prototype.digest = function (mesh, options) {
  38913. var size = (options && options.facetNb) || 1;
  38914. var number = (options && options.number);
  38915. var delta = (options && options.delta) || 0;
  38916. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38917. var meshInd = mesh.getIndices();
  38918. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38919. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38920. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38921. var f = 0; // facet counter
  38922. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  38923. // compute size from number
  38924. if (number) {
  38925. number = (number > totalFacets) ? totalFacets : number;
  38926. size = Math.round(totalFacets / number);
  38927. delta = 0;
  38928. }
  38929. else {
  38930. size = (size > totalFacets) ? totalFacets : size;
  38931. }
  38932. var facetPos = []; // submesh positions
  38933. var facetInd = []; // submesh indices
  38934. var facetUV = []; // submesh UV
  38935. var facetCol = []; // submesh colors
  38936. var barycenter = BABYLON.Tmp.Vector3[0];
  38937. var rand;
  38938. var sizeO = size;
  38939. while (f < totalFacets) {
  38940. size = sizeO + Math.floor((1 + delta) * Math.random());
  38941. if (f > totalFacets - size) {
  38942. size = totalFacets - f;
  38943. }
  38944. // reset temp arrays
  38945. facetPos.length = 0;
  38946. facetInd.length = 0;
  38947. facetUV.length = 0;
  38948. facetCol.length = 0;
  38949. // iterate over "size" facets
  38950. var fi = 0;
  38951. for (var j = f * 3; j < (f + size) * 3; j++) {
  38952. facetInd.push(fi);
  38953. var i = meshInd[j];
  38954. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  38955. if (meshUV) {
  38956. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  38957. }
  38958. if (meshCol) {
  38959. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  38960. }
  38961. fi++;
  38962. }
  38963. // create a model shape for each single particle
  38964. var idx = this.nbParticles;
  38965. var shape = this._posToShape(facetPos);
  38966. var shapeUV = this._uvsToShapeUV(facetUV);
  38967. // compute the barycenter of the shape
  38968. var v;
  38969. for (v = 0; v < shape.length; v++) {
  38970. barycenter.addInPlace(shape[v]);
  38971. }
  38972. barycenter.scaleInPlace(1 / shape.length);
  38973. // shift the shape from its barycenter to the origin
  38974. for (v = 0; v < shape.length; v++) {
  38975. shape[v].subtractInPlace(barycenter);
  38976. }
  38977. var bInfo;
  38978. if (this._particlesIntersect) {
  38979. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  38980. }
  38981. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  38982. // add the particle in the SPS
  38983. var currentPos = this._positions.length;
  38984. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  38985. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  38986. // initialize the particle position
  38987. this.particles[this.nbParticles].position.addInPlace(barycenter);
  38988. this._index += shape.length;
  38989. idx++;
  38990. this.nbParticles++;
  38991. this._shapeCounter++;
  38992. f += size;
  38993. }
  38994. return this;
  38995. };
  38996. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  38997. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  38998. var index = 0;
  38999. var idx = 0;
  39000. for (var p = 0; p < this.particles.length; p++) {
  39001. this._particle = this.particles[p];
  39002. this._shape = this._particle._model._shape;
  39003. if (this._particle.rotationQuaternion) {
  39004. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  39005. }
  39006. else {
  39007. this._yaw = this._particle.rotation.y;
  39008. this._pitch = this._particle.rotation.x;
  39009. this._roll = this._particle.rotation.z;
  39010. this._quaternionRotationYPR();
  39011. }
  39012. this._quaternionToRotationMatrix();
  39013. this._rotMatrix.invertToRef(this._invertMatrix);
  39014. for (var pt = 0; pt < this._shape.length; pt++) {
  39015. idx = index + pt * 3;
  39016. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  39017. this._fixedNormal32[idx] = this._normal.x;
  39018. this._fixedNormal32[idx + 1] = this._normal.y;
  39019. this._fixedNormal32[idx + 2] = this._normal.z;
  39020. }
  39021. index = idx + 3;
  39022. }
  39023. };
  39024. //reset copy
  39025. SolidParticleSystem.prototype._resetCopy = function () {
  39026. this._copy.position.x = 0;
  39027. this._copy.position.y = 0;
  39028. this._copy.position.z = 0;
  39029. this._copy.rotation.x = 0;
  39030. this._copy.rotation.y = 0;
  39031. this._copy.rotation.z = 0;
  39032. this._copy.rotationQuaternion = null;
  39033. this._copy.scaling.x = 1;
  39034. this._copy.scaling.y = 1;
  39035. this._copy.scaling.z = 1;
  39036. this._copy.uvs.x = 0;
  39037. this._copy.uvs.y = 0;
  39038. this._copy.uvs.z = 1;
  39039. this._copy.uvs.w = 1;
  39040. this._copy.color = null;
  39041. };
  39042. // _meshBuilder : inserts the shape model in the global SPS mesh
  39043. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  39044. var i;
  39045. var u = 0;
  39046. var c = 0;
  39047. var n = 0;
  39048. this._resetCopy();
  39049. if (options && options.positionFunction) {
  39050. options.positionFunction(this._copy, idx, idxInShape);
  39051. this._mustUnrotateFixedNormals = true;
  39052. }
  39053. if (this._copy.rotationQuaternion) {
  39054. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  39055. }
  39056. else {
  39057. this._yaw = this._copy.rotation.y;
  39058. this._pitch = this._copy.rotation.x;
  39059. this._roll = this._copy.rotation.z;
  39060. this._quaternionRotationYPR();
  39061. }
  39062. this._quaternionToRotationMatrix();
  39063. for (i = 0; i < shape.length; i++) {
  39064. this._vertex.x = shape[i].x;
  39065. this._vertex.y = shape[i].y;
  39066. this._vertex.z = shape[i].z;
  39067. if (options && options.vertexFunction) {
  39068. options.vertexFunction(this._copy, this._vertex, i);
  39069. }
  39070. this._vertex.x *= this._copy.scaling.x;
  39071. this._vertex.y *= this._copy.scaling.y;
  39072. this._vertex.z *= this._copy.scaling.z;
  39073. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  39074. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  39075. if (meshUV) {
  39076. 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);
  39077. u += 2;
  39078. }
  39079. if (this._copy.color) {
  39080. this._color = this._copy.color;
  39081. }
  39082. else if (meshCol && meshCol[c] !== undefined) {
  39083. this._color.r = meshCol[c];
  39084. this._color.g = meshCol[c + 1];
  39085. this._color.b = meshCol[c + 2];
  39086. this._color.a = meshCol[c + 3];
  39087. }
  39088. else {
  39089. this._color.r = 1;
  39090. this._color.g = 1;
  39091. this._color.b = 1;
  39092. this._color.a = 1;
  39093. }
  39094. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  39095. c += 4;
  39096. if (!this.recomputeNormals && meshNor) {
  39097. this._normal.x = meshNor[n];
  39098. this._normal.y = meshNor[n + 1];
  39099. this._normal.z = meshNor[n + 2];
  39100. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  39101. normals.push(this._normal.x, this._normal.y, this._normal.z);
  39102. n += 3;
  39103. }
  39104. }
  39105. for (i = 0; i < meshInd.length; i++) {
  39106. indices.push(p + meshInd[i]);
  39107. }
  39108. if (this._pickable) {
  39109. var nbfaces = meshInd.length / 3;
  39110. for (i = 0; i < nbfaces; i++) {
  39111. this.pickedParticles.push({ idx: idx, faceId: i });
  39112. }
  39113. }
  39114. return this._copy;
  39115. };
  39116. // returns a shape array from positions array
  39117. SolidParticleSystem.prototype._posToShape = function (positions) {
  39118. var shape = [];
  39119. for (var i = 0; i < positions.length; i += 3) {
  39120. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  39121. }
  39122. return shape;
  39123. };
  39124. // returns a shapeUV array from a Vector4 uvs
  39125. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  39126. var shapeUV = [];
  39127. if (uvs) {
  39128. for (var i = 0; i < uvs.length; i++)
  39129. shapeUV.push(uvs[i]);
  39130. }
  39131. return shapeUV;
  39132. };
  39133. // adds a new particle object in the particles array
  39134. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  39135. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  39136. this.particles.push(sp);
  39137. return sp;
  39138. };
  39139. /**
  39140. * Adds some particles to the SPS from the model shape. Returns the shape id.
  39141. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  39142. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  39143. * `nb` (positive integer) the number of particles to be created from this model
  39144. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  39145. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  39146. */
  39147. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  39148. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39149. var meshInd = mesh.getIndices();
  39150. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39151. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39152. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39153. var bbInfo;
  39154. if (this._particlesIntersect) {
  39155. bbInfo = mesh.getBoundingInfo();
  39156. }
  39157. var shape = this._posToShape(meshPos);
  39158. var shapeUV = this._uvsToShapeUV(meshUV);
  39159. var posfunc = options ? options.positionFunction : null;
  39160. var vtxfunc = options ? options.vertexFunction : null;
  39161. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  39162. // particles
  39163. var sp;
  39164. var currentCopy;
  39165. var idx = this.nbParticles;
  39166. for (var i = 0; i < nb; i++) {
  39167. var currentPos = this._positions.length;
  39168. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  39169. if (this._updatable) {
  39170. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  39171. sp.position.copyFrom(currentCopy.position);
  39172. sp.rotation.copyFrom(currentCopy.rotation);
  39173. if (currentCopy.rotationQuaternion) {
  39174. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  39175. }
  39176. if (currentCopy.color) {
  39177. sp.color.copyFrom(currentCopy.color);
  39178. }
  39179. sp.scaling.copyFrom(currentCopy.scaling);
  39180. sp.uvs.copyFrom(currentCopy.uvs);
  39181. }
  39182. this._index += shape.length;
  39183. idx++;
  39184. }
  39185. this.nbParticles += nb;
  39186. this._shapeCounter++;
  39187. return this._shapeCounter - 1;
  39188. };
  39189. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  39190. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  39191. this._resetCopy();
  39192. if (particle._model._positionFunction) {
  39193. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  39194. }
  39195. if (this._copy.rotationQuaternion) {
  39196. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  39197. }
  39198. else {
  39199. this._yaw = this._copy.rotation.y;
  39200. this._pitch = this._copy.rotation.x;
  39201. this._roll = this._copy.rotation.z;
  39202. this._quaternionRotationYPR();
  39203. }
  39204. this._quaternionToRotationMatrix();
  39205. this._shape = particle._model._shape;
  39206. for (var pt = 0; pt < this._shape.length; pt++) {
  39207. this._vertex.x = this._shape[pt].x;
  39208. this._vertex.y = this._shape[pt].y;
  39209. this._vertex.z = this._shape[pt].z;
  39210. if (particle._model._vertexFunction) {
  39211. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  39212. }
  39213. this._vertex.x *= this._copy.scaling.x;
  39214. this._vertex.y *= this._copy.scaling.y;
  39215. this._vertex.z *= this._copy.scaling.z;
  39216. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  39217. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  39218. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  39219. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  39220. }
  39221. particle.position.x = 0.0;
  39222. particle.position.y = 0.0;
  39223. particle.position.z = 0.0;
  39224. particle.rotation.x = 0.0;
  39225. particle.rotation.y = 0.0;
  39226. particle.rotation.z = 0.0;
  39227. particle.rotationQuaternion = null;
  39228. particle.scaling.x = 1.0;
  39229. particle.scaling.y = 1.0;
  39230. particle.scaling.z = 1.0;
  39231. };
  39232. /**
  39233. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  39234. * Returns the SPS.
  39235. */
  39236. SolidParticleSystem.prototype.rebuildMesh = function () {
  39237. for (var p = 0; p < this.particles.length; p++) {
  39238. this._rebuildParticle(this.particles[p]);
  39239. }
  39240. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  39241. return this;
  39242. };
  39243. /**
  39244. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  39245. * This method calls `updateParticle()` for each particle of the SPS.
  39246. * For an animated SPS, it is usually called within the render loop.
  39247. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  39248. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  39249. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  39250. * Returns the SPS.
  39251. */
  39252. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  39253. if (start === void 0) { start = 0; }
  39254. if (end === void 0) { end = this.nbParticles - 1; }
  39255. if (update === void 0) { update = true; }
  39256. if (!this._updatable) {
  39257. return;
  39258. }
  39259. // custom beforeUpdate
  39260. this.beforeUpdateParticles(start, end, update);
  39261. this._cam_axisX.x = 1.0;
  39262. this._cam_axisX.y = 0.0;
  39263. this._cam_axisX.z = 0.0;
  39264. this._cam_axisY.x = 0.0;
  39265. this._cam_axisY.y = 1.0;
  39266. this._cam_axisY.z = 0.0;
  39267. this._cam_axisZ.x = 0.0;
  39268. this._cam_axisZ.y = 0.0;
  39269. this._cam_axisZ.z = 1.0;
  39270. // if the particles will always face the camera
  39271. if (this.billboard) {
  39272. this.mesh.computeWorldMatrix(true);
  39273. // compute the camera position and un-rotate it by the current mesh rotation
  39274. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  39275. this._quaternionToRotationMatrix();
  39276. this._rotMatrix.invertToRef(this._invertMatrix);
  39277. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  39278. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  39279. this._cam_axisZ.normalize();
  39280. // same for camera up vector extracted from the cam view matrix
  39281. var view = this._camera.getViewMatrix(true);
  39282. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  39283. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  39284. this._cam_axisY.normalize();
  39285. this._cam_axisX.normalize();
  39286. }
  39287. }
  39288. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  39289. var idx = 0; // current position index in the global array positions32
  39290. var index = 0; // position start index in the global array positions32 of the current particle
  39291. var colidx = 0; // current color index in the global array colors32
  39292. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  39293. var uvidx = 0; // current uv index in the global array uvs32
  39294. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  39295. var pt = 0; // current index in the particle model shape
  39296. if (this.mesh.isFacetDataEnabled) {
  39297. this._computeBoundingBox = true;
  39298. }
  39299. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  39300. if (this._computeBoundingBox) {
  39301. if (start == 0 && end == this.nbParticles - 1) {
  39302. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  39303. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  39304. }
  39305. else {
  39306. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  39307. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  39308. }
  39309. }
  39310. // particle loop
  39311. index = this.particles[start]._pos;
  39312. var vpos = (index / 3) | 0;
  39313. colorIndex = vpos * 4;
  39314. uvIndex = vpos * 2;
  39315. for (var p = start; p <= end; p++) {
  39316. this._particle = this.particles[p];
  39317. this._shape = this._particle._model._shape;
  39318. this._shapeUV = this._particle._model._shapeUV;
  39319. // call to custom user function to update the particle properties
  39320. this.updateParticle(this._particle);
  39321. if (this._particle.isVisible) {
  39322. // particle rotation matrix
  39323. if (this.billboard) {
  39324. this._particle.rotation.x = 0.0;
  39325. this._particle.rotation.y = 0.0;
  39326. }
  39327. if (this._computeParticleRotation || this.billboard) {
  39328. if (this._particle.rotationQuaternion) {
  39329. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  39330. }
  39331. else {
  39332. this._yaw = this._particle.rotation.y;
  39333. this._pitch = this._particle.rotation.x;
  39334. this._roll = this._particle.rotation.z;
  39335. this._quaternionRotationYPR();
  39336. }
  39337. this._quaternionToRotationMatrix();
  39338. }
  39339. // particle vertex loop
  39340. for (pt = 0; pt < this._shape.length; pt++) {
  39341. idx = index + pt * 3;
  39342. colidx = colorIndex + pt * 4;
  39343. uvidx = uvIndex + pt * 2;
  39344. this._vertex.x = this._shape[pt].x;
  39345. this._vertex.y = this._shape[pt].y;
  39346. this._vertex.z = this._shape[pt].z;
  39347. if (this._computeParticleVertex) {
  39348. this.updateParticleVertex(this._particle, this._vertex, pt);
  39349. }
  39350. // positions
  39351. this._vertex.x *= this._particle.scaling.x;
  39352. this._vertex.y *= this._particle.scaling.y;
  39353. this._vertex.z *= this._particle.scaling.z;
  39354. 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];
  39355. 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;
  39356. 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;
  39357. 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;
  39358. 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;
  39359. 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;
  39360. 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;
  39361. if (this._computeBoundingBox) {
  39362. if (this._positions32[idx] < this._minimum.x) {
  39363. this._minimum.x = this._positions32[idx];
  39364. }
  39365. if (this._positions32[idx] > this._maximum.x) {
  39366. this._maximum.x = this._positions32[idx];
  39367. }
  39368. if (this._positions32[idx + 1] < this._minimum.y) {
  39369. this._minimum.y = this._positions32[idx + 1];
  39370. }
  39371. if (this._positions32[idx + 1] > this._maximum.y) {
  39372. this._maximum.y = this._positions32[idx + 1];
  39373. }
  39374. if (this._positions32[idx + 2] < this._minimum.z) {
  39375. this._minimum.z = this._positions32[idx + 2];
  39376. }
  39377. if (this._positions32[idx + 2] > this._maximum.z) {
  39378. this._maximum.z = this._positions32[idx + 2];
  39379. }
  39380. }
  39381. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  39382. if (!this._computeParticleVertex) {
  39383. this._normal.x = this._fixedNormal32[idx];
  39384. this._normal.y = this._fixedNormal32[idx + 1];
  39385. this._normal.z = this._fixedNormal32[idx + 2];
  39386. 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]);
  39387. 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]);
  39388. 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]);
  39389. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  39390. 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;
  39391. 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;
  39392. }
  39393. if (this._computeParticleColor) {
  39394. this._colors32[colidx] = this._particle.color.r;
  39395. this._colors32[colidx + 1] = this._particle.color.g;
  39396. this._colors32[colidx + 2] = this._particle.color.b;
  39397. this._colors32[colidx + 3] = this._particle.color.a;
  39398. }
  39399. if (this._computeParticleTexture) {
  39400. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  39401. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  39402. }
  39403. }
  39404. }
  39405. else {
  39406. for (pt = 0; pt < this._shape.length; pt++) {
  39407. idx = index + pt * 3;
  39408. colidx = colorIndex + pt * 4;
  39409. uvidx = uvIndex + pt * 2;
  39410. this._positions32[idx] = this._camera.globalPosition.x;
  39411. this._positions32[idx + 1] = this._camera.globalPosition.y;
  39412. this._positions32[idx + 2] = this._camera.globalPosition.z;
  39413. this._normals32[idx] = 0.0;
  39414. this._normals32[idx + 1] = 0.0;
  39415. this._normals32[idx + 2] = 0.0;
  39416. if (this._computeParticleColor) {
  39417. this._colors32[colidx] = this._particle.color.r;
  39418. this._colors32[colidx + 1] = this._particle.color.g;
  39419. this._colors32[colidx + 2] = this._particle.color.b;
  39420. this._colors32[colidx + 3] = this._particle.color.a;
  39421. }
  39422. if (this._computeParticleTexture) {
  39423. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  39424. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  39425. }
  39426. }
  39427. }
  39428. // if the particle intersections must be computed : update the bbInfo
  39429. if (this._particlesIntersect) {
  39430. var bInfo = this._particle._boundingInfo;
  39431. var bBox = bInfo.boundingBox;
  39432. var bSphere = bInfo.boundingSphere;
  39433. if (!this._bSphereOnly) {
  39434. // place, scale and rotate the particle bbox within the SPS local system, then update it
  39435. for (var b = 0; b < bBox.vectors.length; b++) {
  39436. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  39437. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  39438. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  39439. 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];
  39440. 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;
  39441. 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;
  39442. 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;
  39443. 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;
  39444. 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;
  39445. 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;
  39446. }
  39447. bBox._update(this.mesh._worldMatrix);
  39448. }
  39449. // place and scale the particle bouding sphere in the SPS local system, then update it
  39450. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  39451. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  39452. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  39453. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  39454. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  39455. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  39456. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  39457. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  39458. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  39459. 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));
  39460. bSphere._update(this.mesh._worldMatrix);
  39461. }
  39462. // increment indexes for the next particle
  39463. index = idx + 3;
  39464. colorIndex = colidx + 4;
  39465. uvIndex = uvidx + 2;
  39466. }
  39467. // if the VBO must be updated
  39468. if (update) {
  39469. if (this._computeParticleColor) {
  39470. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  39471. }
  39472. if (this._computeParticleTexture) {
  39473. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  39474. }
  39475. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  39476. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  39477. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  39478. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  39479. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  39480. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  39481. for (var i = 0; i < this._normals32.length; i++) {
  39482. this._fixedNormal32[i] = this._normals32[i];
  39483. }
  39484. }
  39485. if (!this.mesh.areNormalsFrozen) {
  39486. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  39487. }
  39488. }
  39489. }
  39490. if (this._computeBoundingBox) {
  39491. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  39492. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  39493. }
  39494. this.afterUpdateParticles(start, end, update);
  39495. return this;
  39496. };
  39497. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  39498. this._halfroll = this._roll * 0.5;
  39499. this._halfpitch = this._pitch * 0.5;
  39500. this._halfyaw = this._yaw * 0.5;
  39501. this._sinRoll = Math.sin(this._halfroll);
  39502. this._cosRoll = Math.cos(this._halfroll);
  39503. this._sinPitch = Math.sin(this._halfpitch);
  39504. this._cosPitch = Math.cos(this._halfpitch);
  39505. this._sinYaw = Math.sin(this._halfyaw);
  39506. this._cosYaw = Math.cos(this._halfyaw);
  39507. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  39508. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  39509. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  39510. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  39511. };
  39512. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  39513. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  39514. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  39515. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  39516. this._rotMatrix.m[3] = 0;
  39517. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  39518. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  39519. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  39520. this._rotMatrix.m[7] = 0;
  39521. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  39522. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  39523. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  39524. this._rotMatrix.m[11] = 0;
  39525. this._rotMatrix.m[12] = 0;
  39526. this._rotMatrix.m[13] = 0;
  39527. this._rotMatrix.m[14] = 0;
  39528. this._rotMatrix.m[15] = 1.0;
  39529. };
  39530. /**
  39531. * Disposes the SPS.
  39532. * Returns nothing.
  39533. */
  39534. SolidParticleSystem.prototype.dispose = function () {
  39535. this.mesh.dispose();
  39536. this.vars = null;
  39537. // drop references to internal big arrays for the GC
  39538. this._positions = null;
  39539. this._indices = null;
  39540. this._normals = null;
  39541. this._uvs = null;
  39542. this._colors = null;
  39543. this._positions32 = null;
  39544. this._normals32 = null;
  39545. this._fixedNormal32 = null;
  39546. this._uvs32 = null;
  39547. this._colors32 = null;
  39548. this.pickedParticles = null;
  39549. };
  39550. /**
  39551. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  39552. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39553. * Returns the SPS.
  39554. */
  39555. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  39556. if (!this._isVisibilityBoxLocked) {
  39557. this.mesh.refreshBoundingInfo();
  39558. }
  39559. return this;
  39560. };
  39561. /**
  39562. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  39563. * @param size the size (float) of the visibility box
  39564. * note : this doesn't lock the SPS mesh bounding box.
  39565. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39566. */
  39567. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  39568. var vis = size / 2;
  39569. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  39570. };
  39571. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  39572. // getter and setter
  39573. get: function () {
  39574. return this._alwaysVisible;
  39575. },
  39576. /**
  39577. * Sets the SPS as always visible or not
  39578. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39579. */
  39580. set: function (val) {
  39581. this._alwaysVisible = val;
  39582. this.mesh.alwaysSelectAsActiveMesh = val;
  39583. },
  39584. enumerable: true,
  39585. configurable: true
  39586. });
  39587. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  39588. get: function () {
  39589. return this._isVisibilityBoxLocked;
  39590. },
  39591. /**
  39592. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  39593. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39594. */
  39595. set: function (val) {
  39596. this._isVisibilityBoxLocked = val;
  39597. this.mesh.getBoundingInfo().isLocked = val;
  39598. },
  39599. enumerable: true,
  39600. configurable: true
  39601. });
  39602. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  39603. // getters
  39604. get: function () {
  39605. return this._computeParticleRotation;
  39606. },
  39607. // Optimizer setters
  39608. /**
  39609. * Tells to `setParticles()` to compute the particle rotations or not.
  39610. * Default value : true. The SPS is faster when it's set to false.
  39611. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  39612. */
  39613. set: function (val) {
  39614. this._computeParticleRotation = val;
  39615. },
  39616. enumerable: true,
  39617. configurable: true
  39618. });
  39619. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  39620. get: function () {
  39621. return this._computeParticleColor;
  39622. },
  39623. /**
  39624. * Tells to `setParticles()` to compute the particle colors or not.
  39625. * Default value : true. The SPS is faster when it's set to false.
  39626. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  39627. */
  39628. set: function (val) {
  39629. this._computeParticleColor = val;
  39630. },
  39631. enumerable: true,
  39632. configurable: true
  39633. });
  39634. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  39635. get: function () {
  39636. return this._computeParticleTexture;
  39637. },
  39638. /**
  39639. * Tells to `setParticles()` to compute the particle textures or not.
  39640. * Default value : true. The SPS is faster when it's set to false.
  39641. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  39642. */
  39643. set: function (val) {
  39644. this._computeParticleTexture = val;
  39645. },
  39646. enumerable: true,
  39647. configurable: true
  39648. });
  39649. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  39650. get: function () {
  39651. return this._computeParticleVertex;
  39652. },
  39653. /**
  39654. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  39655. * Default value : false. The SPS is faster when it's set to false.
  39656. * Note : the particle custom vertex positions aren't stored values.
  39657. */
  39658. set: function (val) {
  39659. this._computeParticleVertex = val;
  39660. },
  39661. enumerable: true,
  39662. configurable: true
  39663. });
  39664. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  39665. get: function () {
  39666. return this._computeBoundingBox;
  39667. },
  39668. /**
  39669. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  39670. */
  39671. set: function (val) {
  39672. this._computeBoundingBox = val;
  39673. },
  39674. enumerable: true,
  39675. configurable: true
  39676. });
  39677. // =======================================================================
  39678. // Particle behavior logic
  39679. // these following methods may be overwritten by the user to fit his needs
  39680. /**
  39681. * This function does nothing. It may be overwritten to set all the particle first values.
  39682. * The SPS doesn't call this function, you may have to call it by your own.
  39683. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39684. */
  39685. SolidParticleSystem.prototype.initParticles = function () {
  39686. };
  39687. /**
  39688. * This function does nothing. It may be overwritten to recycle a particle.
  39689. * The SPS doesn't call this function, you may have to call it by your own.
  39690. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39691. */
  39692. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  39693. return particle;
  39694. };
  39695. /**
  39696. * Updates a particle : this function should be overwritten by the user.
  39697. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  39698. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39699. * ex : just set a particle position or velocity and recycle conditions
  39700. */
  39701. SolidParticleSystem.prototype.updateParticle = function (particle) {
  39702. return particle;
  39703. };
  39704. /**
  39705. * Updates a vertex of a particle : it can be overwritten by the user.
  39706. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  39707. * @param particle the current particle
  39708. * @param vertex the current index of the current particle
  39709. * @param pt the index of the current vertex in the particle shape
  39710. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  39711. * ex : just set a vertex particle position
  39712. */
  39713. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  39714. return vertex;
  39715. };
  39716. /**
  39717. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  39718. * This does nothing and may be overwritten by the user.
  39719. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39720. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39721. * @param update the boolean update value actually passed to setParticles()
  39722. */
  39723. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  39724. };
  39725. /**
  39726. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  39727. * This will be passed three parameters.
  39728. * This does nothing and may be overwritten by the user.
  39729. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39730. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39731. * @param update the boolean update value actually passed to setParticles()
  39732. */
  39733. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  39734. };
  39735. return SolidParticleSystem;
  39736. }());
  39737. BABYLON.SolidParticleSystem = SolidParticleSystem;
  39738. })(BABYLON || (BABYLON = {}));
  39739. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  39740. /// <reference path="babylon.mesh.ts" />
  39741. var BABYLON;
  39742. (function (BABYLON) {
  39743. var GroundMesh = (function (_super) {
  39744. __extends(GroundMesh, _super);
  39745. function GroundMesh(name, scene) {
  39746. var _this = _super.call(this, name, scene) || this;
  39747. _this.generateOctree = false;
  39748. _this._worldInverse = new BABYLON.Matrix();
  39749. return _this;
  39750. }
  39751. GroundMesh.prototype.getClassName = function () {
  39752. return "GroundMesh";
  39753. };
  39754. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  39755. get: function () {
  39756. return Math.min(this._subdivisionsX, this._subdivisionsY);
  39757. },
  39758. enumerable: true,
  39759. configurable: true
  39760. });
  39761. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  39762. get: function () {
  39763. return this._subdivisionsX;
  39764. },
  39765. enumerable: true,
  39766. configurable: true
  39767. });
  39768. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  39769. get: function () {
  39770. return this._subdivisionsY;
  39771. },
  39772. enumerable: true,
  39773. configurable: true
  39774. });
  39775. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  39776. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  39777. this._subdivisionsX = chunksCount;
  39778. this._subdivisionsY = chunksCount;
  39779. this.subdivide(chunksCount);
  39780. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  39781. };
  39782. /**
  39783. * Returns a height (y) value in the Worl system :
  39784. * the ground altitude at the coordinates (x, z) expressed in the World system.
  39785. * Returns the ground y position if (x, z) are outside the ground surface.
  39786. */
  39787. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  39788. var world = this.getWorldMatrix();
  39789. var invMat = BABYLON.Tmp.Matrix[5];
  39790. world.invertToRef(invMat);
  39791. var tmpVect = BABYLON.Tmp.Vector3[8];
  39792. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  39793. x = tmpVect.x;
  39794. z = tmpVect.z;
  39795. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39796. return this.position.y;
  39797. }
  39798. if (!this._heightQuads || this._heightQuads.length == 0) {
  39799. this._initHeightQuads();
  39800. this._computeHeightQuads();
  39801. }
  39802. var facet = this._getFacetAt(x, z);
  39803. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  39804. // return y in the World system
  39805. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  39806. return tmpVect.y;
  39807. };
  39808. /**
  39809. * Returns a normalized vector (Vector3) orthogonal to the ground
  39810. * at the ground coordinates (x, z) expressed in the World system.
  39811. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  39812. */
  39813. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  39814. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  39815. this.getNormalAtCoordinatesToRef(x, z, normal);
  39816. return normal;
  39817. };
  39818. /**
  39819. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  39820. * at the ground coordinates (x, z) expressed in the World system.
  39821. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  39822. * Returns the GroundMesh.
  39823. */
  39824. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  39825. var world = this.getWorldMatrix();
  39826. var tmpMat = BABYLON.Tmp.Matrix[5];
  39827. world.invertToRef(tmpMat);
  39828. var tmpVect = BABYLON.Tmp.Vector3[8];
  39829. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  39830. x = tmpVect.x;
  39831. z = tmpVect.z;
  39832. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39833. return this;
  39834. }
  39835. if (!this._heightQuads || this._heightQuads.length == 0) {
  39836. this._initHeightQuads();
  39837. this._computeHeightQuads();
  39838. }
  39839. var facet = this._getFacetAt(x, z);
  39840. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  39841. return this;
  39842. };
  39843. /**
  39844. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  39845. * if the ground has been updated.
  39846. * This can be used in the render loop.
  39847. * Returns the GroundMesh.
  39848. */
  39849. GroundMesh.prototype.updateCoordinateHeights = function () {
  39850. if (!this._heightQuads || this._heightQuads.length == 0) {
  39851. this._initHeightQuads();
  39852. }
  39853. this._computeHeightQuads();
  39854. return this;
  39855. };
  39856. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  39857. GroundMesh.prototype._getFacetAt = function (x, z) {
  39858. // retrieve col and row from x, z coordinates in the ground local system
  39859. var subdivisionsX = this._subdivisionsX;
  39860. var subdivisionsY = this._subdivisionsY;
  39861. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  39862. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  39863. var quad = this._heightQuads[row * this._subdivisionsX + col];
  39864. var facet;
  39865. if (z < quad.slope.x * x + quad.slope.y) {
  39866. facet = quad.facet1;
  39867. }
  39868. else {
  39869. facet = quad.facet2;
  39870. }
  39871. return facet;
  39872. };
  39873. // Creates and populates the heightMap array with "facet" elements :
  39874. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  39875. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39876. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39877. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39878. // Returns the GroundMesh.
  39879. GroundMesh.prototype._initHeightQuads = function () {
  39880. var subdivisionsX = this._subdivisionsX;
  39881. var subdivisionsY = this._subdivisionsY;
  39882. this._heightQuads = new Array();
  39883. for (var row = 0; row < subdivisionsY; row++) {
  39884. for (var col = 0; col < subdivisionsX; col++) {
  39885. 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) };
  39886. this._heightQuads[row * subdivisionsX + col] = quad;
  39887. }
  39888. }
  39889. return this;
  39890. };
  39891. // Compute each quad element values and update the the heightMap array :
  39892. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39893. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39894. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39895. // Returns the GroundMesh.
  39896. GroundMesh.prototype._computeHeightQuads = function () {
  39897. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39898. var v1 = BABYLON.Tmp.Vector3[3];
  39899. var v2 = BABYLON.Tmp.Vector3[2];
  39900. var v3 = BABYLON.Tmp.Vector3[1];
  39901. var v4 = BABYLON.Tmp.Vector3[0];
  39902. var v1v2 = BABYLON.Tmp.Vector3[4];
  39903. var v1v3 = BABYLON.Tmp.Vector3[5];
  39904. var v1v4 = BABYLON.Tmp.Vector3[6];
  39905. var norm1 = BABYLON.Tmp.Vector3[7];
  39906. var norm2 = BABYLON.Tmp.Vector3[8];
  39907. var i = 0;
  39908. var j = 0;
  39909. var k = 0;
  39910. var cd = 0; // 2D slope coefficient : z = cd * x + h
  39911. var h = 0;
  39912. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  39913. var d2 = 0;
  39914. var subdivisionsX = this._subdivisionsX;
  39915. var subdivisionsY = this._subdivisionsY;
  39916. for (var row = 0; row < subdivisionsY; row++) {
  39917. for (var col = 0; col < subdivisionsX; col++) {
  39918. i = col * 3;
  39919. j = row * (subdivisionsX + 1) * 3;
  39920. k = (row + 1) * (subdivisionsX + 1) * 3;
  39921. v1.x = positions[j + i];
  39922. v1.y = positions[j + i + 1];
  39923. v1.z = positions[j + i + 2];
  39924. v2.x = positions[j + i + 3];
  39925. v2.y = positions[j + i + 4];
  39926. v2.z = positions[j + i + 5];
  39927. v3.x = positions[k + i];
  39928. v3.y = positions[k + i + 1];
  39929. v3.z = positions[k + i + 2];
  39930. v4.x = positions[k + i + 3];
  39931. v4.y = positions[k + i + 4];
  39932. v4.z = positions[k + i + 5];
  39933. // 2D slope V1V4
  39934. cd = (v4.z - v1.z) / (v4.x - v1.x);
  39935. h = v1.z - cd * v1.x; // v1 belongs to the slope
  39936. // facet equations :
  39937. // we compute each facet normal vector
  39938. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  39939. // we compute the value d by applying the equation to v1 which belongs to the plane
  39940. // then we store the facet equation in a Vector4
  39941. v2.subtractToRef(v1, v1v2);
  39942. v3.subtractToRef(v1, v1v3);
  39943. v4.subtractToRef(v1, v1v4);
  39944. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  39945. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  39946. norm1.normalize();
  39947. norm2.normalize();
  39948. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  39949. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  39950. var quad = this._heightQuads[row * subdivisionsX + col];
  39951. quad.slope.copyFromFloats(cd, h);
  39952. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  39953. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  39954. }
  39955. }
  39956. return this;
  39957. };
  39958. GroundMesh.prototype.serialize = function (serializationObject) {
  39959. _super.prototype.serialize.call(this, serializationObject);
  39960. serializationObject.subdivisionsX = this._subdivisionsX;
  39961. serializationObject.subdivisionsY = this._subdivisionsY;
  39962. serializationObject.minX = this._minX;
  39963. serializationObject.maxX = this._maxX;
  39964. serializationObject.minZ = this._minZ;
  39965. serializationObject.maxZ = this._maxZ;
  39966. serializationObject.width = this._width;
  39967. serializationObject.height = this._height;
  39968. };
  39969. GroundMesh.Parse = function (parsedMesh, scene) {
  39970. var result = new GroundMesh(parsedMesh.name, scene);
  39971. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  39972. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  39973. result._minX = parsedMesh.minX;
  39974. result._maxX = parsedMesh.maxX;
  39975. result._minZ = parsedMesh.minZ;
  39976. result._maxZ = parsedMesh.maxZ;
  39977. result._width = parsedMesh.width;
  39978. result._height = parsedMesh.height;
  39979. return result;
  39980. };
  39981. return GroundMesh;
  39982. }(BABYLON.Mesh));
  39983. BABYLON.GroundMesh = GroundMesh;
  39984. })(BABYLON || (BABYLON = {}));
  39985. //# sourceMappingURL=babylon.groundMesh.js.map
  39986. var BABYLON;
  39987. (function (BABYLON) {
  39988. /**
  39989. * Creates an instance based on a source mesh.
  39990. */
  39991. var InstancedMesh = (function (_super) {
  39992. __extends(InstancedMesh, _super);
  39993. function InstancedMesh(name, source) {
  39994. var _this = _super.call(this, name, source.getScene()) || this;
  39995. source.instances.push(_this);
  39996. _this._sourceMesh = source;
  39997. _this.position.copyFrom(source.position);
  39998. _this.rotation.copyFrom(source.rotation);
  39999. _this.scaling.copyFrom(source.scaling);
  40000. if (source.rotationQuaternion) {
  40001. _this.rotationQuaternion = source.rotationQuaternion.clone();
  40002. }
  40003. _this.infiniteDistance = source.infiniteDistance;
  40004. _this.setPivotMatrix(source.getPivotMatrix());
  40005. _this.refreshBoundingInfo();
  40006. _this._syncSubMeshes();
  40007. return _this;
  40008. }
  40009. /**
  40010. * Returns the string "InstancedMesh".
  40011. */
  40012. InstancedMesh.prototype.getClassName = function () {
  40013. return "InstancedMesh";
  40014. };
  40015. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  40016. // Methods
  40017. get: function () {
  40018. return this._sourceMesh.receiveShadows;
  40019. },
  40020. enumerable: true,
  40021. configurable: true
  40022. });
  40023. Object.defineProperty(InstancedMesh.prototype, "material", {
  40024. get: function () {
  40025. return this._sourceMesh.material;
  40026. },
  40027. enumerable: true,
  40028. configurable: true
  40029. });
  40030. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  40031. get: function () {
  40032. return this._sourceMesh.visibility;
  40033. },
  40034. enumerable: true,
  40035. configurable: true
  40036. });
  40037. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  40038. get: function () {
  40039. return this._sourceMesh.skeleton;
  40040. },
  40041. enumerable: true,
  40042. configurable: true
  40043. });
  40044. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  40045. get: function () {
  40046. return this._sourceMesh.renderingGroupId;
  40047. },
  40048. enumerable: true,
  40049. configurable: true
  40050. });
  40051. /**
  40052. * Returns the total number of vertices (integer).
  40053. */
  40054. InstancedMesh.prototype.getTotalVertices = function () {
  40055. return this._sourceMesh.getTotalVertices();
  40056. };
  40057. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  40058. get: function () {
  40059. return this._sourceMesh;
  40060. },
  40061. enumerable: true,
  40062. configurable: true
  40063. });
  40064. /**
  40065. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  40066. */
  40067. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  40068. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  40069. };
  40070. /**
  40071. * Sets the vertex data of the mesh geometry for the requested `kind`.
  40072. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  40073. * The `data` are either a numeric array either a Float32Array.
  40074. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  40075. * 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).
  40076. * Note that a new underlying VertexBuffer object is created each call.
  40077. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  40078. *
  40079. * Possible `kind` values :
  40080. * - BABYLON.VertexBuffer.PositionKind
  40081. * - BABYLON.VertexBuffer.UVKind
  40082. * - BABYLON.VertexBuffer.UV2Kind
  40083. * - BABYLON.VertexBuffer.UV3Kind
  40084. * - BABYLON.VertexBuffer.UV4Kind
  40085. * - BABYLON.VertexBuffer.UV5Kind
  40086. * - BABYLON.VertexBuffer.UV6Kind
  40087. * - BABYLON.VertexBuffer.ColorKind
  40088. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40089. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40090. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40091. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40092. *
  40093. * Returns the Mesh.
  40094. */
  40095. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40096. if (this.sourceMesh) {
  40097. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  40098. }
  40099. return this.sourceMesh;
  40100. };
  40101. /**
  40102. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  40103. * If the mesh has no geometry, it is simply returned as it is.
  40104. * The `data` are either a numeric array either a Float32Array.
  40105. * No new underlying VertexBuffer object is created.
  40106. * 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.
  40107. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  40108. *
  40109. * Possible `kind` values :
  40110. * - BABYLON.VertexBuffer.PositionKind
  40111. * - BABYLON.VertexBuffer.UVKind
  40112. * - BABYLON.VertexBuffer.UV2Kind
  40113. * - BABYLON.VertexBuffer.UV3Kind
  40114. * - BABYLON.VertexBuffer.UV4Kind
  40115. * - BABYLON.VertexBuffer.UV5Kind
  40116. * - BABYLON.VertexBuffer.UV6Kind
  40117. * - BABYLON.VertexBuffer.ColorKind
  40118. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40119. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40120. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40121. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40122. *
  40123. * Returns the Mesh.
  40124. */
  40125. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  40126. if (this.sourceMesh) {
  40127. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  40128. }
  40129. return this.sourceMesh;
  40130. };
  40131. /**
  40132. * Sets the mesh indices.
  40133. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  40134. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  40135. * This method creates a new index buffer each call.
  40136. * Returns the Mesh.
  40137. */
  40138. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  40139. if (this.sourceMesh) {
  40140. this.sourceMesh.setIndices(indices, totalVertices);
  40141. }
  40142. return this.sourceMesh;
  40143. };
  40144. /**
  40145. * Boolean : True if the mesh owns the requested kind of data.
  40146. */
  40147. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  40148. return this._sourceMesh.isVerticesDataPresent(kind);
  40149. };
  40150. /**
  40151. * Returns an array of indices (IndicesArray).
  40152. */
  40153. InstancedMesh.prototype.getIndices = function () {
  40154. return this._sourceMesh.getIndices();
  40155. };
  40156. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  40157. get: function () {
  40158. return this._sourceMesh._positions;
  40159. },
  40160. enumerable: true,
  40161. configurable: true
  40162. });
  40163. /**
  40164. * Sets a new updated BoundingInfo to the mesh.
  40165. * Returns the mesh.
  40166. */
  40167. InstancedMesh.prototype.refreshBoundingInfo = function () {
  40168. var meshBB = this._sourceMesh.getBoundingInfo();
  40169. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  40170. this._updateBoundingInfo();
  40171. return this;
  40172. };
  40173. InstancedMesh.prototype._preActivate = function () {
  40174. if (this._currentLOD) {
  40175. this._currentLOD._preActivate();
  40176. }
  40177. return this;
  40178. };
  40179. InstancedMesh.prototype._activate = function (renderId) {
  40180. if (this._currentLOD) {
  40181. this._currentLOD._registerInstanceForRenderId(this, renderId);
  40182. }
  40183. return this;
  40184. };
  40185. /**
  40186. * Returns the current associated LOD AbstractMesh.
  40187. */
  40188. InstancedMesh.prototype.getLOD = function (camera) {
  40189. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  40190. if (this._currentLOD === this.sourceMesh) {
  40191. return this;
  40192. }
  40193. return this._currentLOD;
  40194. };
  40195. InstancedMesh.prototype._syncSubMeshes = function () {
  40196. this.releaseSubMeshes();
  40197. if (this._sourceMesh.subMeshes) {
  40198. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  40199. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  40200. }
  40201. }
  40202. return this;
  40203. };
  40204. InstancedMesh.prototype._generatePointsArray = function () {
  40205. return this._sourceMesh._generatePointsArray();
  40206. };
  40207. /**
  40208. * Creates a new InstancedMesh from the current mesh.
  40209. * - name (string) : the cloned mesh name
  40210. * - newParent (optional Node) : the optional Node to parent the clone to.
  40211. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  40212. *
  40213. * Returns the clone.
  40214. */
  40215. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40216. var result = this._sourceMesh.createInstance(name);
  40217. // Deep copy
  40218. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  40219. // Bounding info
  40220. this.refreshBoundingInfo();
  40221. // Parent
  40222. if (newParent) {
  40223. result.parent = newParent;
  40224. }
  40225. if (!doNotCloneChildren) {
  40226. // Children
  40227. for (var index = 0; index < this.getScene().meshes.length; index++) {
  40228. var mesh = this.getScene().meshes[index];
  40229. if (mesh.parent === this) {
  40230. mesh.clone(mesh.name, result);
  40231. }
  40232. }
  40233. }
  40234. result.computeWorldMatrix(true);
  40235. return result;
  40236. };
  40237. /**
  40238. * Disposes the InstancedMesh.
  40239. * Returns nothing.
  40240. */
  40241. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  40242. // Remove from mesh
  40243. var index = this._sourceMesh.instances.indexOf(this);
  40244. this._sourceMesh.instances.splice(index, 1);
  40245. _super.prototype.dispose.call(this, doNotRecurse);
  40246. };
  40247. return InstancedMesh;
  40248. }(BABYLON.AbstractMesh));
  40249. BABYLON.InstancedMesh = InstancedMesh;
  40250. })(BABYLON || (BABYLON = {}));
  40251. //# sourceMappingURL=babylon.instancedMesh.js.map
  40252. /// <reference path="babylon.mesh.ts" />
  40253. var BABYLON;
  40254. (function (BABYLON) {
  40255. var LinesMesh = (function (_super) {
  40256. __extends(LinesMesh, _super);
  40257. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  40258. if (parent === void 0) { parent = null; }
  40259. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  40260. _this.useVertexColor = useVertexColor;
  40261. _this.color = new BABYLON.Color3(1, 1, 1);
  40262. _this.alpha = 1;
  40263. if (source) {
  40264. _this.color = source.color.clone();
  40265. _this.alpha = source.alpha;
  40266. _this.useVertexColor = source.useVertexColor;
  40267. }
  40268. _this._intersectionThreshold = 0.1;
  40269. var options = {
  40270. attributes: [BABYLON.VertexBuffer.PositionKind],
  40271. uniforms: ["world", "viewProjection"],
  40272. needAlphaBlending: false,
  40273. };
  40274. if (!useVertexColor) {
  40275. options.uniforms.push("color");
  40276. options.needAlphaBlending = true;
  40277. }
  40278. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  40279. return _this;
  40280. }
  40281. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  40282. /**
  40283. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40284. * This margin is expressed in world space coordinates, so its value may vary.
  40285. * Default value is 0.1
  40286. * @returns the intersection Threshold value.
  40287. */
  40288. get: function () {
  40289. return this._intersectionThreshold;
  40290. },
  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. * @param value the new threshold to apply
  40295. */
  40296. set: function (value) {
  40297. if (this._intersectionThreshold === value) {
  40298. return;
  40299. }
  40300. this._intersectionThreshold = value;
  40301. if (this.geometry) {
  40302. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  40303. }
  40304. },
  40305. enumerable: true,
  40306. configurable: true
  40307. });
  40308. /**
  40309. * Returns the string "LineMesh"
  40310. */
  40311. LinesMesh.prototype.getClassName = function () {
  40312. return "LinesMesh";
  40313. };
  40314. Object.defineProperty(LinesMesh.prototype, "material", {
  40315. get: function () {
  40316. return this._colorShader;
  40317. },
  40318. enumerable: true,
  40319. configurable: true
  40320. });
  40321. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  40322. get: function () {
  40323. return false;
  40324. },
  40325. enumerable: true,
  40326. configurable: true
  40327. });
  40328. LinesMesh.prototype.createInstance = function (name) {
  40329. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  40330. return null;
  40331. };
  40332. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  40333. // VBOs
  40334. this._geometry._bind(this._colorShader.getEffect());
  40335. // Color
  40336. if (!this.useVertexColor) {
  40337. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  40338. }
  40339. return this;
  40340. };
  40341. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  40342. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  40343. return this;
  40344. }
  40345. var engine = this.getScene().getEngine();
  40346. // Draw order
  40347. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  40348. return this;
  40349. };
  40350. LinesMesh.prototype.dispose = function (doNotRecurse) {
  40351. this._colorShader.dispose();
  40352. _super.prototype.dispose.call(this, doNotRecurse);
  40353. };
  40354. /**
  40355. * Returns a new LineMesh object cloned from the current one.
  40356. */
  40357. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40358. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  40359. };
  40360. return LinesMesh;
  40361. }(BABYLON.Mesh));
  40362. BABYLON.LinesMesh = LinesMesh;
  40363. })(BABYLON || (BABYLON = {}));
  40364. //# sourceMappingURL=babylon.linesMesh.js.map
  40365. var BABYLON;
  40366. (function (BABYLON) {
  40367. var ShaderMaterial = (function (_super) {
  40368. __extends(ShaderMaterial, _super);
  40369. function ShaderMaterial(name, scene, shaderPath, options) {
  40370. var _this = _super.call(this, name, scene) || this;
  40371. _this._textures = {};
  40372. _this._textureArrays = {};
  40373. _this._floats = {};
  40374. _this._floatsArrays = {};
  40375. _this._colors3 = {};
  40376. _this._colors4 = {};
  40377. _this._vectors2 = {};
  40378. _this._vectors3 = {};
  40379. _this._vectors4 = {};
  40380. _this._matrices = {};
  40381. _this._matrices3x3 = {};
  40382. _this._matrices2x2 = {};
  40383. _this._vectors3Arrays = {};
  40384. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40385. _this._shaderPath = shaderPath;
  40386. options.needAlphaBlending = options.needAlphaBlending || false;
  40387. options.needAlphaTesting = options.needAlphaTesting || false;
  40388. options.attributes = options.attributes || ["position", "normal", "uv"];
  40389. options.uniforms = options.uniforms || ["worldViewProjection"];
  40390. options.uniformBuffers = options.uniformBuffers || [];
  40391. options.samplers = options.samplers || [];
  40392. options.defines = options.defines || [];
  40393. _this._options = options;
  40394. return _this;
  40395. }
  40396. ShaderMaterial.prototype.getClassName = function () {
  40397. return "ShaderMaterial";
  40398. };
  40399. ShaderMaterial.prototype.needAlphaBlending = function () {
  40400. return this._options.needAlphaBlending;
  40401. };
  40402. ShaderMaterial.prototype.needAlphaTesting = function () {
  40403. return this._options.needAlphaTesting;
  40404. };
  40405. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40406. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40407. this._options.uniforms.push(uniformName);
  40408. }
  40409. };
  40410. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40411. if (this._options.samplers.indexOf(name) === -1) {
  40412. this._options.samplers.push(name);
  40413. }
  40414. this._textures[name] = texture;
  40415. return this;
  40416. };
  40417. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40418. if (this._options.samplers.indexOf(name) === -1) {
  40419. this._options.samplers.push(name);
  40420. }
  40421. this._checkUniform(name);
  40422. this._textureArrays[name] = textures;
  40423. return this;
  40424. };
  40425. ShaderMaterial.prototype.setFloat = function (name, value) {
  40426. this._checkUniform(name);
  40427. this._floats[name] = value;
  40428. return this;
  40429. };
  40430. ShaderMaterial.prototype.setFloats = function (name, value) {
  40431. this._checkUniform(name);
  40432. this._floatsArrays[name] = value;
  40433. return this;
  40434. };
  40435. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40436. this._checkUniform(name);
  40437. this._colors3[name] = value;
  40438. return this;
  40439. };
  40440. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40441. this._checkUniform(name);
  40442. this._colors4[name] = value;
  40443. return this;
  40444. };
  40445. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40446. this._checkUniform(name);
  40447. this._vectors2[name] = value;
  40448. return this;
  40449. };
  40450. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40451. this._checkUniform(name);
  40452. this._vectors3[name] = value;
  40453. return this;
  40454. };
  40455. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40456. this._checkUniform(name);
  40457. this._vectors4[name] = value;
  40458. return this;
  40459. };
  40460. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40461. this._checkUniform(name);
  40462. this._matrices[name] = value;
  40463. return this;
  40464. };
  40465. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40466. this._checkUniform(name);
  40467. this._matrices3x3[name] = value;
  40468. return this;
  40469. };
  40470. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40471. this._checkUniform(name);
  40472. this._matrices2x2[name] = value;
  40473. return this;
  40474. };
  40475. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40476. this._checkUniform(name);
  40477. this._vectors3Arrays[name] = value;
  40478. return this;
  40479. };
  40480. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40481. if (!mesh) {
  40482. return true;
  40483. }
  40484. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40485. return false;
  40486. }
  40487. return false;
  40488. };
  40489. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40490. var scene = this.getScene();
  40491. var engine = scene.getEngine();
  40492. if (!this.checkReadyOnEveryCall) {
  40493. if (this._renderId === scene.getRenderId()) {
  40494. if (this._checkCache(scene, mesh, useInstances)) {
  40495. return true;
  40496. }
  40497. }
  40498. }
  40499. // Instances
  40500. var defines = [];
  40501. var attribs = [];
  40502. var fallbacks = new BABYLON.EffectFallbacks();
  40503. if (useInstances) {
  40504. defines.push("#define INSTANCES");
  40505. }
  40506. for (var index = 0; index < this._options.defines.length; index++) {
  40507. defines.push(this._options.defines[index]);
  40508. }
  40509. for (var index = 0; index < this._options.attributes.length; index++) {
  40510. attribs.push(this._options.attributes[index]);
  40511. }
  40512. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40513. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40514. defines.push("#define VERTEXCOLOR");
  40515. }
  40516. // Bones
  40517. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40518. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40519. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40520. if (mesh.numBoneInfluencers > 4) {
  40521. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40522. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40523. }
  40524. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40525. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40526. fallbacks.addCPUSkinningFallback(0, mesh);
  40527. if (this._options.uniforms.indexOf("mBones") === -1) {
  40528. this._options.uniforms.push("mBones");
  40529. }
  40530. }
  40531. else {
  40532. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40533. }
  40534. // Textures
  40535. for (var name in this._textures) {
  40536. if (!this._textures[name].isReady()) {
  40537. return false;
  40538. }
  40539. }
  40540. // Alpha test
  40541. if (engine.getAlphaTesting()) {
  40542. defines.push("#define ALPHATEST");
  40543. }
  40544. var previousEffect = this._effect;
  40545. var join = defines.join("\n");
  40546. this._effect = engine.createEffect(this._shaderPath, {
  40547. attributes: attribs,
  40548. uniformsNames: this._options.uniforms,
  40549. uniformBuffersNames: this._options.uniformBuffers,
  40550. samplers: this._options.samplers,
  40551. defines: join,
  40552. fallbacks: fallbacks,
  40553. onCompiled: this.onCompiled,
  40554. onError: this.onError
  40555. }, engine);
  40556. if (!this._effect.isReady()) {
  40557. return false;
  40558. }
  40559. if (previousEffect !== this._effect) {
  40560. scene.resetCachedMaterial();
  40561. }
  40562. this._renderId = scene.getRenderId();
  40563. return true;
  40564. };
  40565. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40566. var scene = this.getScene();
  40567. if (this._options.uniforms.indexOf("world") !== -1) {
  40568. this._effect.setMatrix("world", world);
  40569. }
  40570. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40571. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40572. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40573. }
  40574. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40575. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40576. }
  40577. };
  40578. ShaderMaterial.prototype.bind = function (world, mesh) {
  40579. // Std values
  40580. this.bindOnlyWorldMatrix(world);
  40581. if (this.getScene().getCachedMaterial() !== this) {
  40582. if (this._options.uniforms.indexOf("view") !== -1) {
  40583. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40584. }
  40585. if (this._options.uniforms.indexOf("projection") !== -1) {
  40586. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40587. }
  40588. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40589. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40590. }
  40591. // Bones
  40592. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40593. var name;
  40594. // Texture
  40595. for (name in this._textures) {
  40596. this._effect.setTexture(name, this._textures[name]);
  40597. }
  40598. // Texture arrays
  40599. for (name in this._textureArrays) {
  40600. this._effect.setTextureArray(name, this._textureArrays[name]);
  40601. }
  40602. // Float
  40603. for (name in this._floats) {
  40604. this._effect.setFloat(name, this._floats[name]);
  40605. }
  40606. // Float s
  40607. for (name in this._floatsArrays) {
  40608. this._effect.setArray(name, this._floatsArrays[name]);
  40609. }
  40610. // Color3
  40611. for (name in this._colors3) {
  40612. this._effect.setColor3(name, this._colors3[name]);
  40613. }
  40614. // Color4
  40615. for (name in this._colors4) {
  40616. var color = this._colors4[name];
  40617. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40618. }
  40619. // Vector2
  40620. for (name in this._vectors2) {
  40621. this._effect.setVector2(name, this._vectors2[name]);
  40622. }
  40623. // Vector3
  40624. for (name in this._vectors3) {
  40625. this._effect.setVector3(name, this._vectors3[name]);
  40626. }
  40627. // Vector4
  40628. for (name in this._vectors4) {
  40629. this._effect.setVector4(name, this._vectors4[name]);
  40630. }
  40631. // Matrix
  40632. for (name in this._matrices) {
  40633. this._effect.setMatrix(name, this._matrices[name]);
  40634. }
  40635. // Matrix 3x3
  40636. for (name in this._matrices3x3) {
  40637. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40638. }
  40639. // Matrix 2x2
  40640. for (name in this._matrices2x2) {
  40641. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40642. }
  40643. // Vector3Array
  40644. for (name in this._vectors3Arrays) {
  40645. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40646. }
  40647. }
  40648. this._afterBind(mesh);
  40649. };
  40650. ShaderMaterial.prototype.getActiveTextures = function () {
  40651. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40652. for (var name in this._textures) {
  40653. activeTextures.push(this._textures[name]);
  40654. }
  40655. for (var name in this._textureArrays) {
  40656. var array = this._textureArrays[name];
  40657. for (var index = 0; index < array.length; index++) {
  40658. activeTextures.push(array[index]);
  40659. }
  40660. }
  40661. return activeTextures;
  40662. };
  40663. ShaderMaterial.prototype.clone = function (name) {
  40664. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40665. return newShaderMaterial;
  40666. };
  40667. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40668. if (forceDisposeTextures) {
  40669. var name;
  40670. for (name in this._textures) {
  40671. this._textures[name].dispose();
  40672. }
  40673. for (name in this._textureArrays) {
  40674. var array = this._textureArrays[name];
  40675. for (var index = 0; index < array.length; index++) {
  40676. array[index].dispose();
  40677. }
  40678. }
  40679. }
  40680. this._textures = {};
  40681. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40682. };
  40683. ShaderMaterial.prototype.serialize = function () {
  40684. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40685. serializationObject.customType = "BABYLON.ShaderMaterial";
  40686. serializationObject.options = this._options;
  40687. serializationObject.shaderPath = this._shaderPath;
  40688. var name;
  40689. // Texture
  40690. serializationObject.textures = {};
  40691. for (name in this._textures) {
  40692. serializationObject.textures[name] = this._textures[name].serialize();
  40693. }
  40694. // Texture arrays
  40695. serializationObject.textureArrays = {};
  40696. for (name in this._textureArrays) {
  40697. serializationObject.textureArrays[name] = [];
  40698. var array = this._textureArrays[name];
  40699. for (var index = 0; index < array.length; index++) {
  40700. serializationObject.textureArrays[name].push(array[index].serialize());
  40701. }
  40702. }
  40703. // Float
  40704. serializationObject.floats = {};
  40705. for (name in this._floats) {
  40706. serializationObject.floats[name] = this._floats[name];
  40707. }
  40708. // Float s
  40709. serializationObject.floatArrays = {};
  40710. for (name in this._floatsArrays) {
  40711. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40712. }
  40713. // Color3
  40714. serializationObject.colors3 = {};
  40715. for (name in this._colors3) {
  40716. serializationObject.colors3[name] = this._colors3[name].asArray();
  40717. }
  40718. // Color4
  40719. serializationObject.colors4 = {};
  40720. for (name in this._colors4) {
  40721. serializationObject.colors4[name] = this._colors4[name].asArray();
  40722. }
  40723. // Vector2
  40724. serializationObject.vectors2 = {};
  40725. for (name in this._vectors2) {
  40726. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40727. }
  40728. // Vector3
  40729. serializationObject.vectors3 = {};
  40730. for (name in this._vectors3) {
  40731. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40732. }
  40733. // Vector4
  40734. serializationObject.vectors4 = {};
  40735. for (name in this._vectors4) {
  40736. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40737. }
  40738. // Matrix
  40739. serializationObject.matrices = {};
  40740. for (name in this._matrices) {
  40741. serializationObject.matrices[name] = this._matrices[name].asArray();
  40742. }
  40743. // Matrix 3x3
  40744. serializationObject.matrices3x3 = {};
  40745. for (name in this._matrices3x3) {
  40746. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40747. }
  40748. // Matrix 2x2
  40749. serializationObject.matrices2x2 = {};
  40750. for (name in this._matrices2x2) {
  40751. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40752. }
  40753. // Vector3Array
  40754. serializationObject.vectors3Arrays = {};
  40755. for (name in this._vectors3Arrays) {
  40756. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40757. }
  40758. return serializationObject;
  40759. };
  40760. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40761. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40762. var name;
  40763. // Texture
  40764. for (name in source.textures) {
  40765. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40766. }
  40767. // Texture arrays
  40768. for (name in source.textureArrays) {
  40769. var array = source.textureArrays[name];
  40770. var textureArray = new Array();
  40771. for (var index = 0; index < array.length; index++) {
  40772. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40773. }
  40774. material.setTextureArray(name, textureArray);
  40775. }
  40776. // Float
  40777. for (name in source.floats) {
  40778. material.setFloat(name, source.floats[name]);
  40779. }
  40780. // Float s
  40781. for (name in source.floatsArrays) {
  40782. material.setFloats(name, source.floatsArrays[name]);
  40783. }
  40784. // Color3
  40785. for (name in source.colors3) {
  40786. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40787. }
  40788. // Color4
  40789. for (name in source.colors4) {
  40790. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40791. }
  40792. // Vector2
  40793. for (name in source.vectors2) {
  40794. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40795. }
  40796. // Vector3
  40797. for (name in source.vectors3) {
  40798. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40799. }
  40800. // Vector4
  40801. for (name in source.vectors4) {
  40802. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40803. }
  40804. // Matrix
  40805. for (name in source.matrices) {
  40806. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40807. }
  40808. // Matrix 3x3
  40809. for (name in source.matrices3x3) {
  40810. material.setMatrix3x3(name, source.matrices3x3[name]);
  40811. }
  40812. // Matrix 2x2
  40813. for (name in source.matrices2x2) {
  40814. material.setMatrix2x2(name, source.matrices2x2[name]);
  40815. }
  40816. // Vector3Array
  40817. for (name in source.vectors3Arrays) {
  40818. material.setArray3(name, source.vectors3Arrays[name]);
  40819. }
  40820. return material;
  40821. };
  40822. return ShaderMaterial;
  40823. }(BABYLON.Material));
  40824. BABYLON.ShaderMaterial = ShaderMaterial;
  40825. })(BABYLON || (BABYLON = {}));
  40826. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40827. var BABYLON;
  40828. (function (BABYLON) {
  40829. var MeshBuilder = (function () {
  40830. function MeshBuilder() {
  40831. }
  40832. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  40833. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  40834. return BABYLON.Mesh.DOUBLESIDE;
  40835. }
  40836. if (orientation === undefined || orientation === null) {
  40837. return BABYLON.Mesh.FRONTSIDE;
  40838. }
  40839. return orientation;
  40840. };
  40841. /**
  40842. * Creates a box mesh.
  40843. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  40844. * The parameter `size` sets the size (float) of each box side (default 1).
  40845. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  40846. * 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).
  40847. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40849. * 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).
  40850. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40852. */
  40853. MeshBuilder.CreateBox = function (name, options, scene) {
  40854. var box = new BABYLON.Mesh(name, scene);
  40855. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40856. box.sideOrientation = options.sideOrientation;
  40857. var vertexData = BABYLON.VertexData.CreateBox(options);
  40858. vertexData.applyToMesh(box, options.updatable);
  40859. return box;
  40860. };
  40861. /**
  40862. * Creates a sphere mesh.
  40863. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  40864. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  40865. * 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`).
  40866. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  40867. * 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
  40868. * 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).
  40869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40870. * 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).
  40871. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40873. */
  40874. MeshBuilder.CreateSphere = function (name, options, scene) {
  40875. var sphere = new BABYLON.Mesh(name, scene);
  40876. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40877. sphere.sideOrientation = options.sideOrientation;
  40878. var vertexData = BABYLON.VertexData.CreateSphere(options);
  40879. vertexData.applyToMesh(sphere, options.updatable);
  40880. return sphere;
  40881. };
  40882. /**
  40883. * Creates a plane polygonal mesh. By default, this is a disc.
  40884. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  40885. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  40886. * 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.
  40887. * 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
  40888. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40889. * 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).
  40890. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40891. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40892. */
  40893. MeshBuilder.CreateDisc = function (name, options, scene) {
  40894. var disc = new BABYLON.Mesh(name, scene);
  40895. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40896. disc.sideOrientation = options.sideOrientation;
  40897. var vertexData = BABYLON.VertexData.CreateDisc(options);
  40898. vertexData.applyToMesh(disc, options.updatable);
  40899. return disc;
  40900. };
  40901. /**
  40902. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  40903. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  40904. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  40905. * 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`).
  40906. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  40907. * 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.
  40908. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40909. * 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).
  40910. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40912. */
  40913. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  40914. var sphere = new BABYLON.Mesh(name, scene);
  40915. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40916. sphere.sideOrientation = options.sideOrientation;
  40917. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  40918. vertexData.applyToMesh(sphere, options.updatable);
  40919. return sphere;
  40920. };
  40921. ;
  40922. /**
  40923. * Creates a ribbon mesh.
  40924. * 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.
  40925. *
  40926. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  40927. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  40928. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  40929. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  40930. * 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.
  40931. * 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.
  40932. * 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
  40933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40934. * 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).
  40935. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40936. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40937. * 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.
  40938. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  40939. * 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
  40940. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  40941. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  40942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40943. */
  40944. MeshBuilder.CreateRibbon = function (name, options, scene) {
  40945. var pathArray = options.pathArray;
  40946. var closeArray = options.closeArray;
  40947. var closePath = options.closePath;
  40948. var offset = options.offset;
  40949. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40950. var instance = options.instance;
  40951. var updatable = options.updatable;
  40952. if (instance) {
  40953. // positionFunction : ribbon case
  40954. // only pathArray and sideOrientation parameters are taken into account for positions update
  40955. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  40956. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  40957. var positionFunction = function (positions) {
  40958. var minlg = pathArray[0].length;
  40959. var i = 0;
  40960. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  40961. for (var si = 1; si <= ns; si++) {
  40962. for (var p = 0; p < pathArray.length; p++) {
  40963. var path = pathArray[p];
  40964. var l = path.length;
  40965. minlg = (minlg < l) ? minlg : l;
  40966. var j = 0;
  40967. while (j < minlg) {
  40968. positions[i] = path[j].x;
  40969. positions[i + 1] = path[j].y;
  40970. positions[i + 2] = path[j].z;
  40971. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  40972. BABYLON.Tmp.Vector3[0].x = path[j].x;
  40973. }
  40974. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  40975. BABYLON.Tmp.Vector3[1].x = path[j].x;
  40976. }
  40977. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  40978. BABYLON.Tmp.Vector3[0].y = path[j].y;
  40979. }
  40980. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  40981. BABYLON.Tmp.Vector3[1].y = path[j].y;
  40982. }
  40983. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  40984. BABYLON.Tmp.Vector3[0].z = path[j].z;
  40985. }
  40986. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  40987. BABYLON.Tmp.Vector3[1].z = path[j].z;
  40988. }
  40989. j++;
  40990. i += 3;
  40991. }
  40992. if (instance._closePath) {
  40993. positions[i] = path[0].x;
  40994. positions[i + 1] = path[0].y;
  40995. positions[i + 2] = path[0].z;
  40996. i += 3;
  40997. }
  40998. }
  40999. }
  41000. };
  41001. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41002. positionFunction(positions);
  41003. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  41004. instance._boundingInfo.update(instance._worldMatrix);
  41005. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  41006. if (options.colors) {
  41007. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41008. for (var c = 0; c < options.colors.length; c++) {
  41009. colors[c * 4] = options.colors[c].r;
  41010. colors[c * 4 + 1] = options.colors[c].g;
  41011. colors[c * 4 + 2] = options.colors[c].b;
  41012. colors[c * 4 + 3] = options.colors[c].a;
  41013. }
  41014. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  41015. }
  41016. if (options.uvs) {
  41017. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41018. for (var i = 0; i < options.uvs.length; i++) {
  41019. uvs[i * 2] = options.uvs[i].x;
  41020. uvs[i * 2 + 1] = options.uvs[i].y;
  41021. }
  41022. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  41023. }
  41024. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  41025. var indices = instance.getIndices();
  41026. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41027. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  41028. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  41029. if (instance._closePath) {
  41030. var indexFirst = 0;
  41031. var indexLast = 0;
  41032. for (var p = 0; p < pathArray.length; p++) {
  41033. indexFirst = instance._idx[p] * 3;
  41034. if (p + 1 < pathArray.length) {
  41035. indexLast = (instance._idx[p + 1] - 1) * 3;
  41036. }
  41037. else {
  41038. indexLast = normals.length - 3;
  41039. }
  41040. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  41041. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  41042. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  41043. normals[indexLast] = normals[indexFirst];
  41044. normals[indexLast + 1] = normals[indexFirst + 1];
  41045. normals[indexLast + 2] = normals[indexFirst + 2];
  41046. }
  41047. }
  41048. if (!(instance.areNormalsFrozen)) {
  41049. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  41050. }
  41051. }
  41052. return instance;
  41053. }
  41054. else {
  41055. var ribbon = new BABYLON.Mesh(name, scene);
  41056. ribbon.sideOrientation = sideOrientation;
  41057. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  41058. if (closePath) {
  41059. ribbon._idx = vertexData._idx;
  41060. }
  41061. ribbon._closePath = closePath;
  41062. ribbon._closeArray = closeArray;
  41063. vertexData.applyToMesh(ribbon, updatable);
  41064. return ribbon;
  41065. }
  41066. };
  41067. /**
  41068. * Creates a cylinder or a cone mesh.
  41069. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  41070. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  41071. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  41072. * 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.
  41073. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  41074. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  41075. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  41076. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  41077. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  41078. * 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).
  41079. * 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
  41080. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  41081. * 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
  41082. * 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.
  41083. * If `enclose` is false, a ring surface is one element.
  41084. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  41085. * 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
  41086. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41087. * 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).
  41088. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41090. */
  41091. MeshBuilder.CreateCylinder = function (name, options, scene) {
  41092. var cylinder = new BABYLON.Mesh(name, scene);
  41093. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41094. cylinder.sideOrientation = options.sideOrientation;
  41095. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  41096. vertexData.applyToMesh(cylinder, options.updatable);
  41097. return cylinder;
  41098. };
  41099. /**
  41100. * Creates a torus mesh.
  41101. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  41102. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  41103. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  41104. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  41105. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41106. * 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).
  41107. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41109. */
  41110. MeshBuilder.CreateTorus = function (name, options, scene) {
  41111. var torus = new BABYLON.Mesh(name, scene);
  41112. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41113. torus.sideOrientation = options.sideOrientation;
  41114. var vertexData = BABYLON.VertexData.CreateTorus(options);
  41115. vertexData.applyToMesh(torus, options.updatable);
  41116. return torus;
  41117. };
  41118. /**
  41119. * Creates a torus knot mesh.
  41120. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  41121. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  41122. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  41123. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  41124. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  41125. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41126. * 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).
  41127. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41129. */
  41130. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  41131. var torusKnot = new BABYLON.Mesh(name, scene);
  41132. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41133. torusKnot.sideOrientation = options.sideOrientation;
  41134. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  41135. vertexData.applyToMesh(torusKnot, options.updatable);
  41136. return torusKnot;
  41137. };
  41138. /**
  41139. * Creates a line system mesh.
  41140. * A line system is a pool of many lines gathered in a single mesh.
  41141. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  41142. * 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.
  41143. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  41144. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  41145. * 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
  41146. * 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
  41147. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  41148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41149. */
  41150. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  41151. var instance = options.instance;
  41152. var lines = options.lines;
  41153. if (instance) {
  41154. var positionFunction = function (positions) {
  41155. var i = 0;
  41156. for (var l = 0; l < lines.length; l++) {
  41157. var points = lines[l];
  41158. for (var p = 0; p < points.length; p++) {
  41159. positions[i] = points[p].x;
  41160. positions[i + 1] = points[p].y;
  41161. positions[i + 2] = points[p].z;
  41162. i += 3;
  41163. }
  41164. }
  41165. };
  41166. instance.updateMeshPositions(positionFunction, false);
  41167. return instance;
  41168. }
  41169. // line system creation
  41170. var lineSystem = new BABYLON.LinesMesh(name, scene);
  41171. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  41172. vertexData.applyToMesh(lineSystem, options.updatable);
  41173. return lineSystem;
  41174. };
  41175. /**
  41176. * Creates a line mesh.
  41177. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  41178. * 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.
  41179. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  41180. * The parameter `points` is an array successive Vector3.
  41181. * 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
  41182. * When updating an instance, remember that only point positions can change, not the number of points.
  41183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41184. */
  41185. MeshBuilder.CreateLines = function (name, options, scene) {
  41186. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  41187. return lines;
  41188. };
  41189. /**
  41190. * Creates a dashed line mesh.
  41191. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  41192. * 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.
  41193. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  41194. * The parameter `points` is an array successive Vector3.
  41195. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  41196. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  41197. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  41198. * 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
  41199. * When updating an instance, remember that only point positions can change, not the number of points.
  41200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41201. */
  41202. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  41203. var points = options.points;
  41204. var instance = options.instance;
  41205. var gapSize = options.gapSize;
  41206. var dashNb = options.dashNb;
  41207. var dashSize = options.dashSize;
  41208. if (instance) {
  41209. var positionFunction = function (positions) {
  41210. var curvect = BABYLON.Vector3.Zero();
  41211. var nbSeg = positions.length / 6;
  41212. var lg = 0;
  41213. var nb = 0;
  41214. var shft = 0;
  41215. var dashshft = 0;
  41216. var curshft = 0;
  41217. var p = 0;
  41218. var i = 0;
  41219. var j = 0;
  41220. for (i = 0; i < points.length - 1; i++) {
  41221. points[i + 1].subtractToRef(points[i], curvect);
  41222. lg += curvect.length();
  41223. }
  41224. shft = lg / nbSeg;
  41225. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  41226. for (i = 0; i < points.length - 1; i++) {
  41227. points[i + 1].subtractToRef(points[i], curvect);
  41228. nb = Math.floor(curvect.length() / shft);
  41229. curvect.normalize();
  41230. j = 0;
  41231. while (j < nb && p < positions.length) {
  41232. curshft = shft * j;
  41233. positions[p] = points[i].x + curshft * curvect.x;
  41234. positions[p + 1] = points[i].y + curshft * curvect.y;
  41235. positions[p + 2] = points[i].z + curshft * curvect.z;
  41236. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  41237. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  41238. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  41239. p += 6;
  41240. j++;
  41241. }
  41242. }
  41243. while (p < positions.length) {
  41244. positions[p] = points[i].x;
  41245. positions[p + 1] = points[i].y;
  41246. positions[p + 2] = points[i].z;
  41247. p += 3;
  41248. }
  41249. };
  41250. instance.updateMeshPositions(positionFunction, false);
  41251. return instance;
  41252. }
  41253. // dashed lines creation
  41254. var dashedLines = new BABYLON.LinesMesh(name, scene);
  41255. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  41256. vertexData.applyToMesh(dashedLines, options.updatable);
  41257. dashedLines.dashSize = dashSize;
  41258. dashedLines.gapSize = gapSize;
  41259. return dashedLines;
  41260. };
  41261. /**
  41262. * Creates an extruded shape mesh.
  41263. * 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.
  41264. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  41265. *
  41266. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  41267. * 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
  41268. * extruded along the Z axis.
  41269. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  41270. * 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.
  41271. * The parameter `scale` (float, default 1) is the value to scale the shape.
  41272. * 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
  41273. * 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
  41274. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  41275. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41276. * 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).
  41277. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41278. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41279. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41280. */
  41281. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  41282. var path = options.path;
  41283. var shape = options.shape;
  41284. var scale = options.scale || 1;
  41285. var rotation = options.rotation || 0;
  41286. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  41287. var updatable = options.updatable;
  41288. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41289. var instance = options.instance;
  41290. var invertUV = options.invertUV || false;
  41291. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  41292. };
  41293. /**
  41294. * Creates an custom extruded shape mesh.
  41295. * 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.
  41296. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  41297. *
  41298. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  41299. * 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
  41300. * extruded along the Z axis.
  41301. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  41302. * 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
  41303. * and the distance of this point from the begining of the path :
  41304. * ```javascript
  41305. * var rotationFunction = function(i, distance) {
  41306. * // do things
  41307. * return rotationValue; }
  41308. * ```
  41309. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  41310. * 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
  41311. * and the distance of this point from the begining of the path :
  41312. * ```javascript
  41313. * var scaleFunction = function(i, distance) {
  41314. * // do things
  41315. * return scaleValue;}
  41316. * ```
  41317. * It must returns a float value that will be the scale value applied to the shape on each path point.
  41318. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  41319. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  41320. * 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
  41321. * 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
  41322. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  41323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41324. * 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).
  41325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41326. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41328. */
  41329. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  41330. var path = options.path;
  41331. var shape = options.shape;
  41332. var scaleFunction = options.scaleFunction || (function () { return 1; });
  41333. var rotationFunction = options.rotationFunction || (function () { return 0; });
  41334. var ribbonCloseArray = options.ribbonCloseArray || false;
  41335. var ribbonClosePath = options.ribbonClosePath || false;
  41336. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  41337. var updatable = options.updatable;
  41338. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41339. var instance = options.instance;
  41340. var invertUV = options.invertUV || false;
  41341. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  41342. };
  41343. /**
  41344. * Creates lathe mesh.
  41345. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  41346. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  41347. *
  41348. * 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
  41349. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  41350. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  41351. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  41352. * 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.
  41353. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  41354. * 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
  41355. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41356. * 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).
  41357. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41358. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41360. */
  41361. MeshBuilder.CreateLathe = function (name, options, scene) {
  41362. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  41363. var closed = (options.closed === undefined) ? true : options.closed;
  41364. var shape = options.shape;
  41365. var radius = options.radius || 1;
  41366. var tessellation = options.tessellation || 64;
  41367. var updatable = options.updatable;
  41368. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41369. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  41370. var pi2 = Math.PI * 2;
  41371. var paths = new Array();
  41372. var invertUV = options.invertUV || false;
  41373. var i = 0;
  41374. var p = 0;
  41375. var step = pi2 / tessellation * arc;
  41376. var rotated;
  41377. var path = new Array();
  41378. ;
  41379. for (i = 0; i <= tessellation; i++) {
  41380. var path = [];
  41381. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  41382. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  41383. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  41384. }
  41385. for (p = 0; p < shape.length; p++) {
  41386. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  41387. path.push(rotated);
  41388. }
  41389. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  41390. 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));
  41391. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  41392. }
  41393. paths.push(path);
  41394. }
  41395. // lathe ribbon
  41396. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  41397. return lathe;
  41398. };
  41399. /**
  41400. * Creates a plane mesh.
  41401. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  41402. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  41403. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  41404. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  41405. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41406. * 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).
  41407. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41408. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41409. */
  41410. MeshBuilder.CreatePlane = function (name, options, scene) {
  41411. var plane = new BABYLON.Mesh(name, scene);
  41412. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41413. plane.sideOrientation = options.sideOrientation;
  41414. var vertexData = BABYLON.VertexData.CreatePlane(options);
  41415. vertexData.applyToMesh(plane, options.updatable);
  41416. if (options.sourcePlane) {
  41417. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  41418. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  41419. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  41420. plane.rotate(vectorProduct, product);
  41421. }
  41422. return plane;
  41423. };
  41424. /**
  41425. * Creates a ground mesh.
  41426. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  41427. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  41428. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  41429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41430. */
  41431. MeshBuilder.CreateGround = function (name, options, scene) {
  41432. var ground = new BABYLON.GroundMesh(name, scene);
  41433. ground._setReady(false);
  41434. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  41435. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  41436. ground._width = options.width || 1;
  41437. ground._height = options.height || 1;
  41438. ground._maxX = ground._width / 2;
  41439. ground._maxZ = ground._height / 2;
  41440. ground._minX = -ground._maxX;
  41441. ground._minZ = -ground._maxZ;
  41442. var vertexData = BABYLON.VertexData.CreateGround(options);
  41443. vertexData.applyToMesh(ground, options.updatable);
  41444. ground._setReady(true);
  41445. return ground;
  41446. };
  41447. /**
  41448. * Creates a tiled ground mesh.
  41449. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  41450. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  41451. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  41452. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  41453. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  41454. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  41455. * numbers of subdivisions on the ground width and height of each tile.
  41456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41457. */
  41458. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  41459. var tiledGround = new BABYLON.Mesh(name, scene);
  41460. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  41461. vertexData.applyToMesh(tiledGround, options.updatable);
  41462. return tiledGround;
  41463. };
  41464. /**
  41465. * Creates a ground mesh from a height map.
  41466. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  41467. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  41468. * The parameter `url` sets the URL of the height map image resource.
  41469. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  41470. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  41471. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  41472. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  41473. * 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.
  41474. * 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).
  41475. * This function is passed the newly built mesh :
  41476. * ```javascript
  41477. * function(mesh) { // do things
  41478. * return; }
  41479. * ```
  41480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41481. */
  41482. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  41483. var width = options.width || 10.0;
  41484. var height = options.height || 10.0;
  41485. var subdivisions = options.subdivisions || 1 | 0;
  41486. var minHeight = options.minHeight || 0.0;
  41487. var maxHeight = options.maxHeight || 10.0;
  41488. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  41489. var updatable = options.updatable;
  41490. var onReady = options.onReady;
  41491. var ground = new BABYLON.GroundMesh(name, scene);
  41492. ground._subdivisionsX = subdivisions;
  41493. ground._subdivisionsY = subdivisions;
  41494. ground._width = width;
  41495. ground._height = height;
  41496. ground._maxX = ground._width / 2.0;
  41497. ground._maxZ = ground._height / 2.0;
  41498. ground._minX = -ground._maxX;
  41499. ground._minZ = -ground._maxZ;
  41500. ground._setReady(false);
  41501. var onload = function (img) {
  41502. // Getting height map data
  41503. var canvas = document.createElement("canvas");
  41504. var context = canvas.getContext("2d");
  41505. var bufferWidth = img.width;
  41506. var bufferHeight = img.height;
  41507. canvas.width = bufferWidth;
  41508. canvas.height = bufferHeight;
  41509. context.drawImage(img, 0, 0);
  41510. // Create VertexData from map data
  41511. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  41512. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  41513. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  41514. width: width, height: height,
  41515. subdivisions: subdivisions,
  41516. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  41517. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  41518. });
  41519. vertexData.applyToMesh(ground, updatable);
  41520. ground._setReady(true);
  41521. //execute ready callback, if set
  41522. if (onReady) {
  41523. onReady(ground);
  41524. }
  41525. };
  41526. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  41527. return ground;
  41528. };
  41529. /**
  41530. * Creates a polygon mesh.
  41531. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  41532. * 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.
  41533. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41535. * 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).
  41536. * Remember you can only change the shape positions, not their number when updating a polygon.
  41537. */
  41538. MeshBuilder.CreatePolygon = function (name, options, scene) {
  41539. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41540. var shape = options.shape;
  41541. var holes = options.holes || [];
  41542. var depth = options.depth || 0;
  41543. var contours = [];
  41544. var hole = [];
  41545. for (var i = 0; i < shape.length; i++) {
  41546. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  41547. }
  41548. var epsilon = 0.00000001;
  41549. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  41550. contours.pop();
  41551. }
  41552. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  41553. for (var hNb = 0; hNb < holes.length; hNb++) {
  41554. hole = [];
  41555. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  41556. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  41557. }
  41558. polygonTriangulation.addHole(hole);
  41559. }
  41560. var polygon = polygonTriangulation.build(options.updatable, depth);
  41561. polygon.sideOrientation = options.sideOrientation;
  41562. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  41563. vertexData.applyToMesh(polygon, options.updatable);
  41564. return polygon;
  41565. };
  41566. ;
  41567. /**
  41568. * Creates an extruded polygon mesh, with depth in the Y direction.
  41569. * 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).
  41570. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  41571. */
  41572. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  41573. return MeshBuilder.CreatePolygon(name, options, scene);
  41574. };
  41575. ;
  41576. /**
  41577. * Creates a tube mesh.
  41578. * 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.
  41579. *
  41580. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  41581. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  41582. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  41583. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  41584. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  41585. * 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.
  41586. * It must return a radius value (positive float) :
  41587. * ```javascript
  41588. * var radiusFunction = function(i, distance) {
  41589. * // do things
  41590. * return radius; }
  41591. * ```
  41592. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  41593. * 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
  41594. * 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
  41595. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41596. * 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).
  41597. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41598. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41600. */
  41601. MeshBuilder.CreateTube = function (name, options, scene) {
  41602. var path = options.path;
  41603. var radius = options.radius || 1.0;
  41604. var tessellation = options.tessellation || 64 | 0;
  41605. var radiusFunction = options.radiusFunction;
  41606. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  41607. var invertUV = options.invertUV || false;
  41608. var updatable = options.updatable;
  41609. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41610. var instance = options.instance;
  41611. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  41612. // tube geometry
  41613. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  41614. var tangents = path3D.getTangents();
  41615. var normals = path3D.getNormals();
  41616. var distances = path3D.getDistances();
  41617. var pi2 = Math.PI * 2;
  41618. var step = pi2 / tessellation * arc;
  41619. var returnRadius = function () { return radius; };
  41620. var radiusFunctionFinal = radiusFunction || returnRadius;
  41621. var circlePath;
  41622. var rad;
  41623. var normal;
  41624. var rotated;
  41625. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41626. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41627. for (var i = 0; i < path.length; i++) {
  41628. rad = radiusFunctionFinal(i, distances[i]); // current radius
  41629. circlePath = Array(); // current circle array
  41630. normal = normals[i]; // current normal
  41631. for (var t = 0; t < tessellation; t++) {
  41632. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  41633. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  41634. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  41635. rotated.scaleInPlace(rad).addInPlace(path[i]);
  41636. circlePath[t] = rotated;
  41637. }
  41638. circlePaths[index] = circlePath;
  41639. index++;
  41640. }
  41641. // cap
  41642. var capPath = function (nbPoints, pathIndex) {
  41643. var pointCap = Array();
  41644. for (var i = 0; i < nbPoints; i++) {
  41645. pointCap.push(path[pathIndex]);
  41646. }
  41647. return pointCap;
  41648. };
  41649. switch (cap) {
  41650. case BABYLON.Mesh.NO_CAP:
  41651. break;
  41652. case BABYLON.Mesh.CAP_START:
  41653. circlePaths[0] = capPath(tessellation, 0);
  41654. circlePaths[1] = circlePaths[2].slice(0);
  41655. break;
  41656. case BABYLON.Mesh.CAP_END:
  41657. circlePaths[index] = circlePaths[index - 1].slice(0);
  41658. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41659. break;
  41660. case BABYLON.Mesh.CAP_ALL:
  41661. circlePaths[0] = capPath(tessellation, 0);
  41662. circlePaths[1] = circlePaths[2].slice(0);
  41663. circlePaths[index] = circlePaths[index - 1].slice(0);
  41664. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41665. break;
  41666. default:
  41667. break;
  41668. }
  41669. return circlePaths;
  41670. };
  41671. var path3D;
  41672. var pathArray;
  41673. if (instance) {
  41674. var arc = options.arc || instance.arc;
  41675. path3D = (instance.path3D).update(path);
  41676. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  41677. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  41678. instance.path3D = path3D;
  41679. instance.pathArray = pathArray;
  41680. instance.arc = arc;
  41681. return instance;
  41682. }
  41683. // tube creation
  41684. path3D = new BABYLON.Path3D(path);
  41685. var newPathArray = new Array();
  41686. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41687. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  41688. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  41689. tube.pathArray = pathArray;
  41690. tube.path3D = path3D;
  41691. tube.tessellation = tessellation;
  41692. tube.cap = cap;
  41693. tube.arc = options.arc;
  41694. return tube;
  41695. };
  41696. /**
  41697. * Creates a polyhedron mesh.
  41698. *
  41699. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  41700. * 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
  41701. * to choose the wanted type.
  41702. * The parameter `size` (positive float, default 1) sets the polygon size.
  41703. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  41704. * 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`.
  41705. * 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
  41706. * 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)`).
  41707. * 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
  41708. * 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.
  41709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41710. * 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).
  41711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41713. */
  41714. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  41715. var polyhedron = new BABYLON.Mesh(name, scene);
  41716. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41717. polyhedron.sideOrientation = options.sideOrientation;
  41718. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  41719. vertexData.applyToMesh(polyhedron, options.updatable);
  41720. return polyhedron;
  41721. };
  41722. /**
  41723. * Creates a decal mesh.
  41724. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  41725. * 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.
  41726. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  41727. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  41728. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  41729. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  41730. */
  41731. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  41732. var indices = sourceMesh.getIndices();
  41733. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41734. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41735. var position = options.position || BABYLON.Vector3.Zero();
  41736. var normal = options.normal || BABYLON.Vector3.Up();
  41737. var size = options.size || BABYLON.Vector3.One();
  41738. var angle = options.angle || 0;
  41739. // Getting correct rotation
  41740. if (!normal) {
  41741. var target = new BABYLON.Vector3(0, 0, 1);
  41742. var camera = sourceMesh.getScene().activeCamera;
  41743. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  41744. normal = camera.globalPosition.subtract(cameraWorldTarget);
  41745. }
  41746. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  41747. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  41748. var pitch = Math.atan2(normal.y, len);
  41749. // Matrix
  41750. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  41751. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  41752. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  41753. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  41754. var vertexData = new BABYLON.VertexData();
  41755. vertexData.indices = [];
  41756. vertexData.positions = [];
  41757. vertexData.normals = [];
  41758. vertexData.uvs = [];
  41759. var currentVertexDataIndex = 0;
  41760. var extractDecalVector3 = function (indexId) {
  41761. var vertexId = indices[indexId];
  41762. var result = new BABYLON.PositionNormalVertex();
  41763. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  41764. // Send vector to decal local world
  41765. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  41766. // Get normal
  41767. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  41768. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  41769. return result;
  41770. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  41771. var clip = function (vertices, axis) {
  41772. if (vertices.length === 0) {
  41773. return vertices;
  41774. }
  41775. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  41776. var clipVertices = function (v0, v1) {
  41777. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  41778. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  41779. };
  41780. var result = new Array();
  41781. for (var index = 0; index < vertices.length; index += 3) {
  41782. var v1Out;
  41783. var v2Out;
  41784. var v3Out;
  41785. var total = 0;
  41786. var nV1, nV2, nV3, nV4;
  41787. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  41788. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  41789. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  41790. v1Out = d1 > 0;
  41791. v2Out = d2 > 0;
  41792. v3Out = d3 > 0;
  41793. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  41794. switch (total) {
  41795. case 0:
  41796. result.push(vertices[index]);
  41797. result.push(vertices[index + 1]);
  41798. result.push(vertices[index + 2]);
  41799. break;
  41800. case 1:
  41801. if (v1Out) {
  41802. nV1 = vertices[index + 1];
  41803. nV2 = vertices[index + 2];
  41804. nV3 = clipVertices(vertices[index], nV1);
  41805. nV4 = clipVertices(vertices[index], nV2);
  41806. }
  41807. if (v2Out) {
  41808. nV1 = vertices[index];
  41809. nV2 = vertices[index + 2];
  41810. nV3 = clipVertices(vertices[index + 1], nV1);
  41811. nV4 = clipVertices(vertices[index + 1], nV2);
  41812. result.push(nV3);
  41813. result.push(nV2.clone());
  41814. result.push(nV1.clone());
  41815. result.push(nV2.clone());
  41816. result.push(nV3.clone());
  41817. result.push(nV4);
  41818. break;
  41819. }
  41820. if (v3Out) {
  41821. nV1 = vertices[index];
  41822. nV2 = vertices[index + 1];
  41823. nV3 = clipVertices(vertices[index + 2], nV1);
  41824. nV4 = clipVertices(vertices[index + 2], nV2);
  41825. }
  41826. result.push(nV1.clone());
  41827. result.push(nV2.clone());
  41828. result.push(nV3);
  41829. result.push(nV4);
  41830. result.push(nV3.clone());
  41831. result.push(nV2.clone());
  41832. break;
  41833. case 2:
  41834. if (!v1Out) {
  41835. nV1 = vertices[index].clone();
  41836. nV2 = clipVertices(nV1, vertices[index + 1]);
  41837. nV3 = clipVertices(nV1, vertices[index + 2]);
  41838. result.push(nV1);
  41839. result.push(nV2);
  41840. result.push(nV3);
  41841. }
  41842. if (!v2Out) {
  41843. nV1 = vertices[index + 1].clone();
  41844. nV2 = clipVertices(nV1, vertices[index + 2]);
  41845. nV3 = clipVertices(nV1, vertices[index]);
  41846. result.push(nV1);
  41847. result.push(nV2);
  41848. result.push(nV3);
  41849. }
  41850. if (!v3Out) {
  41851. nV1 = vertices[index + 2].clone();
  41852. nV2 = clipVertices(nV1, vertices[index]);
  41853. nV3 = clipVertices(nV1, vertices[index + 1]);
  41854. result.push(nV1);
  41855. result.push(nV2);
  41856. result.push(nV3);
  41857. }
  41858. break;
  41859. case 3:
  41860. break;
  41861. }
  41862. }
  41863. return result;
  41864. };
  41865. for (var index = 0; index < indices.length; index += 3) {
  41866. var faceVertices = new Array();
  41867. faceVertices.push(extractDecalVector3(index));
  41868. faceVertices.push(extractDecalVector3(index + 1));
  41869. faceVertices.push(extractDecalVector3(index + 2));
  41870. // Clip
  41871. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  41872. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  41873. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  41874. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  41875. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  41876. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  41877. if (faceVertices.length === 0) {
  41878. continue;
  41879. }
  41880. // Add UVs and get back to world
  41881. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  41882. var vertex = faceVertices[vIndex];
  41883. //TODO check for Int32Array | Uint32Array | Uint16Array
  41884. vertexData.indices.push(currentVertexDataIndex);
  41885. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  41886. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  41887. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  41888. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  41889. currentVertexDataIndex++;
  41890. }
  41891. }
  41892. // Return mesh
  41893. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  41894. vertexData.applyToMesh(decal);
  41895. decal.position = position.clone();
  41896. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  41897. return decal;
  41898. };
  41899. // Privates
  41900. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  41901. // extrusion geometry
  41902. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  41903. var tangents = path3D.getTangents();
  41904. var normals = path3D.getNormals();
  41905. var binormals = path3D.getBinormals();
  41906. var distances = path3D.getDistances();
  41907. var angle = 0;
  41908. var returnScale = function () { return scale; };
  41909. var returnRotation = function () { return rotation; };
  41910. var rotate = custom ? rotateFunction : returnRotation;
  41911. var scl = custom ? scaleFunction : returnScale;
  41912. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41913. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41914. for (var i = 0; i < curve.length; i++) {
  41915. var shapePath = new Array();
  41916. var angleStep = rotate(i, distances[i]);
  41917. var scaleRatio = scl(i, distances[i]);
  41918. for (var p = 0; p < shape.length; p++) {
  41919. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  41920. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  41921. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  41922. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  41923. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  41924. shapePath[p] = rotated;
  41925. }
  41926. shapePaths[index] = shapePath;
  41927. angle += angleStep;
  41928. index++;
  41929. }
  41930. // cap
  41931. var capPath = function (shapePath) {
  41932. var pointCap = Array();
  41933. var barycenter = BABYLON.Vector3.Zero();
  41934. var i;
  41935. for (i = 0; i < shapePath.length; i++) {
  41936. barycenter.addInPlace(shapePath[i]);
  41937. }
  41938. barycenter.scaleInPlace(1.0 / shapePath.length);
  41939. for (i = 0; i < shapePath.length; i++) {
  41940. pointCap.push(barycenter);
  41941. }
  41942. return pointCap;
  41943. };
  41944. switch (cap) {
  41945. case BABYLON.Mesh.NO_CAP:
  41946. break;
  41947. case BABYLON.Mesh.CAP_START:
  41948. shapePaths[0] = capPath(shapePaths[2]);
  41949. shapePaths[1] = shapePaths[2];
  41950. break;
  41951. case BABYLON.Mesh.CAP_END:
  41952. shapePaths[index] = shapePaths[index - 1];
  41953. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41954. break;
  41955. case BABYLON.Mesh.CAP_ALL:
  41956. shapePaths[0] = capPath(shapePaths[2]);
  41957. shapePaths[1] = shapePaths[2];
  41958. shapePaths[index] = shapePaths[index - 1];
  41959. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41960. break;
  41961. default:
  41962. break;
  41963. }
  41964. return shapePaths;
  41965. };
  41966. var path3D;
  41967. var pathArray;
  41968. if (instance) {
  41969. path3D = (instance.path3D).update(curve);
  41970. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  41971. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  41972. return instance;
  41973. }
  41974. // extruded shape creation
  41975. path3D = new BABYLON.Path3D(curve);
  41976. var newShapePaths = new Array();
  41977. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41978. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  41979. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  41980. extrudedGeneric.pathArray = pathArray;
  41981. extrudedGeneric.path3D = path3D;
  41982. extrudedGeneric.cap = cap;
  41983. return extrudedGeneric;
  41984. };
  41985. return MeshBuilder;
  41986. }());
  41987. BABYLON.MeshBuilder = MeshBuilder;
  41988. })(BABYLON || (BABYLON = {}));
  41989. //# sourceMappingURL=babylon.meshBuilder.js.map
  41990. var BABYLON;
  41991. (function (BABYLON) {
  41992. var AudioEngine = (function () {
  41993. function AudioEngine() {
  41994. this._audioContext = null;
  41995. this._audioContextInitialized = false;
  41996. this.canUseWebAudio = false;
  41997. this.WarnedWebAudioUnsupported = false;
  41998. this.unlocked = false;
  41999. this.isMP3supported = false;
  42000. this.isOGGsupported = false;
  42001. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  42002. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  42003. this.canUseWebAudio = true;
  42004. }
  42005. var audioElem = document.createElement('audio');
  42006. try {
  42007. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  42008. this.isMP3supported = true;
  42009. }
  42010. }
  42011. catch (e) {
  42012. // protect error during capability check.
  42013. }
  42014. try {
  42015. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  42016. this.isOGGsupported = true;
  42017. }
  42018. }
  42019. catch (e) {
  42020. // protect error during capability check.
  42021. }
  42022. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  42023. this._unlockiOSaudio();
  42024. }
  42025. else {
  42026. this.unlocked = true;
  42027. }
  42028. }
  42029. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  42030. get: function () {
  42031. if (!this._audioContextInitialized) {
  42032. this._initializeAudioContext();
  42033. }
  42034. return this._audioContext;
  42035. },
  42036. enumerable: true,
  42037. configurable: true
  42038. });
  42039. AudioEngine.prototype._unlockiOSaudio = function () {
  42040. var _this = this;
  42041. var unlockaudio = function () {
  42042. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  42043. var source = _this.audioContext.createBufferSource();
  42044. source.buffer = buffer;
  42045. source.connect(_this.audioContext.destination);
  42046. source.start(0);
  42047. setTimeout(function () {
  42048. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  42049. _this.unlocked = true;
  42050. window.removeEventListener('touchend', unlockaudio, false);
  42051. if (_this.onAudioUnlocked) {
  42052. _this.onAudioUnlocked();
  42053. }
  42054. }
  42055. }, 0);
  42056. };
  42057. window.addEventListener('touchend', unlockaudio, false);
  42058. };
  42059. AudioEngine.prototype._initializeAudioContext = function () {
  42060. try {
  42061. if (this.canUseWebAudio) {
  42062. this._audioContext = new AudioContext();
  42063. // create a global volume gain node
  42064. this.masterGain = this._audioContext.createGain();
  42065. this.masterGain.gain.value = 1;
  42066. this.masterGain.connect(this._audioContext.destination);
  42067. this._audioContextInitialized = true;
  42068. }
  42069. }
  42070. catch (e) {
  42071. this.canUseWebAudio = false;
  42072. BABYLON.Tools.Error("Web Audio: " + e.message);
  42073. }
  42074. };
  42075. AudioEngine.prototype.dispose = function () {
  42076. if (this.canUseWebAudio && this._audioContextInitialized) {
  42077. if (this._connectedAnalyser) {
  42078. this._connectedAnalyser.stopDebugCanvas();
  42079. this._connectedAnalyser.dispose();
  42080. this.masterGain.disconnect();
  42081. this.masterGain.connect(this._audioContext.destination);
  42082. this._connectedAnalyser = null;
  42083. }
  42084. this.masterGain.gain.value = 1;
  42085. }
  42086. this.WarnedWebAudioUnsupported = false;
  42087. };
  42088. AudioEngine.prototype.getGlobalVolume = function () {
  42089. if (this.canUseWebAudio && this._audioContextInitialized) {
  42090. return this.masterGain.gain.value;
  42091. }
  42092. else {
  42093. return -1;
  42094. }
  42095. };
  42096. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  42097. if (this.canUseWebAudio && this._audioContextInitialized) {
  42098. this.masterGain.gain.value = newVolume;
  42099. }
  42100. };
  42101. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  42102. if (this._connectedAnalyser) {
  42103. this._connectedAnalyser.stopDebugCanvas();
  42104. }
  42105. if (this.canUseWebAudio && this._audioContextInitialized) {
  42106. this._connectedAnalyser = analyser;
  42107. this.masterGain.disconnect();
  42108. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  42109. }
  42110. };
  42111. return AudioEngine;
  42112. }());
  42113. BABYLON.AudioEngine = AudioEngine;
  42114. })(BABYLON || (BABYLON = {}));
  42115. //# sourceMappingURL=babylon.audioEngine.js.map
  42116. var BABYLON;
  42117. (function (BABYLON) {
  42118. var Sound = (function () {
  42119. /**
  42120. * Create a sound and attach it to a scene
  42121. * @param name Name of your sound
  42122. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  42123. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  42124. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  42125. */
  42126. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  42127. var _this = this;
  42128. this.autoplay = false;
  42129. this.loop = false;
  42130. this.useCustomAttenuation = false;
  42131. this.spatialSound = false;
  42132. this.refDistance = 1;
  42133. this.rolloffFactor = 1;
  42134. this.maxDistance = 100;
  42135. this.distanceModel = "linear";
  42136. this._panningModel = "equalpower";
  42137. this._playbackRate = 1;
  42138. this._streaming = false;
  42139. this._startTime = 0;
  42140. this._startOffset = 0;
  42141. this._position = BABYLON.Vector3.Zero();
  42142. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  42143. this._volume = 1;
  42144. this._isLoaded = false;
  42145. this._isReadyToPlay = false;
  42146. this.isPlaying = false;
  42147. this.isPaused = false;
  42148. this._isDirectional = false;
  42149. // Used if you'd like to create a directional sound.
  42150. // If not set, the sound will be omnidirectional
  42151. this._coneInnerAngle = 360;
  42152. this._coneOuterAngle = 360;
  42153. this._coneOuterGain = 0;
  42154. this._isOutputConnected = false;
  42155. this._urlType = "Unknown";
  42156. this.name = name;
  42157. this._scene = scene;
  42158. this._readyToPlayCallback = readyToPlayCallback;
  42159. // Default custom attenuation function is a linear attenuation
  42160. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  42161. if (currentDistance < maxDistance) {
  42162. return currentVolume * (1 - currentDistance / maxDistance);
  42163. }
  42164. else {
  42165. return 0;
  42166. }
  42167. };
  42168. if (options) {
  42169. this.autoplay = options.autoplay || false;
  42170. this.loop = options.loop || false;
  42171. // if volume === 0, we need another way to check this option
  42172. if (options.volume !== undefined) {
  42173. this._volume = options.volume;
  42174. }
  42175. this.spatialSound = options.spatialSound || false;
  42176. this.maxDistance = options.maxDistance || 100;
  42177. this.useCustomAttenuation = options.useCustomAttenuation || false;
  42178. this.rolloffFactor = options.rolloffFactor || 1;
  42179. this.refDistance = options.refDistance || 1;
  42180. this.distanceModel = options.distanceModel || "linear";
  42181. this._playbackRate = options.playbackRate || 1;
  42182. this._streaming = options.streaming || false;
  42183. }
  42184. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42185. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  42186. this._soundGain.gain.value = this._volume;
  42187. this._inputAudioNode = this._soundGain;
  42188. this._ouputAudioNode = this._soundGain;
  42189. if (this.spatialSound) {
  42190. this._createSpatialParameters();
  42191. }
  42192. this._scene.mainSoundTrack.AddSound(this);
  42193. var validParameter = true;
  42194. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  42195. if (urlOrArrayBuffer) {
  42196. if (typeof (urlOrArrayBuffer) === "string")
  42197. this._urlType = "String";
  42198. if (Array.isArray(urlOrArrayBuffer))
  42199. this._urlType = "Array";
  42200. if (urlOrArrayBuffer instanceof ArrayBuffer)
  42201. this._urlType = "ArrayBuffer";
  42202. var urls = [];
  42203. var codecSupportedFound = false;
  42204. switch (this._urlType) {
  42205. case "ArrayBuffer":
  42206. if (urlOrArrayBuffer.byteLength > 0) {
  42207. codecSupportedFound = true;
  42208. this._soundLoaded(urlOrArrayBuffer);
  42209. }
  42210. break;
  42211. case "String":
  42212. urls.push(urlOrArrayBuffer);
  42213. case "Array":
  42214. if (urls.length === 0)
  42215. urls = urlOrArrayBuffer;
  42216. // If we found a supported format, we load it immediately and stop the loop
  42217. for (var i = 0; i < urls.length; i++) {
  42218. var url = urls[i];
  42219. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  42220. codecSupportedFound = true;
  42221. }
  42222. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  42223. codecSupportedFound = true;
  42224. }
  42225. if (url.indexOf(".wav", url.length - 4) !== -1) {
  42226. codecSupportedFound = true;
  42227. }
  42228. if (codecSupportedFound) {
  42229. // Loading sound using XHR2
  42230. if (!this._streaming) {
  42231. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  42232. }
  42233. else {
  42234. this._htmlAudioElement = new Audio(url);
  42235. this._htmlAudioElement.controls = false;
  42236. this._htmlAudioElement.loop = this.loop;
  42237. this._htmlAudioElement.crossOrigin = "anonymous";
  42238. this._htmlAudioElement.preload = "auto";
  42239. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  42240. _this._isReadyToPlay = true;
  42241. if (_this.autoplay) {
  42242. _this.play();
  42243. }
  42244. if (_this._readyToPlayCallback) {
  42245. _this._readyToPlayCallback();
  42246. }
  42247. });
  42248. document.body.appendChild(this._htmlAudioElement);
  42249. }
  42250. break;
  42251. }
  42252. }
  42253. break;
  42254. default:
  42255. validParameter = false;
  42256. break;
  42257. }
  42258. if (!validParameter) {
  42259. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  42260. }
  42261. else {
  42262. if (!codecSupportedFound) {
  42263. this._isReadyToPlay = true;
  42264. // Simulating a ready to play event to avoid breaking code path
  42265. if (this._readyToPlayCallback) {
  42266. window.setTimeout(function () {
  42267. _this._readyToPlayCallback();
  42268. }, 1000);
  42269. }
  42270. }
  42271. }
  42272. }
  42273. }
  42274. else {
  42275. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  42276. this._scene.mainSoundTrack.AddSound(this);
  42277. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  42278. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  42279. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  42280. }
  42281. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  42282. if (this._readyToPlayCallback) {
  42283. window.setTimeout(function () {
  42284. _this._readyToPlayCallback();
  42285. }, 1000);
  42286. }
  42287. }
  42288. }
  42289. Sound.prototype.dispose = function () {
  42290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  42291. if (this.isPlaying) {
  42292. this.stop();
  42293. }
  42294. this._isReadyToPlay = false;
  42295. if (this.soundTrackId === -1) {
  42296. this._scene.mainSoundTrack.RemoveSound(this);
  42297. }
  42298. else {
  42299. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  42300. }
  42301. if (this._soundGain) {
  42302. this._soundGain.disconnect();
  42303. this._soundGain = null;
  42304. }
  42305. if (this._soundPanner) {
  42306. this._soundPanner.disconnect();
  42307. this._soundPanner = null;
  42308. }
  42309. if (this._soundSource) {
  42310. this._soundSource.disconnect();
  42311. this._soundSource = null;
  42312. }
  42313. this._audioBuffer = null;
  42314. if (this._htmlAudioElement) {
  42315. this._htmlAudioElement.pause();
  42316. this._htmlAudioElement.src = "";
  42317. document.body.removeChild(this._htmlAudioElement);
  42318. }
  42319. if (this._connectedMesh) {
  42320. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42321. this._connectedMesh = null;
  42322. }
  42323. }
  42324. };
  42325. Sound.prototype.isReady = function () {
  42326. return this._isReadyToPlay;
  42327. };
  42328. Sound.prototype._soundLoaded = function (audioData) {
  42329. var _this = this;
  42330. this._isLoaded = true;
  42331. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  42332. _this._audioBuffer = buffer;
  42333. _this._isReadyToPlay = true;
  42334. if (_this.autoplay) {
  42335. _this.play();
  42336. }
  42337. if (_this._readyToPlayCallback) {
  42338. _this._readyToPlayCallback();
  42339. }
  42340. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  42341. };
  42342. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  42343. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42344. this._audioBuffer = audioBuffer;
  42345. this._isReadyToPlay = true;
  42346. }
  42347. };
  42348. Sound.prototype.updateOptions = function (options) {
  42349. if (options) {
  42350. this.loop = options.loop || this.loop;
  42351. this.maxDistance = options.maxDistance || this.maxDistance;
  42352. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  42353. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  42354. this.refDistance = options.refDistance || this.refDistance;
  42355. this.distanceModel = options.distanceModel || this.distanceModel;
  42356. this._playbackRate = options.playbackRate || this._playbackRate;
  42357. this._updateSpatialParameters();
  42358. if (this.isPlaying) {
  42359. if (this._streaming) {
  42360. this._htmlAudioElement.playbackRate = this._playbackRate;
  42361. }
  42362. else {
  42363. this._soundSource.playbackRate.value = this._playbackRate;
  42364. }
  42365. }
  42366. }
  42367. };
  42368. Sound.prototype._createSpatialParameters = function () {
  42369. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42370. if (this._scene.headphone) {
  42371. this._panningModel = "HRTF";
  42372. }
  42373. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  42374. this._updateSpatialParameters();
  42375. this._soundPanner.connect(this._ouputAudioNode);
  42376. this._inputAudioNode = this._soundPanner;
  42377. }
  42378. };
  42379. Sound.prototype._updateSpatialParameters = function () {
  42380. if (this.spatialSound) {
  42381. if (this.useCustomAttenuation) {
  42382. // Tricks to disable in a way embedded Web Audio attenuation
  42383. this._soundPanner.distanceModel = "linear";
  42384. this._soundPanner.maxDistance = Number.MAX_VALUE;
  42385. this._soundPanner.refDistance = 1;
  42386. this._soundPanner.rolloffFactor = 1;
  42387. this._soundPanner.panningModel = this._panningModel;
  42388. }
  42389. else {
  42390. this._soundPanner.distanceModel = this.distanceModel;
  42391. this._soundPanner.maxDistance = this.maxDistance;
  42392. this._soundPanner.refDistance = this.refDistance;
  42393. this._soundPanner.rolloffFactor = this.rolloffFactor;
  42394. this._soundPanner.panningModel = this._panningModel;
  42395. }
  42396. }
  42397. };
  42398. Sound.prototype.switchPanningModelToHRTF = function () {
  42399. this._panningModel = "HRTF";
  42400. this._switchPanningModel();
  42401. };
  42402. Sound.prototype.switchPanningModelToEqualPower = function () {
  42403. this._panningModel = "equalpower";
  42404. this._switchPanningModel();
  42405. };
  42406. Sound.prototype._switchPanningModel = function () {
  42407. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42408. this._soundPanner.panningModel = this._panningModel;
  42409. }
  42410. };
  42411. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  42412. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42413. if (this._isOutputConnected) {
  42414. this._ouputAudioNode.disconnect();
  42415. }
  42416. this._ouputAudioNode.connect(soundTrackAudioNode);
  42417. this._isOutputConnected = true;
  42418. }
  42419. };
  42420. /**
  42421. * Transform this sound into a directional source
  42422. * @param coneInnerAngle Size of the inner cone in degree
  42423. * @param coneOuterAngle Size of the outer cone in degree
  42424. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  42425. */
  42426. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  42427. if (coneOuterAngle < coneInnerAngle) {
  42428. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  42429. return;
  42430. }
  42431. this._coneInnerAngle = coneInnerAngle;
  42432. this._coneOuterAngle = coneOuterAngle;
  42433. this._coneOuterGain = coneOuterGain;
  42434. this._isDirectional = true;
  42435. if (this.isPlaying && this.loop) {
  42436. this.stop();
  42437. this.play();
  42438. }
  42439. };
  42440. Sound.prototype.setPosition = function (newPosition) {
  42441. this._position = newPosition;
  42442. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42443. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42444. }
  42445. };
  42446. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  42447. this._localDirection = newLocalDirection;
  42448. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  42449. this._updateDirection();
  42450. }
  42451. };
  42452. Sound.prototype._updateDirection = function () {
  42453. var mat = this._connectedMesh.getWorldMatrix();
  42454. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  42455. direction.normalize();
  42456. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  42457. };
  42458. Sound.prototype.updateDistanceFromListener = function () {
  42459. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  42460. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  42461. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  42462. }
  42463. };
  42464. Sound.prototype.setAttenuationFunction = function (callback) {
  42465. this._customAttenuationFunction = callback;
  42466. };
  42467. /**
  42468. * Play the sound
  42469. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  42470. * @param offset (optional) Start the sound setting it at a specific time
  42471. */
  42472. Sound.prototype.play = function (time, offset) {
  42473. var _this = this;
  42474. if (this._isReadyToPlay && this._scene.audioEnabled) {
  42475. try {
  42476. if (this._startOffset < 0) {
  42477. time = -this._startOffset;
  42478. this._startOffset = 0;
  42479. }
  42480. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42481. if (!this._soundSource || !this._streamingSource) {
  42482. if (this.spatialSound) {
  42483. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42484. if (this._isDirectional) {
  42485. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  42486. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  42487. this._soundPanner.coneOuterGain = this._coneOuterGain;
  42488. if (this._connectedMesh) {
  42489. this._updateDirection();
  42490. }
  42491. else {
  42492. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  42493. }
  42494. }
  42495. }
  42496. }
  42497. if (this._streaming) {
  42498. if (!this._streamingSource) {
  42499. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  42500. this._htmlAudioElement.onended = function () { _this._onended(); };
  42501. this._htmlAudioElement.playbackRate = this._playbackRate;
  42502. }
  42503. this._streamingSource.disconnect();
  42504. this._streamingSource.connect(this._inputAudioNode);
  42505. this._htmlAudioElement.play();
  42506. }
  42507. else {
  42508. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  42509. this._soundSource.buffer = this._audioBuffer;
  42510. this._soundSource.connect(this._inputAudioNode);
  42511. this._soundSource.loop = this.loop;
  42512. this._soundSource.playbackRate.value = this._playbackRate;
  42513. this._soundSource.onended = function () { _this._onended(); };
  42514. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  42515. }
  42516. this._startTime = startTime;
  42517. this.isPlaying = true;
  42518. this.isPaused = false;
  42519. }
  42520. catch (ex) {
  42521. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  42522. }
  42523. }
  42524. };
  42525. Sound.prototype._onended = function () {
  42526. this.isPlaying = false;
  42527. if (this.onended) {
  42528. this.onended();
  42529. }
  42530. };
  42531. /**
  42532. * Stop the sound
  42533. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  42534. */
  42535. Sound.prototype.stop = function (time) {
  42536. if (this.isPlaying) {
  42537. if (this._streaming) {
  42538. this._htmlAudioElement.pause();
  42539. // Test needed for Firefox or it will generate an Invalid State Error
  42540. if (this._htmlAudioElement.currentTime > 0) {
  42541. this._htmlAudioElement.currentTime = 0;
  42542. }
  42543. }
  42544. else {
  42545. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42546. this._soundSource.stop(stopTime);
  42547. this._soundSource.onended = null;
  42548. if (!this.isPaused) {
  42549. this._startOffset = 0;
  42550. }
  42551. }
  42552. this.isPlaying = false;
  42553. }
  42554. };
  42555. Sound.prototype.pause = function () {
  42556. if (this.isPlaying) {
  42557. this.isPaused = true;
  42558. if (this._streaming) {
  42559. this._htmlAudioElement.pause();
  42560. }
  42561. else {
  42562. this.stop(0);
  42563. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  42564. }
  42565. }
  42566. };
  42567. Sound.prototype.setVolume = function (newVolume, time) {
  42568. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42569. if (time) {
  42570. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  42571. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  42572. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  42573. }
  42574. else {
  42575. this._soundGain.gain.value = newVolume;
  42576. }
  42577. }
  42578. this._volume = newVolume;
  42579. };
  42580. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  42581. this._playbackRate = newPlaybackRate;
  42582. if (this.isPlaying) {
  42583. if (this._streaming) {
  42584. this._htmlAudioElement.playbackRate = this._playbackRate;
  42585. }
  42586. else {
  42587. this._soundSource.playbackRate.value = this._playbackRate;
  42588. }
  42589. }
  42590. };
  42591. Sound.prototype.getVolume = function () {
  42592. return this._volume;
  42593. };
  42594. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  42595. var _this = this;
  42596. if (this._connectedMesh) {
  42597. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42598. this._registerFunc = null;
  42599. }
  42600. this._connectedMesh = meshToConnectTo;
  42601. if (!this.spatialSound) {
  42602. this.spatialSound = true;
  42603. this._createSpatialParameters();
  42604. if (this.isPlaying && this.loop) {
  42605. this.stop();
  42606. this.play();
  42607. }
  42608. }
  42609. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  42610. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  42611. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  42612. };
  42613. Sound.prototype.detachFromMesh = function () {
  42614. if (this._connectedMesh) {
  42615. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42616. this._registerFunc = null;
  42617. this._connectedMesh = null;
  42618. }
  42619. };
  42620. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  42621. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  42622. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  42623. this._updateDirection();
  42624. }
  42625. };
  42626. Sound.prototype.clone = function () {
  42627. var _this = this;
  42628. if (!this._streaming) {
  42629. var setBufferAndRun = function () {
  42630. if (_this._isReadyToPlay) {
  42631. clonedSound._audioBuffer = _this.getAudioBuffer();
  42632. clonedSound._isReadyToPlay = true;
  42633. if (clonedSound.autoplay) {
  42634. clonedSound.play();
  42635. }
  42636. }
  42637. else {
  42638. window.setTimeout(setBufferAndRun, 300);
  42639. }
  42640. };
  42641. var currentOptions = {
  42642. autoplay: this.autoplay, loop: this.loop,
  42643. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  42644. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  42645. refDistance: this.refDistance, distanceModel: this.distanceModel
  42646. };
  42647. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  42648. if (this.useCustomAttenuation) {
  42649. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  42650. }
  42651. clonedSound.setPosition(this._position);
  42652. clonedSound.setPlaybackRate(this._playbackRate);
  42653. setBufferAndRun();
  42654. return clonedSound;
  42655. }
  42656. else {
  42657. return null;
  42658. }
  42659. };
  42660. Sound.prototype.getAudioBuffer = function () {
  42661. return this._audioBuffer;
  42662. };
  42663. Sound.prototype.serialize = function () {
  42664. var serializationObject = {
  42665. name: this.name,
  42666. url: this.name,
  42667. autoplay: this.autoplay,
  42668. loop: this.loop,
  42669. volume: this._volume,
  42670. spatialSound: this.spatialSound,
  42671. maxDistance: this.maxDistance,
  42672. rolloffFactor: this.rolloffFactor,
  42673. refDistance: this.refDistance,
  42674. distanceModel: this.distanceModel,
  42675. playbackRate: this._playbackRate,
  42676. panningModel: this._panningModel,
  42677. soundTrackId: this.soundTrackId
  42678. };
  42679. if (this.spatialSound) {
  42680. if (this._connectedMesh)
  42681. serializationObject.connectedMeshId = this._connectedMesh.id;
  42682. serializationObject.position = this._position.asArray();
  42683. serializationObject.refDistance = this.refDistance;
  42684. serializationObject.distanceModel = this.distanceModel;
  42685. serializationObject.isDirectional = this._isDirectional;
  42686. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  42687. serializationObject.coneInnerAngle = this._coneInnerAngle;
  42688. serializationObject.coneOuterAngle = this._coneOuterAngle;
  42689. serializationObject.coneOuterGain = this._coneOuterGain;
  42690. }
  42691. return serializationObject;
  42692. };
  42693. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  42694. var soundName = parsedSound.name;
  42695. var soundUrl;
  42696. if (parsedSound.url) {
  42697. soundUrl = rootUrl + parsedSound.url;
  42698. }
  42699. else {
  42700. soundUrl = rootUrl + soundName;
  42701. }
  42702. var options = {
  42703. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  42704. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  42705. rolloffFactor: parsedSound.rolloffFactor,
  42706. refDistance: parsedSound.refDistance,
  42707. distanceModel: parsedSound.distanceModel,
  42708. playbackRate: parsedSound.playbackRate
  42709. };
  42710. var newSound;
  42711. if (!sourceSound) {
  42712. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  42713. scene._addPendingData(newSound);
  42714. }
  42715. else {
  42716. var setBufferAndRun = function () {
  42717. if (sourceSound._isReadyToPlay) {
  42718. newSound._audioBuffer = sourceSound.getAudioBuffer();
  42719. newSound._isReadyToPlay = true;
  42720. if (newSound.autoplay) {
  42721. newSound.play();
  42722. }
  42723. }
  42724. else {
  42725. window.setTimeout(setBufferAndRun, 300);
  42726. }
  42727. };
  42728. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  42729. setBufferAndRun();
  42730. }
  42731. if (parsedSound.position) {
  42732. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  42733. newSound.setPosition(soundPosition);
  42734. }
  42735. if (parsedSound.isDirectional) {
  42736. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  42737. if (parsedSound.localDirectionToMesh) {
  42738. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  42739. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  42740. }
  42741. }
  42742. if (parsedSound.connectedMeshId) {
  42743. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  42744. if (connectedMesh) {
  42745. newSound.attachToMesh(connectedMesh);
  42746. }
  42747. }
  42748. return newSound;
  42749. };
  42750. return Sound;
  42751. }());
  42752. BABYLON.Sound = Sound;
  42753. })(BABYLON || (BABYLON = {}));
  42754. //# sourceMappingURL=babylon.sound.js.map
  42755. var BABYLON;
  42756. (function (BABYLON) {
  42757. var SoundTrack = (function () {
  42758. function SoundTrack(scene, options) {
  42759. this.id = -1;
  42760. this._isMainTrack = false;
  42761. this._isInitialized = false;
  42762. this._scene = scene;
  42763. this.soundCollection = new Array();
  42764. this._options = options;
  42765. if (!this._isMainTrack) {
  42766. this._scene.soundTracks.push(this);
  42767. this.id = this._scene.soundTracks.length - 1;
  42768. }
  42769. }
  42770. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  42771. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42772. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  42773. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  42774. if (this._options) {
  42775. if (this._options.volume) {
  42776. this._outputAudioNode.gain.value = this._options.volume;
  42777. }
  42778. if (this._options.mainTrack) {
  42779. this._isMainTrack = this._options.mainTrack;
  42780. }
  42781. }
  42782. this._isInitialized = true;
  42783. }
  42784. };
  42785. SoundTrack.prototype.dispose = function () {
  42786. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42787. if (this._connectedAnalyser) {
  42788. this._connectedAnalyser.stopDebugCanvas();
  42789. }
  42790. while (this.soundCollection.length) {
  42791. this.soundCollection[0].dispose();
  42792. }
  42793. if (this._outputAudioNode) {
  42794. this._outputAudioNode.disconnect();
  42795. }
  42796. this._outputAudioNode = null;
  42797. }
  42798. };
  42799. SoundTrack.prototype.AddSound = function (sound) {
  42800. if (!this._isInitialized) {
  42801. this._initializeSoundTrackAudioGraph();
  42802. }
  42803. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42804. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  42805. }
  42806. if (sound.soundTrackId) {
  42807. if (sound.soundTrackId === -1) {
  42808. this._scene.mainSoundTrack.RemoveSound(sound);
  42809. }
  42810. else {
  42811. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  42812. }
  42813. }
  42814. this.soundCollection.push(sound);
  42815. sound.soundTrackId = this.id;
  42816. };
  42817. SoundTrack.prototype.RemoveSound = function (sound) {
  42818. var index = this.soundCollection.indexOf(sound);
  42819. if (index !== -1) {
  42820. this.soundCollection.splice(index, 1);
  42821. }
  42822. };
  42823. SoundTrack.prototype.setVolume = function (newVolume) {
  42824. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42825. this._outputAudioNode.gain.value = newVolume;
  42826. }
  42827. };
  42828. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  42829. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42830. for (var i = 0; i < this.soundCollection.length; i++) {
  42831. this.soundCollection[i].switchPanningModelToHRTF();
  42832. }
  42833. }
  42834. };
  42835. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  42836. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42837. for (var i = 0; i < this.soundCollection.length; i++) {
  42838. this.soundCollection[i].switchPanningModelToEqualPower();
  42839. }
  42840. }
  42841. };
  42842. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  42843. if (this._connectedAnalyser) {
  42844. this._connectedAnalyser.stopDebugCanvas();
  42845. }
  42846. this._connectedAnalyser = analyser;
  42847. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42848. this._outputAudioNode.disconnect();
  42849. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  42850. }
  42851. };
  42852. return SoundTrack;
  42853. }());
  42854. BABYLON.SoundTrack = SoundTrack;
  42855. })(BABYLON || (BABYLON = {}));
  42856. //# sourceMappingURL=babylon.soundtrack.js.map
  42857. var BABYLON;
  42858. (function (BABYLON) {
  42859. var Analyser = (function () {
  42860. function Analyser(scene) {
  42861. this.SMOOTHING = 0.75;
  42862. this.FFT_SIZE = 512;
  42863. this.BARGRAPHAMPLITUDE = 256;
  42864. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  42865. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  42866. this._scene = scene;
  42867. this._audioEngine = BABYLON.Engine.audioEngine;
  42868. if (this._audioEngine.canUseWebAudio) {
  42869. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  42870. this._webAudioAnalyser.minDecibels = -140;
  42871. this._webAudioAnalyser.maxDecibels = 0;
  42872. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42873. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42874. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  42875. }
  42876. }
  42877. Analyser.prototype.getFrequencyBinCount = function () {
  42878. if (this._audioEngine.canUseWebAudio) {
  42879. return this._webAudioAnalyser.frequencyBinCount;
  42880. }
  42881. else {
  42882. return 0;
  42883. }
  42884. };
  42885. Analyser.prototype.getByteFrequencyData = function () {
  42886. if (this._audioEngine.canUseWebAudio) {
  42887. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42888. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42889. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  42890. }
  42891. return this._byteFreqs;
  42892. };
  42893. Analyser.prototype.getByteTimeDomainData = function () {
  42894. if (this._audioEngine.canUseWebAudio) {
  42895. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42896. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42897. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  42898. }
  42899. return this._byteTime;
  42900. };
  42901. Analyser.prototype.getFloatFrequencyData = function () {
  42902. if (this._audioEngine.canUseWebAudio) {
  42903. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42904. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42905. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  42906. }
  42907. return this._floatFreqs;
  42908. };
  42909. Analyser.prototype.drawDebugCanvas = function () {
  42910. var _this = this;
  42911. if (this._audioEngine.canUseWebAudio) {
  42912. if (!this._debugCanvas) {
  42913. this._debugCanvas = document.createElement("canvas");
  42914. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  42915. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  42916. this._debugCanvas.style.position = "absolute";
  42917. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  42918. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  42919. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  42920. document.body.appendChild(this._debugCanvas);
  42921. this._registerFunc = function () {
  42922. _this.drawDebugCanvas();
  42923. };
  42924. this._scene.registerBeforeRender(this._registerFunc);
  42925. }
  42926. if (this._registerFunc) {
  42927. var workingArray = this.getByteFrequencyData();
  42928. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  42929. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  42930. // Draw the frequency domain chart.
  42931. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  42932. var value = workingArray[i];
  42933. var percent = value / this.BARGRAPHAMPLITUDE;
  42934. var height = this.DEBUGCANVASSIZE.height * percent;
  42935. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  42936. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  42937. var hue = i / this.getFrequencyBinCount() * 360;
  42938. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  42939. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  42940. }
  42941. }
  42942. }
  42943. };
  42944. Analyser.prototype.stopDebugCanvas = function () {
  42945. if (this._debugCanvas) {
  42946. this._scene.unregisterBeforeRender(this._registerFunc);
  42947. this._registerFunc = null;
  42948. document.body.removeChild(this._debugCanvas);
  42949. this._debugCanvas = null;
  42950. this._debugCanvasContext = null;
  42951. }
  42952. };
  42953. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  42954. if (this._audioEngine.canUseWebAudio) {
  42955. inputAudioNode.connect(this._webAudioAnalyser);
  42956. this._webAudioAnalyser.connect(outputAudioNode);
  42957. }
  42958. };
  42959. Analyser.prototype.dispose = function () {
  42960. if (this._audioEngine.canUseWebAudio) {
  42961. this._webAudioAnalyser.disconnect();
  42962. }
  42963. };
  42964. return Analyser;
  42965. }());
  42966. BABYLON.Analyser = Analyser;
  42967. })(BABYLON || (BABYLON = {}));
  42968. //# sourceMappingURL=babylon.analyser.js.map
  42969. var BABYLON;
  42970. (function (BABYLON) {
  42971. var CubeTexture = (function (_super) {
  42972. __extends(CubeTexture, _super);
  42973. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  42974. if (onLoad === void 0) { onLoad = null; }
  42975. if (onError === void 0) { onError = null; }
  42976. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  42977. var _this = _super.call(this, scene) || this;
  42978. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42979. _this.name = rootUrl;
  42980. _this.url = rootUrl;
  42981. _this._noMipmap = noMipmap;
  42982. _this.hasAlpha = false;
  42983. _this._format = format;
  42984. if (!rootUrl && !files) {
  42985. return _this;
  42986. }
  42987. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  42988. if (!files) {
  42989. if (!extensions) {
  42990. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  42991. }
  42992. files = [];
  42993. for (var index = 0; index < extensions.length; index++) {
  42994. files.push(rootUrl + extensions[index]);
  42995. }
  42996. _this._extensions = extensions;
  42997. }
  42998. _this._files = files;
  42999. if (!_this._texture) {
  43000. if (!scene.useDelayedTextureLoading) {
  43001. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  43002. }
  43003. else {
  43004. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43005. }
  43006. }
  43007. else if (onLoad) {
  43008. if (_this._texture.isReady) {
  43009. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  43010. }
  43011. else {
  43012. _this._texture.onLoadedCallbacks.push(onLoad);
  43013. }
  43014. }
  43015. _this.isCube = true;
  43016. _this._textureMatrix = BABYLON.Matrix.Identity();
  43017. return _this;
  43018. }
  43019. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  43020. return new CubeTexture("", scene, null, noMipmap, files);
  43021. };
  43022. // Methods
  43023. CubeTexture.prototype.delayLoad = function () {
  43024. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  43025. return;
  43026. }
  43027. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  43028. this._texture = this._getFromCache(this.url, this._noMipmap);
  43029. if (!this._texture) {
  43030. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  43031. }
  43032. };
  43033. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  43034. return this._textureMatrix;
  43035. };
  43036. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  43037. var texture = BABYLON.SerializationHelper.Parse(function () {
  43038. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  43039. }, parsedTexture, scene);
  43040. // Animations
  43041. if (parsedTexture.animations) {
  43042. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  43043. var parsedAnimation = parsedTexture.animations[animationIndex];
  43044. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  43045. }
  43046. }
  43047. return texture;
  43048. };
  43049. CubeTexture.prototype.clone = function () {
  43050. var _this = this;
  43051. return BABYLON.SerializationHelper.Clone(function () {
  43052. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  43053. }, this);
  43054. };
  43055. return CubeTexture;
  43056. }(BABYLON.BaseTexture));
  43057. BABYLON.CubeTexture = CubeTexture;
  43058. })(BABYLON || (BABYLON = {}));
  43059. //# sourceMappingURL=babylon.cubeTexture.js.map
  43060. var BABYLON;
  43061. (function (BABYLON) {
  43062. var RenderTargetTexture = (function (_super) {
  43063. __extends(RenderTargetTexture, _super);
  43064. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  43065. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  43066. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43067. if (isCube === void 0) { isCube = false; }
  43068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43069. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  43070. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  43071. if (isMulti === void 0) { isMulti = false; }
  43072. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  43073. _this.isCube = isCube;
  43074. /**
  43075. * Use this list to define the list of mesh you want to render.
  43076. */
  43077. _this.renderList = new Array();
  43078. _this.renderParticles = true;
  43079. _this.renderSprites = false;
  43080. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  43081. // Events
  43082. /**
  43083. * An event triggered when the texture is unbind.
  43084. * @type {BABYLON.Observable}
  43085. */
  43086. _this.onAfterUnbindObservable = new BABYLON.Observable();
  43087. /**
  43088. * An event triggered before rendering the texture
  43089. * @type {BABYLON.Observable}
  43090. */
  43091. _this.onBeforeRenderObservable = new BABYLON.Observable();
  43092. /**
  43093. * An event triggered after rendering the texture
  43094. * @type {BABYLON.Observable}
  43095. */
  43096. _this.onAfterRenderObservable = new BABYLON.Observable();
  43097. /**
  43098. * An event triggered after the texture clear
  43099. * @type {BABYLON.Observable}
  43100. */
  43101. _this.onClearObservable = new BABYLON.Observable();
  43102. _this._currentRefreshId = -1;
  43103. _this._refreshRate = 1;
  43104. _this._samples = 1;
  43105. scene = _this.getScene();
  43106. _this.name = name;
  43107. _this.isRenderTarget = true;
  43108. _this._size = size;
  43109. _this._generateMipMaps = generateMipMaps;
  43110. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  43111. // Rendering groups
  43112. _this._renderingManager = new BABYLON.RenderingManager(scene);
  43113. if (isMulti) {
  43114. return _this;
  43115. }
  43116. _this._renderTargetOptions = {
  43117. generateMipMaps: generateMipMaps,
  43118. type: type,
  43119. samplingMode: samplingMode,
  43120. generateDepthBuffer: generateDepthBuffer,
  43121. generateStencilBuffer: generateStencilBuffer
  43122. };
  43123. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  43124. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43125. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43126. }
  43127. if (isCube) {
  43128. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  43129. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  43130. _this._textureMatrix = BABYLON.Matrix.Identity();
  43131. }
  43132. else {
  43133. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  43134. }
  43135. return _this;
  43136. }
  43137. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  43138. get: function () {
  43139. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  43140. },
  43141. enumerable: true,
  43142. configurable: true
  43143. });
  43144. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  43145. get: function () {
  43146. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  43147. },
  43148. enumerable: true,
  43149. configurable: true
  43150. });
  43151. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  43152. get: function () {
  43153. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  43154. },
  43155. enumerable: true,
  43156. configurable: true
  43157. });
  43158. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  43159. set: function (callback) {
  43160. if (this._onAfterUnbindObserver) {
  43161. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  43162. }
  43163. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  43164. },
  43165. enumerable: true,
  43166. configurable: true
  43167. });
  43168. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  43169. set: function (callback) {
  43170. if (this._onBeforeRenderObserver) {
  43171. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  43172. }
  43173. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  43174. },
  43175. enumerable: true,
  43176. configurable: true
  43177. });
  43178. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  43179. set: function (callback) {
  43180. if (this._onAfterRenderObserver) {
  43181. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  43182. }
  43183. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  43184. },
  43185. enumerable: true,
  43186. configurable: true
  43187. });
  43188. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  43189. set: function (callback) {
  43190. if (this._onClearObserver) {
  43191. this.onClearObservable.remove(this._onClearObserver);
  43192. }
  43193. this._onClearObserver = this.onClearObservable.add(callback);
  43194. },
  43195. enumerable: true,
  43196. configurable: true
  43197. });
  43198. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  43199. get: function () {
  43200. return this._renderTargetOptions;
  43201. },
  43202. enumerable: true,
  43203. configurable: true
  43204. });
  43205. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  43206. get: function () {
  43207. return this._samples;
  43208. },
  43209. set: function (value) {
  43210. if (this._samples === value) {
  43211. return;
  43212. }
  43213. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  43214. },
  43215. enumerable: true,
  43216. configurable: true
  43217. });
  43218. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  43219. this._currentRefreshId = -1;
  43220. };
  43221. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  43222. get: function () {
  43223. return this._refreshRate;
  43224. },
  43225. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  43226. set: function (value) {
  43227. this._refreshRate = value;
  43228. this.resetRefreshCounter();
  43229. },
  43230. enumerable: true,
  43231. configurable: true
  43232. });
  43233. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  43234. if (!this._postProcessManager) {
  43235. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  43236. this._postProcesses = new Array();
  43237. }
  43238. this._postProcesses.push(postProcess);
  43239. this._postProcesses[0].autoClear = false;
  43240. };
  43241. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  43242. if (!this._postProcesses) {
  43243. return;
  43244. }
  43245. if (dispose) {
  43246. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  43247. var postProcess = _a[_i];
  43248. postProcess.dispose();
  43249. postProcess = null;
  43250. }
  43251. }
  43252. this._postProcesses = [];
  43253. };
  43254. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  43255. if (!this._postProcesses) {
  43256. return;
  43257. }
  43258. var index = this._postProcesses.indexOf(postProcess);
  43259. if (index === -1) {
  43260. return;
  43261. }
  43262. this._postProcesses.splice(index, 1);
  43263. if (this._postProcesses.length > 0) {
  43264. this._postProcesses[0].autoClear = false;
  43265. }
  43266. };
  43267. RenderTargetTexture.prototype._shouldRender = function () {
  43268. if (this._currentRefreshId === -1) {
  43269. this._currentRefreshId = 1;
  43270. return true;
  43271. }
  43272. if (this.refreshRate === this._currentRefreshId) {
  43273. this._currentRefreshId = 1;
  43274. return true;
  43275. }
  43276. this._currentRefreshId++;
  43277. return false;
  43278. };
  43279. RenderTargetTexture.prototype.isReady = function () {
  43280. if (!this.getScene().renderTargetsEnabled) {
  43281. return false;
  43282. }
  43283. return _super.prototype.isReady.call(this);
  43284. };
  43285. RenderTargetTexture.prototype.getRenderSize = function () {
  43286. return this._size;
  43287. };
  43288. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  43289. get: function () {
  43290. return true;
  43291. },
  43292. enumerable: true,
  43293. configurable: true
  43294. });
  43295. RenderTargetTexture.prototype.scale = function (ratio) {
  43296. var newSize = this._size * ratio;
  43297. this.resize(newSize);
  43298. };
  43299. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  43300. if (this.isCube) {
  43301. return this._textureMatrix;
  43302. }
  43303. return _super.prototype.getReflectionTextureMatrix.call(this);
  43304. };
  43305. RenderTargetTexture.prototype.resize = function (size) {
  43306. this.releaseInternalTexture();
  43307. if (this.isCube) {
  43308. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  43309. }
  43310. else {
  43311. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  43312. }
  43313. };
  43314. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  43315. var scene = this.getScene();
  43316. var engine = scene.getEngine();
  43317. if (this.useCameraPostProcesses !== undefined) {
  43318. useCameraPostProcess = this.useCameraPostProcesses;
  43319. }
  43320. if (this._waitingRenderList) {
  43321. this.renderList = [];
  43322. for (var index = 0; index < this._waitingRenderList.length; index++) {
  43323. var id = this._waitingRenderList[index];
  43324. this.renderList.push(scene.getMeshByID(id));
  43325. }
  43326. delete this._waitingRenderList;
  43327. }
  43328. // Is predicate defined?
  43329. if (this.renderListPredicate) {
  43330. this.renderList.splice(0); // Clear previous renderList
  43331. var sceneMeshes = this.getScene().meshes;
  43332. for (var index = 0; index < sceneMeshes.length; index++) {
  43333. var mesh = sceneMeshes[index];
  43334. if (this.renderListPredicate(mesh)) {
  43335. this.renderList.push(mesh);
  43336. }
  43337. }
  43338. }
  43339. if (this.renderList && this.renderList.length === 0) {
  43340. return;
  43341. }
  43342. // Set custom projection.
  43343. // Needs to be before binding to prevent changing the aspect ratio.
  43344. var camera;
  43345. if (this.activeCamera) {
  43346. camera = this.activeCamera;
  43347. engine.setViewport(this.activeCamera.viewport);
  43348. if (this.activeCamera !== scene.activeCamera) {
  43349. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  43350. }
  43351. }
  43352. else {
  43353. camera = scene.activeCamera;
  43354. engine.setViewport(scene.activeCamera.viewport);
  43355. }
  43356. // Prepare renderingManager
  43357. this._renderingManager.reset();
  43358. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  43359. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  43360. var sceneRenderId = scene.getRenderId();
  43361. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  43362. var mesh = currentRenderList[meshIndex];
  43363. if (mesh) {
  43364. if (!mesh.isReady()) {
  43365. // Reset _currentRefreshId
  43366. this.resetRefreshCounter();
  43367. continue;
  43368. }
  43369. mesh._preActivateForIntermediateRendering(sceneRenderId);
  43370. var isMasked = void 0;
  43371. if (!this.renderList) {
  43372. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  43373. }
  43374. else {
  43375. isMasked = false;
  43376. }
  43377. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  43378. mesh._activate(sceneRenderId);
  43379. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  43380. var subMesh = mesh.subMeshes[subIndex];
  43381. scene._activeIndices.addCount(subMesh.indexCount, false);
  43382. this._renderingManager.dispatch(subMesh);
  43383. }
  43384. }
  43385. }
  43386. }
  43387. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  43388. var particleSystem = scene.particleSystems[particleIndex];
  43389. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  43390. continue;
  43391. }
  43392. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  43393. this._renderingManager.dispatchParticles(particleSystem);
  43394. }
  43395. }
  43396. if (this.isCube) {
  43397. for (var face = 0; face < 6; face++) {
  43398. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  43399. scene.incrementRenderId();
  43400. scene.resetCachedMaterial();
  43401. }
  43402. }
  43403. else {
  43404. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  43405. }
  43406. this.onAfterUnbindObservable.notifyObservers(this);
  43407. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  43408. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  43409. }
  43410. engine.setViewport(scene.activeCamera.viewport);
  43411. scene.resetCachedMaterial();
  43412. };
  43413. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  43414. var _this = this;
  43415. var scene = this.getScene();
  43416. var engine = scene.getEngine();
  43417. // Bind
  43418. if (this._postProcessManager) {
  43419. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  43420. }
  43421. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  43422. if (this.isCube) {
  43423. engine.bindFramebuffer(this._texture, faceIndex);
  43424. }
  43425. else {
  43426. engine.bindFramebuffer(this._texture);
  43427. }
  43428. }
  43429. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  43430. // Clear
  43431. if (this.onClearObservable.hasObservers()) {
  43432. this.onClearObservable.notifyObservers(engine);
  43433. }
  43434. else {
  43435. engine.clear(scene.clearColor, true, true, true);
  43436. }
  43437. if (!this._doNotChangeAspectRatio) {
  43438. scene.updateTransformMatrix(true);
  43439. }
  43440. // Render
  43441. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  43442. if (this._postProcessManager) {
  43443. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  43444. }
  43445. else if (useCameraPostProcess) {
  43446. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  43447. }
  43448. if (!this._doNotChangeAspectRatio) {
  43449. scene.updateTransformMatrix(true);
  43450. }
  43451. // Dump ?
  43452. if (dumpForDebug) {
  43453. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  43454. }
  43455. // Unbind
  43456. if (!this.isCube || faceIndex === 5) {
  43457. if (this.isCube) {
  43458. if (faceIndex === 5) {
  43459. engine.generateMipMapsForCubemap(this._texture);
  43460. }
  43461. }
  43462. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  43463. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  43464. });
  43465. }
  43466. else {
  43467. this.onAfterRenderObservable.notifyObservers(faceIndex);
  43468. }
  43469. };
  43470. /**
  43471. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  43472. * This allowed control for front to back rendering or reversly depending of the special needs.
  43473. *
  43474. * @param renderingGroupId The rendering group id corresponding to its index
  43475. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  43476. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  43477. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  43478. */
  43479. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  43480. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  43481. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  43482. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  43483. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  43484. };
  43485. /**
  43486. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  43487. *
  43488. * @param renderingGroupId The rendering group id corresponding to its index
  43489. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  43490. */
  43491. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  43492. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  43493. };
  43494. RenderTargetTexture.prototype.clone = function () {
  43495. var textureSize = this.getSize();
  43496. 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);
  43497. // Base texture
  43498. newTexture.hasAlpha = this.hasAlpha;
  43499. newTexture.level = this.level;
  43500. // RenderTarget Texture
  43501. newTexture.coordinatesMode = this.coordinatesMode;
  43502. newTexture.renderList = this.renderList.slice(0);
  43503. return newTexture;
  43504. };
  43505. RenderTargetTexture.prototype.serialize = function () {
  43506. if (!this.name) {
  43507. return null;
  43508. }
  43509. var serializationObject = _super.prototype.serialize.call(this);
  43510. serializationObject.renderTargetSize = this.getRenderSize();
  43511. serializationObject.renderList = [];
  43512. for (var index = 0; index < this.renderList.length; index++) {
  43513. serializationObject.renderList.push(this.renderList[index].id);
  43514. }
  43515. return serializationObject;
  43516. };
  43517. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  43518. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  43519. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  43520. };
  43521. RenderTargetTexture.prototype.dispose = function () {
  43522. if (this._postProcessManager) {
  43523. this._postProcessManager.dispose();
  43524. this._postProcessManager = null;
  43525. }
  43526. this.clearPostProcesses(true);
  43527. // Remove from custom render targets
  43528. var scene = this.getScene();
  43529. var index = scene.customRenderTargets.indexOf(this);
  43530. if (index >= 0) {
  43531. scene.customRenderTargets.splice(index, 1);
  43532. }
  43533. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  43534. var camera = _a[_i];
  43535. index = camera.customRenderTargets.indexOf(this);
  43536. if (index >= 0) {
  43537. camera.customRenderTargets.splice(index, 1);
  43538. }
  43539. }
  43540. _super.prototype.dispose.call(this);
  43541. };
  43542. return RenderTargetTexture;
  43543. }(BABYLON.Texture));
  43544. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  43545. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  43546. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  43547. BABYLON.RenderTargetTexture = RenderTargetTexture;
  43548. })(BABYLON || (BABYLON = {}));
  43549. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  43550. var BABYLON;
  43551. (function (BABYLON) {
  43552. ;
  43553. var MultiRenderTarget = (function (_super) {
  43554. __extends(MultiRenderTarget, _super);
  43555. function MultiRenderTarget(name, size, count, scene, options) {
  43556. var _this = this;
  43557. options = options || {};
  43558. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  43559. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  43560. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  43561. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  43562. if (!_this.isSupported) {
  43563. _this.dispose();
  43564. return;
  43565. }
  43566. var types = [];
  43567. var samplingModes = [];
  43568. for (var i = 0; i < count; i++) {
  43569. if (options.types && options.types[i]) {
  43570. types.push(options.types[i]);
  43571. }
  43572. else {
  43573. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  43574. }
  43575. if (options.samplingModes && options.samplingModes[i]) {
  43576. samplingModes.push(options.samplingModes[i]);
  43577. }
  43578. else {
  43579. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43580. }
  43581. }
  43582. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  43583. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  43584. _this._count = count;
  43585. _this._size = size;
  43586. _this._multiRenderTargetOptions = {
  43587. samplingModes: samplingModes,
  43588. generateMipMaps: generateMipMaps,
  43589. generateDepthBuffer: generateDepthBuffer,
  43590. generateStencilBuffer: generateStencilBuffer,
  43591. generateDepthTexture: generateDepthTexture,
  43592. types: types,
  43593. textureCount: count
  43594. };
  43595. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  43596. _this._createInternalTextures();
  43597. return _this;
  43598. }
  43599. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  43600. get: function () {
  43601. var engine = this.getScene().getEngine();
  43602. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  43603. },
  43604. enumerable: true,
  43605. configurable: true
  43606. });
  43607. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  43608. get: function () {
  43609. return this._textures;
  43610. },
  43611. enumerable: true,
  43612. configurable: true
  43613. });
  43614. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  43615. get: function () {
  43616. return this._textures[this._textures.length - 1];
  43617. },
  43618. enumerable: true,
  43619. configurable: true
  43620. });
  43621. MultiRenderTarget.prototype._createInternalTextures = function () {
  43622. this._textures = [];
  43623. for (var i = 0; i < this._webGLTextures.length; i++) {
  43624. var texture = new BABYLON.Texture(null, this.getScene());
  43625. texture._texture = this._webGLTextures[i];
  43626. this._textures.push(texture);
  43627. }
  43628. // Keeps references to frame buffer and stencil/depth buffer
  43629. this._texture = this._webGLTextures[0];
  43630. };
  43631. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  43632. get: function () {
  43633. return this._samples;
  43634. },
  43635. set: function (value) {
  43636. if (this._samples === value) {
  43637. return;
  43638. }
  43639. for (var i = 0; i < this._webGLTextures.length; i++) {
  43640. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  43641. }
  43642. },
  43643. enumerable: true,
  43644. configurable: true
  43645. });
  43646. MultiRenderTarget.prototype.resize = function (size) {
  43647. this.releaseInternalTextures();
  43648. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  43649. this._createInternalTextures();
  43650. };
  43651. MultiRenderTarget.prototype.dispose = function () {
  43652. this.releaseInternalTextures();
  43653. _super.prototype.dispose.call(this);
  43654. };
  43655. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  43656. if (!this._webGLTextures) {
  43657. return;
  43658. }
  43659. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  43660. if (this._webGLTextures[i] !== undefined) {
  43661. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  43662. this._webGLTextures.splice(i, 1);
  43663. }
  43664. }
  43665. };
  43666. return MultiRenderTarget;
  43667. }(BABYLON.RenderTargetTexture));
  43668. BABYLON.MultiRenderTarget = MultiRenderTarget;
  43669. })(BABYLON || (BABYLON = {}));
  43670. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  43671. /// <reference path="babylon.renderTargetTexture.ts" />
  43672. var BABYLON;
  43673. (function (BABYLON) {
  43674. var MirrorTexture = (function (_super) {
  43675. __extends(MirrorTexture, _super);
  43676. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  43677. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43679. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  43680. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  43681. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  43682. _this._transformMatrix = BABYLON.Matrix.Zero();
  43683. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  43684. _this._blurKernelX = 0;
  43685. _this._blurKernelY = 0;
  43686. _this._blurRatio = 1.0;
  43687. _this.onBeforeRenderObservable.add(function () {
  43688. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  43689. _this._savedViewMatrix = scene.getViewMatrix();
  43690. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  43691. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  43692. scene.clipPlane = _this.mirrorPlane;
  43693. scene.getEngine().cullBackFaces = false;
  43694. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  43695. });
  43696. _this.onAfterRenderObservable.add(function () {
  43697. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  43698. scene.getEngine().cullBackFaces = true;
  43699. scene._mirroredCameraPosition = null;
  43700. delete scene.clipPlane;
  43701. });
  43702. return _this;
  43703. }
  43704. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  43705. get: function () {
  43706. return this._blurRatio;
  43707. },
  43708. set: function (value) {
  43709. if (this._blurRatio === value) {
  43710. return;
  43711. }
  43712. this._blurRatio = value;
  43713. this._preparePostProcesses();
  43714. },
  43715. enumerable: true,
  43716. configurable: true
  43717. });
  43718. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  43719. set: function (value) {
  43720. this.blurKernelX = value;
  43721. this.blurKernelY = value;
  43722. },
  43723. enumerable: true,
  43724. configurable: true
  43725. });
  43726. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  43727. get: function () {
  43728. return this._blurKernelX;
  43729. },
  43730. set: function (value) {
  43731. if (this._blurKernelX === value) {
  43732. return;
  43733. }
  43734. this._blurKernelX = value;
  43735. this._preparePostProcesses();
  43736. },
  43737. enumerable: true,
  43738. configurable: true
  43739. });
  43740. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  43741. get: function () {
  43742. return this._blurKernelY;
  43743. },
  43744. set: function (value) {
  43745. if (this._blurKernelY === value) {
  43746. return;
  43747. }
  43748. this._blurKernelY = value;
  43749. this._preparePostProcesses();
  43750. },
  43751. enumerable: true,
  43752. configurable: true
  43753. });
  43754. MirrorTexture.prototype._preparePostProcesses = function () {
  43755. this.clearPostProcesses(true);
  43756. if (this._blurKernelX && this._blurKernelY) {
  43757. var engine = this.getScene().getEngine();
  43758. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  43759. 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);
  43760. this._blurX.autoClear = false;
  43761. if (this._blurRatio === 1 && this.samples < 2) {
  43762. this._blurX.outputTexture = this._texture;
  43763. }
  43764. else {
  43765. this._blurX.alwaysForcePOT = true;
  43766. }
  43767. 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);
  43768. this._blurY.autoClear = false;
  43769. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  43770. this.addPostProcess(this._blurX);
  43771. this.addPostProcess(this._blurY);
  43772. }
  43773. };
  43774. MirrorTexture.prototype.clone = function () {
  43775. var textureSize = this.getSize();
  43776. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  43777. // Base texture
  43778. newTexture.hasAlpha = this.hasAlpha;
  43779. newTexture.level = this.level;
  43780. // Mirror Texture
  43781. newTexture.mirrorPlane = this.mirrorPlane.clone();
  43782. newTexture.renderList = this.renderList.slice(0);
  43783. return newTexture;
  43784. };
  43785. MirrorTexture.prototype.serialize = function () {
  43786. if (!this.name) {
  43787. return null;
  43788. }
  43789. var serializationObject = _super.prototype.serialize.call(this);
  43790. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  43791. return serializationObject;
  43792. };
  43793. return MirrorTexture;
  43794. }(BABYLON.RenderTargetTexture));
  43795. BABYLON.MirrorTexture = MirrorTexture;
  43796. })(BABYLON || (BABYLON = {}));
  43797. //# sourceMappingURL=babylon.mirrorTexture.js.map
  43798. /// <reference path="babylon.renderTargetTexture.ts" />
  43799. var BABYLON;
  43800. (function (BABYLON) {
  43801. /**
  43802. * Creates a refraction texture used by refraction channel of the standard material.
  43803. * @param name the texture name
  43804. * @param size size of the underlying texture
  43805. * @param scene root scene
  43806. */
  43807. var RefractionTexture = (function (_super) {
  43808. __extends(RefractionTexture, _super);
  43809. function RefractionTexture(name, size, scene, generateMipMaps) {
  43810. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  43811. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  43812. _this.depth = 2.0;
  43813. _this.onBeforeRenderObservable.add(function () {
  43814. scene.clipPlane = _this.refractionPlane;
  43815. });
  43816. _this.onAfterRenderObservable.add(function () {
  43817. delete scene.clipPlane;
  43818. });
  43819. return _this;
  43820. }
  43821. RefractionTexture.prototype.clone = function () {
  43822. var textureSize = this.getSize();
  43823. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  43824. // Base texture
  43825. newTexture.hasAlpha = this.hasAlpha;
  43826. newTexture.level = this.level;
  43827. // Refraction Texture
  43828. newTexture.refractionPlane = this.refractionPlane.clone();
  43829. newTexture.renderList = this.renderList.slice(0);
  43830. newTexture.depth = this.depth;
  43831. return newTexture;
  43832. };
  43833. RefractionTexture.prototype.serialize = function () {
  43834. if (!this.name) {
  43835. return null;
  43836. }
  43837. var serializationObject = _super.prototype.serialize.call(this);
  43838. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  43839. serializationObject.depth = this.depth;
  43840. return serializationObject;
  43841. };
  43842. return RefractionTexture;
  43843. }(BABYLON.RenderTargetTexture));
  43844. BABYLON.RefractionTexture = RefractionTexture;
  43845. })(BABYLON || (BABYLON = {}));
  43846. //# sourceMappingURL=babylon.refractionTexture.js.map
  43847. /// <reference path="babylon.texture.ts" />
  43848. var BABYLON;
  43849. (function (BABYLON) {
  43850. var DynamicTexture = (function (_super) {
  43851. __extends(DynamicTexture, _super);
  43852. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  43853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43854. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  43855. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  43856. _this.name = name;
  43857. var engine = _this.getScene().getEngine();
  43858. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43859. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43860. _this._generateMipMaps = generateMipMaps;
  43861. if (options.getContext) {
  43862. _this._canvas = options;
  43863. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43864. }
  43865. else {
  43866. _this._canvas = document.createElement("canvas");
  43867. if (options.width) {
  43868. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43869. }
  43870. else {
  43871. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  43872. }
  43873. }
  43874. var textureSize = _this.getSize();
  43875. _this._canvas.width = textureSize.width;
  43876. _this._canvas.height = textureSize.height;
  43877. _this._context = _this._canvas.getContext("2d");
  43878. return _this;
  43879. }
  43880. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  43881. get: function () {
  43882. return true;
  43883. },
  43884. enumerable: true,
  43885. configurable: true
  43886. });
  43887. DynamicTexture.prototype._recreate = function (textureSize) {
  43888. this._canvas.width = textureSize.width;
  43889. this._canvas.height = textureSize.height;
  43890. this.releaseInternalTexture();
  43891. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  43892. };
  43893. DynamicTexture.prototype.scale = function (ratio) {
  43894. var textureSize = this.getSize();
  43895. textureSize.width *= ratio;
  43896. textureSize.height *= ratio;
  43897. this._recreate(textureSize);
  43898. };
  43899. DynamicTexture.prototype.scaleTo = function (width, height) {
  43900. var textureSize = this.getSize();
  43901. textureSize.width = width;
  43902. textureSize.height = height;
  43903. this._recreate(textureSize);
  43904. };
  43905. DynamicTexture.prototype.getContext = function () {
  43906. return this._context;
  43907. };
  43908. DynamicTexture.prototype.clear = function () {
  43909. var size = this.getSize();
  43910. this._context.fillRect(0, 0, size.width, size.height);
  43911. };
  43912. DynamicTexture.prototype.update = function (invertY) {
  43913. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  43914. };
  43915. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  43916. if (update === void 0) { update = true; }
  43917. var size = this.getSize();
  43918. if (clearColor) {
  43919. this._context.fillStyle = clearColor;
  43920. this._context.fillRect(0, 0, size.width, size.height);
  43921. }
  43922. this._context.font = font;
  43923. if (x === null || x === undefined) {
  43924. var textSize = this._context.measureText(text);
  43925. x = (size.width - textSize.width) / 2;
  43926. }
  43927. if (y === null || y === undefined) {
  43928. var fontSize = parseInt((font.replace(/\D/g, '')));
  43929. ;
  43930. y = (size.height / 2) + (fontSize / 3.65);
  43931. }
  43932. this._context.fillStyle = color;
  43933. this._context.fillText(text, x, y);
  43934. if (update) {
  43935. this.update(invertY);
  43936. }
  43937. };
  43938. DynamicTexture.prototype.clone = function () {
  43939. var textureSize = this.getSize();
  43940. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  43941. // Base texture
  43942. newTexture.hasAlpha = this.hasAlpha;
  43943. newTexture.level = this.level;
  43944. // Dynamic Texture
  43945. newTexture.wrapU = this.wrapU;
  43946. newTexture.wrapV = this.wrapV;
  43947. return newTexture;
  43948. };
  43949. return DynamicTexture;
  43950. }(BABYLON.Texture));
  43951. BABYLON.DynamicTexture = DynamicTexture;
  43952. })(BABYLON || (BABYLON = {}));
  43953. //# sourceMappingURL=babylon.dynamicTexture.js.map
  43954. var BABYLON;
  43955. (function (BABYLON) {
  43956. var VideoTexture = (function (_super) {
  43957. __extends(VideoTexture, _super);
  43958. /**
  43959. * Creates a video texture.
  43960. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  43961. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  43962. * @param {BABYLON.Scene} scene is obviously the current scene.
  43963. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  43964. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  43965. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  43966. */
  43967. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  43968. if (generateMipMaps === void 0) { generateMipMaps = false; }
  43969. if (invertY === void 0) { invertY = false; }
  43970. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43971. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43972. _this._autoLaunch = true;
  43973. var urls;
  43974. _this.name = name;
  43975. if (urlsOrVideo instanceof HTMLVideoElement) {
  43976. _this.video = urlsOrVideo;
  43977. }
  43978. else {
  43979. urls = urlsOrVideo;
  43980. _this.video = document.createElement("video");
  43981. _this.video.autoplay = false;
  43982. _this.video.loop = true;
  43983. }
  43984. _this._generateMipMaps = generateMipMaps;
  43985. _this._samplingMode = samplingMode;
  43986. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  43987. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  43988. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  43989. }
  43990. else {
  43991. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43992. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43993. _this._generateMipMaps = false;
  43994. }
  43995. if (urls) {
  43996. _this.video.addEventListener("canplay", function () {
  43997. _this._createTexture();
  43998. });
  43999. urls.forEach(function (url) {
  44000. var source = document.createElement("source");
  44001. source.src = url;
  44002. _this.video.appendChild(source);
  44003. });
  44004. }
  44005. else {
  44006. _this._createTexture();
  44007. }
  44008. _this._lastUpdate = BABYLON.Tools.Now;
  44009. return _this;
  44010. }
  44011. VideoTexture.prototype.__setTextureReady = function () {
  44012. this._texture.isReady = true;
  44013. };
  44014. VideoTexture.prototype._createTexture = function () {
  44015. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  44016. if (this._autoLaunch) {
  44017. this._autoLaunch = false;
  44018. this.video.play();
  44019. }
  44020. this._setTextureReady = this.__setTextureReady.bind(this);
  44021. this.video.addEventListener("playing", this._setTextureReady);
  44022. };
  44023. VideoTexture.prototype.update = function () {
  44024. var now = BABYLON.Tools.Now;
  44025. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  44026. return false;
  44027. }
  44028. this._lastUpdate = now;
  44029. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  44030. return true;
  44031. };
  44032. VideoTexture.prototype.dispose = function () {
  44033. _super.prototype.dispose.call(this);
  44034. this.video.removeEventListener("playing", this._setTextureReady);
  44035. };
  44036. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  44037. var video = document.createElement("video");
  44038. var constraintsDeviceId;
  44039. if (constraints && constraints.deviceId) {
  44040. constraintsDeviceId = {
  44041. exact: constraints.deviceId
  44042. };
  44043. }
  44044. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  44045. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  44046. if (navigator.getUserMedia) {
  44047. navigator.getUserMedia({
  44048. video: {
  44049. deviceId: constraintsDeviceId,
  44050. width: {
  44051. min: (constraints && constraints.minWidth) || 256,
  44052. max: (constraints && constraints.maxWidth) || 640
  44053. },
  44054. height: {
  44055. min: (constraints && constraints.minHeight) || 256,
  44056. max: (constraints && constraints.maxHeight) || 480
  44057. }
  44058. }
  44059. }, function (stream) {
  44060. if (video.mozSrcObject !== undefined) {
  44061. video.mozSrcObject = stream;
  44062. }
  44063. else {
  44064. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  44065. }
  44066. video.play();
  44067. if (onReady) {
  44068. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  44069. }
  44070. }, function (e) {
  44071. BABYLON.Tools.Error(e.name);
  44072. });
  44073. }
  44074. };
  44075. return VideoTexture;
  44076. }(BABYLON.Texture));
  44077. BABYLON.VideoTexture = VideoTexture;
  44078. })(BABYLON || (BABYLON = {}));
  44079. //# sourceMappingURL=babylon.videoTexture.js.map
  44080. var BABYLON;
  44081. (function (BABYLON) {
  44082. var RawTexture = (function (_super) {
  44083. __extends(RawTexture, _super);
  44084. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  44085. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44086. if (invertY === void 0) { invertY = false; }
  44087. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44088. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  44089. _this.format = format;
  44090. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  44091. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44092. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44093. return _this;
  44094. }
  44095. RawTexture.prototype.update = function (data) {
  44096. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  44097. };
  44098. // Statics
  44099. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44100. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44101. if (invertY === void 0) { invertY = false; }
  44102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44103. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  44104. };
  44105. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44106. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44107. if (invertY === void 0) { invertY = false; }
  44108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44109. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44110. };
  44111. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44112. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44113. if (invertY === void 0) { invertY = false; }
  44114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44115. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44116. };
  44117. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44118. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44119. if (invertY === void 0) { invertY = false; }
  44120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44121. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  44122. };
  44123. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44124. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44125. if (invertY === void 0) { invertY = false; }
  44126. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44127. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  44128. };
  44129. return RawTexture;
  44130. }(BABYLON.Texture));
  44131. BABYLON.RawTexture = RawTexture;
  44132. })(BABYLON || (BABYLON = {}));
  44133. //# sourceMappingURL=babylon.rawTexture.js.map
  44134. var BABYLON;
  44135. (function (BABYLON) {
  44136. var PostProcess = (function () {
  44137. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  44138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  44139. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44140. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  44141. if (blockCompilation === void 0) { blockCompilation = false; }
  44142. this.name = name;
  44143. this.width = -1;
  44144. this.height = -1;
  44145. this.autoClear = true;
  44146. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  44147. /*
  44148. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  44149. Can only be used on a single postprocess or on the last one of a chain.
  44150. */
  44151. this.enablePixelPerfectMode = false;
  44152. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  44153. this.alwaysForcePOT = false;
  44154. this.samples = 1;
  44155. this._reusable = false;
  44156. this._textures = new BABYLON.SmartArray(2);
  44157. this._currentRenderTextureInd = 0;
  44158. this._scaleRatio = new BABYLON.Vector2(1, 1);
  44159. this._texelSize = BABYLON.Vector2.Zero();
  44160. // Events
  44161. /**
  44162. * An event triggered when the postprocess is activated.
  44163. * @type {BABYLON.Observable}
  44164. */
  44165. this.onActivateObservable = new BABYLON.Observable();
  44166. /**
  44167. * An event triggered when the postprocess changes its size.
  44168. * @type {BABYLON.Observable}
  44169. */
  44170. this.onSizeChangedObservable = new BABYLON.Observable();
  44171. /**
  44172. * An event triggered when the postprocess applies its effect.
  44173. * @type {BABYLON.Observable}
  44174. */
  44175. this.onApplyObservable = new BABYLON.Observable();
  44176. /**
  44177. * An event triggered before rendering the postprocess
  44178. * @type {BABYLON.Observable}
  44179. */
  44180. this.onBeforeRenderObservable = new BABYLON.Observable();
  44181. /**
  44182. * An event triggered after rendering the postprocess
  44183. * @type {BABYLON.Observable}
  44184. */
  44185. this.onAfterRenderObservable = new BABYLON.Observable();
  44186. if (camera != null) {
  44187. this._camera = camera;
  44188. this._scene = camera.getScene();
  44189. camera.attachPostProcess(this);
  44190. this._engine = this._scene.getEngine();
  44191. }
  44192. else {
  44193. this._engine = engine;
  44194. }
  44195. this._options = options;
  44196. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  44197. this._reusable = reusable || false;
  44198. this._textureType = textureType;
  44199. this._samplers = samplers || [];
  44200. this._samplers.push("textureSampler");
  44201. this._fragmentUrl = fragmentUrl;
  44202. this._vertexUrl = vertexUrl;
  44203. this._parameters = parameters || [];
  44204. this._parameters.push("scale");
  44205. this._indexParameters = indexParameters;
  44206. if (!blockCompilation) {
  44207. this.updateEffect(defines);
  44208. }
  44209. }
  44210. Object.defineProperty(PostProcess.prototype, "onActivate", {
  44211. set: function (callback) {
  44212. if (this._onActivateObserver) {
  44213. this.onActivateObservable.remove(this._onActivateObserver);
  44214. }
  44215. this._onActivateObserver = this.onActivateObservable.add(callback);
  44216. },
  44217. enumerable: true,
  44218. configurable: true
  44219. });
  44220. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  44221. set: function (callback) {
  44222. if (this._onSizeChangedObserver) {
  44223. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  44224. }
  44225. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  44226. },
  44227. enumerable: true,
  44228. configurable: true
  44229. });
  44230. Object.defineProperty(PostProcess.prototype, "onApply", {
  44231. set: function (callback) {
  44232. if (this._onApplyObserver) {
  44233. this.onApplyObservable.remove(this._onApplyObserver);
  44234. }
  44235. this._onApplyObserver = this.onApplyObservable.add(callback);
  44236. },
  44237. enumerable: true,
  44238. configurable: true
  44239. });
  44240. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  44241. set: function (callback) {
  44242. if (this._onBeforeRenderObserver) {
  44243. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  44244. }
  44245. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  44246. },
  44247. enumerable: true,
  44248. configurable: true
  44249. });
  44250. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  44251. set: function (callback) {
  44252. if (this._onAfterRenderObserver) {
  44253. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  44254. }
  44255. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  44256. },
  44257. enumerable: true,
  44258. configurable: true
  44259. });
  44260. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  44261. get: function () {
  44262. return this._textures.data[this._currentRenderTextureInd];
  44263. },
  44264. set: function (value) {
  44265. this._forcedOutputTexture = value;
  44266. },
  44267. enumerable: true,
  44268. configurable: true
  44269. });
  44270. PostProcess.prototype.getCamera = function () {
  44271. return this._camera;
  44272. };
  44273. Object.defineProperty(PostProcess.prototype, "texelSize", {
  44274. get: function () {
  44275. if (this._shareOutputWithPostProcess) {
  44276. return this._shareOutputWithPostProcess.texelSize;
  44277. }
  44278. if (this._forcedOutputTexture) {
  44279. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  44280. }
  44281. return this._texelSize;
  44282. },
  44283. enumerable: true,
  44284. configurable: true
  44285. });
  44286. PostProcess.prototype.getEngine = function () {
  44287. return this._engine;
  44288. };
  44289. PostProcess.prototype.getEffect = function () {
  44290. return this._effect;
  44291. };
  44292. PostProcess.prototype.shareOutputWith = function (postProcess) {
  44293. this._disposeTextures();
  44294. this._shareOutputWithPostProcess = postProcess;
  44295. return this;
  44296. };
  44297. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  44298. 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);
  44299. };
  44300. PostProcess.prototype.isReusable = function () {
  44301. return this._reusable;
  44302. };
  44303. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  44304. PostProcess.prototype.markTextureDirty = function () {
  44305. this.width = -1;
  44306. };
  44307. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  44308. var _this = this;
  44309. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  44310. camera = camera || this._camera;
  44311. var scene = camera.getScene();
  44312. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  44313. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  44314. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  44315. var desiredWidth = this._options.width || requiredWidth;
  44316. var desiredHeight = this._options.height || requiredHeight;
  44317. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  44318. if (!this._options.width) {
  44319. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  44320. }
  44321. if (!this._options.height) {
  44322. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  44323. }
  44324. }
  44325. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  44326. if (this._textures.length > 0) {
  44327. for (var i = 0; i < this._textures.length; i++) {
  44328. this._engine._releaseTexture(this._textures.data[i]);
  44329. }
  44330. this._textures.reset();
  44331. }
  44332. this.width = desiredWidth;
  44333. this.height = desiredHeight;
  44334. var textureSize = { width: this.width, height: this.height };
  44335. var textureOptions = {
  44336. generateMipMaps: false,
  44337. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  44338. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  44339. samplingMode: this.renderTargetSamplingMode,
  44340. type: this._textureType
  44341. };
  44342. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  44343. if (this._reusable) {
  44344. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  44345. }
  44346. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  44347. this.onSizeChangedObservable.notifyObservers(this);
  44348. }
  44349. this._textures.forEach(function (texture) {
  44350. if (texture.samples !== _this.samples) {
  44351. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  44352. }
  44353. });
  44354. }
  44355. var target;
  44356. if (this._shareOutputWithPostProcess) {
  44357. target = this._shareOutputWithPostProcess.outputTexture;
  44358. }
  44359. else if (this._forcedOutputTexture) {
  44360. target = this._forcedOutputTexture;
  44361. this.width = this._forcedOutputTexture._width;
  44362. this.height = this._forcedOutputTexture._height;
  44363. }
  44364. else {
  44365. target = this.outputTexture;
  44366. }
  44367. if (this.enablePixelPerfectMode) {
  44368. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  44369. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  44370. }
  44371. else {
  44372. this._scaleRatio.copyFromFloats(1, 1);
  44373. this._engine.bindFramebuffer(target);
  44374. }
  44375. this.onActivateObservable.notifyObservers(camera);
  44376. // Clear
  44377. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  44378. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  44379. }
  44380. if (this._reusable) {
  44381. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  44382. }
  44383. };
  44384. Object.defineProperty(PostProcess.prototype, "isSupported", {
  44385. get: function () {
  44386. return this._effect.isSupported;
  44387. },
  44388. enumerable: true,
  44389. configurable: true
  44390. });
  44391. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  44392. get: function () {
  44393. if (this._shareOutputWithPostProcess) {
  44394. return this._shareOutputWithPostProcess.aspectRatio;
  44395. }
  44396. if (this._forcedOutputTexture) {
  44397. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  44398. }
  44399. return this.width / this.height;
  44400. },
  44401. enumerable: true,
  44402. configurable: true
  44403. });
  44404. PostProcess.prototype.apply = function () {
  44405. // Check
  44406. if (!this._effect || !this._effect.isReady())
  44407. return null;
  44408. // States
  44409. this._engine.enableEffect(this._effect);
  44410. this._engine.setState(false);
  44411. this._engine.setDepthBuffer(false);
  44412. this._engine.setDepthWrite(false);
  44413. // Alpha
  44414. this._engine.setAlphaMode(this.alphaMode);
  44415. if (this.alphaConstants) {
  44416. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  44417. }
  44418. // Texture
  44419. var source;
  44420. if (this._shareOutputWithPostProcess) {
  44421. source = this._shareOutputWithPostProcess.outputTexture;
  44422. }
  44423. else if (this._forcedOutputTexture) {
  44424. source = this._forcedOutputTexture;
  44425. }
  44426. else {
  44427. source = this.outputTexture;
  44428. }
  44429. this._effect._bindTexture("textureSampler", source);
  44430. // Parameters
  44431. this._effect.setVector2("scale", this._scaleRatio);
  44432. this.onApplyObservable.notifyObservers(this._effect);
  44433. return this._effect;
  44434. };
  44435. PostProcess.prototype._disposeTextures = function () {
  44436. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  44437. return;
  44438. }
  44439. if (this._textures.length > 0) {
  44440. for (var i = 0; i < this._textures.length; i++) {
  44441. this._engine._releaseTexture(this._textures.data[i]);
  44442. }
  44443. }
  44444. this._textures.dispose();
  44445. };
  44446. PostProcess.prototype.dispose = function (camera) {
  44447. camera = camera || this._camera;
  44448. this._disposeTextures();
  44449. if (!camera) {
  44450. return;
  44451. }
  44452. camera.detachPostProcess(this);
  44453. var index = camera._postProcesses.indexOf(this);
  44454. if (index === 0 && camera._postProcesses.length > 0) {
  44455. this._camera._postProcesses[0].markTextureDirty();
  44456. }
  44457. this.onActivateObservable.clear();
  44458. this.onAfterRenderObservable.clear();
  44459. this.onApplyObservable.clear();
  44460. this.onBeforeRenderObservable.clear();
  44461. this.onSizeChangedObservable.clear();
  44462. };
  44463. return PostProcess;
  44464. }());
  44465. BABYLON.PostProcess = PostProcess;
  44466. })(BABYLON || (BABYLON = {}));
  44467. //# sourceMappingURL=babylon.postProcess.js.map
  44468. var BABYLON;
  44469. (function (BABYLON) {
  44470. var PassPostProcess = (function (_super) {
  44471. __extends(PassPostProcess, _super);
  44472. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  44473. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44474. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  44475. }
  44476. return PassPostProcess;
  44477. }(BABYLON.PostProcess));
  44478. BABYLON.PassPostProcess = PassPostProcess;
  44479. })(BABYLON || (BABYLON = {}));
  44480. //# sourceMappingURL=babylon.passPostProcess.js.map
  44481. var BABYLON;
  44482. (function (BABYLON) {
  44483. var ShadowGenerator = (function () {
  44484. /**
  44485. * Creates a ShadowGenerator object.
  44486. * A ShadowGenerator is the required tool to use the shadows.
  44487. * Each light casting shadows needs to use its own ShadowGenerator.
  44488. * Required parameters :
  44489. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  44490. * - `light`: the light object generating the shadows.
  44491. * - `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.
  44492. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  44493. */
  44494. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  44495. // Members
  44496. this._bias = 0.00005;
  44497. this._blurBoxOffset = 1;
  44498. this._blurScale = 2;
  44499. this._blurKernel = 1;
  44500. this._useKernelBlur = false;
  44501. this._filter = ShadowGenerator.FILTER_NONE;
  44502. this._darkness = 0;
  44503. this._transparencyShadow = false;
  44504. this.forceBackFacesOnly = false;
  44505. this._lightDirection = BABYLON.Vector3.Zero();
  44506. this._viewMatrix = BABYLON.Matrix.Zero();
  44507. this._projectionMatrix = BABYLON.Matrix.Zero();
  44508. this._transformMatrix = BABYLON.Matrix.Zero();
  44509. this._worldViewProjection = BABYLON.Matrix.Zero();
  44510. this._currentFaceIndex = 0;
  44511. this._currentFaceIndexCache = 0;
  44512. this._isCube = false;
  44513. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  44514. this._mapSize = mapSize;
  44515. this._light = light;
  44516. this._scene = light.getScene();
  44517. light._shadowGenerator = this;
  44518. // Texture type fallback from float to int if not supported.
  44519. var caps = this._scene.getEngine().getCaps();
  44520. if (!useFullFloatFirst) {
  44521. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  44522. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  44523. }
  44524. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  44525. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44526. }
  44527. else {
  44528. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44529. }
  44530. }
  44531. else {
  44532. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  44533. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44534. }
  44535. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  44536. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  44537. }
  44538. else {
  44539. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44540. }
  44541. }
  44542. this._initializeGenerator();
  44543. }
  44544. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  44545. // Static
  44546. get: function () {
  44547. return ShadowGenerator._FILTER_NONE;
  44548. },
  44549. enumerable: true,
  44550. configurable: true
  44551. });
  44552. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  44553. get: function () {
  44554. return ShadowGenerator._FILTER_POISSONSAMPLING;
  44555. },
  44556. enumerable: true,
  44557. configurable: true
  44558. });
  44559. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  44560. get: function () {
  44561. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  44562. },
  44563. enumerable: true,
  44564. configurable: true
  44565. });
  44566. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  44567. get: function () {
  44568. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  44569. },
  44570. enumerable: true,
  44571. configurable: true
  44572. });
  44573. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  44574. get: function () {
  44575. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  44576. },
  44577. enumerable: true,
  44578. configurable: true
  44579. });
  44580. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  44581. get: function () {
  44582. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  44583. },
  44584. enumerable: true,
  44585. configurable: true
  44586. });
  44587. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  44588. get: function () {
  44589. return this._bias;
  44590. },
  44591. set: function (bias) {
  44592. this._bias = bias;
  44593. },
  44594. enumerable: true,
  44595. configurable: true
  44596. });
  44597. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  44598. get: function () {
  44599. return this._blurBoxOffset;
  44600. },
  44601. set: function (value) {
  44602. if (this._blurBoxOffset === value) {
  44603. return;
  44604. }
  44605. this._blurBoxOffset = value;
  44606. this._disposeBlurPostProcesses();
  44607. },
  44608. enumerable: true,
  44609. configurable: true
  44610. });
  44611. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  44612. get: function () {
  44613. return this._blurScale;
  44614. },
  44615. set: function (value) {
  44616. if (this._blurScale === value) {
  44617. return;
  44618. }
  44619. this._blurScale = value;
  44620. this._disposeBlurPostProcesses();
  44621. },
  44622. enumerable: true,
  44623. configurable: true
  44624. });
  44625. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  44626. get: function () {
  44627. return this._blurKernel;
  44628. },
  44629. set: function (value) {
  44630. if (this._blurKernel === value) {
  44631. return;
  44632. }
  44633. this._blurKernel = value;
  44634. this._disposeBlurPostProcesses();
  44635. },
  44636. enumerable: true,
  44637. configurable: true
  44638. });
  44639. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  44640. get: function () {
  44641. return this._useKernelBlur;
  44642. },
  44643. set: function (value) {
  44644. if (this._useKernelBlur === value) {
  44645. return;
  44646. }
  44647. this._useKernelBlur = value;
  44648. this._disposeBlurPostProcesses();
  44649. },
  44650. enumerable: true,
  44651. configurable: true
  44652. });
  44653. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  44654. get: function () {
  44655. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  44656. },
  44657. set: function (value) {
  44658. this._depthScale = value;
  44659. },
  44660. enumerable: true,
  44661. configurable: true
  44662. });
  44663. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  44664. get: function () {
  44665. return this._filter;
  44666. },
  44667. set: function (value) {
  44668. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  44669. if (this._light.needCube()) {
  44670. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  44671. this.useExponentialShadowMap = true;
  44672. return;
  44673. }
  44674. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  44675. this.useCloseExponentialShadowMap = true;
  44676. return;
  44677. }
  44678. }
  44679. if (this._filter === value) {
  44680. return;
  44681. }
  44682. this._filter = value;
  44683. this._disposeBlurPostProcesses();
  44684. this._applyFilterValues();
  44685. this._light._markMeshesAsLightDirty();
  44686. },
  44687. enumerable: true,
  44688. configurable: true
  44689. });
  44690. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  44691. get: function () {
  44692. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  44693. },
  44694. set: function (value) {
  44695. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  44696. },
  44697. enumerable: true,
  44698. configurable: true
  44699. });
  44700. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  44701. get: function () {
  44702. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  44703. return this.useExponentialShadowMap;
  44704. },
  44705. set: function (value) {
  44706. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  44707. this.useExponentialShadowMap = value;
  44708. },
  44709. enumerable: true,
  44710. configurable: true
  44711. });
  44712. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  44713. get: function () {
  44714. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  44715. return this.useBlurExponentialShadowMap;
  44716. },
  44717. set: function (value) {
  44718. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  44719. this.useBlurExponentialShadowMap = value;
  44720. },
  44721. enumerable: true,
  44722. configurable: true
  44723. });
  44724. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  44725. get: function () {
  44726. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  44727. },
  44728. set: function (value) {
  44729. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44730. },
  44731. enumerable: true,
  44732. configurable: true
  44733. });
  44734. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  44735. get: function () {
  44736. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  44737. },
  44738. set: function (value) {
  44739. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44740. },
  44741. enumerable: true,
  44742. configurable: true
  44743. });
  44744. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  44745. get: function () {
  44746. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  44747. },
  44748. set: function (value) {
  44749. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44750. },
  44751. enumerable: true,
  44752. configurable: true
  44753. });
  44754. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  44755. get: function () {
  44756. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  44757. },
  44758. set: function (value) {
  44759. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44760. },
  44761. enumerable: true,
  44762. configurable: true
  44763. });
  44764. /**
  44765. * Returns the darkness value (float).
  44766. */
  44767. ShadowGenerator.prototype.getDarkness = function () {
  44768. return this._darkness;
  44769. };
  44770. /**
  44771. * Sets the ShadowGenerator darkness value (float <= 1.0).
  44772. * Returns the ShadowGenerator.
  44773. */
  44774. ShadowGenerator.prototype.setDarkness = function (darkness) {
  44775. if (darkness >= 1.0)
  44776. this._darkness = 1.0;
  44777. else if (darkness <= 0.0)
  44778. this._darkness = 0.0;
  44779. else
  44780. this._darkness = darkness;
  44781. return this;
  44782. };
  44783. /**
  44784. * Sets the ability to have transparent shadow (boolean).
  44785. * Returns the ShadowGenerator.
  44786. */
  44787. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  44788. this._transparencyShadow = hasShadow;
  44789. return this;
  44790. };
  44791. /**
  44792. * Returns a RenderTargetTexture object : the shadow map texture.
  44793. */
  44794. ShadowGenerator.prototype.getShadowMap = function () {
  44795. return this._shadowMap;
  44796. };
  44797. /**
  44798. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  44799. */
  44800. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  44801. if (this._shadowMap2) {
  44802. return this._shadowMap2;
  44803. }
  44804. return this._shadowMap;
  44805. };
  44806. /**
  44807. * Returns the associated light object.
  44808. */
  44809. ShadowGenerator.prototype.getLight = function () {
  44810. return this._light;
  44811. };
  44812. ShadowGenerator.prototype._initializeGenerator = function () {
  44813. this._light._markMeshesAsLightDirty();
  44814. this._initializeShadowMap();
  44815. };
  44816. ShadowGenerator.prototype._initializeShadowMap = function () {
  44817. var _this = this;
  44818. // Render target
  44819. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  44820. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44821. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44822. this._shadowMap.anisotropicFilteringLevel = 1;
  44823. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44824. this._shadowMap.renderParticles = false;
  44825. // Record Face Index before render.
  44826. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  44827. _this._currentFaceIndex = faceIndex;
  44828. });
  44829. // Custom render function.
  44830. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  44831. // Blur if required afer render.
  44832. this._shadowMap.onAfterUnbindObservable.add(function () {
  44833. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  44834. return;
  44835. }
  44836. if (!_this._blurPostProcesses) {
  44837. _this._initializeBlurRTTAndPostProcesses();
  44838. }
  44839. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  44840. });
  44841. // Clear according to the chosen filter.
  44842. this._shadowMap.onClearObservable.add(function (engine) {
  44843. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  44844. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  44845. }
  44846. else {
  44847. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  44848. }
  44849. });
  44850. };
  44851. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  44852. var _this = this;
  44853. var engine = this._scene.getEngine();
  44854. var targetSize = this._mapSize / this.blurScale;
  44855. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  44856. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  44857. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44858. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44859. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44860. }
  44861. if (this.useKernelBlur) {
  44862. 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);
  44863. this._kernelBlurXPostprocess.width = targetSize;
  44864. this._kernelBlurXPostprocess.height = targetSize;
  44865. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  44866. effect.setTexture("textureSampler", _this._shadowMap);
  44867. });
  44868. 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);
  44869. this._kernelBlurXPostprocess.autoClear = false;
  44870. this._kernelBlurYPostprocess.autoClear = false;
  44871. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44872. this._kernelBlurXPostprocess.packedFloat = true;
  44873. this._kernelBlurYPostprocess.packedFloat = true;
  44874. }
  44875. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  44876. }
  44877. else {
  44878. 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);
  44879. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  44880. effect.setFloat2("screenSize", targetSize, targetSize);
  44881. effect.setTexture("textureSampler", _this._shadowMap);
  44882. });
  44883. this._boxBlurPostprocess.autoClear = false;
  44884. this._blurPostProcesses = [this._boxBlurPostprocess];
  44885. }
  44886. };
  44887. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  44888. var index;
  44889. for (index = 0; index < opaqueSubMeshes.length; index++) {
  44890. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  44891. }
  44892. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  44893. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  44894. }
  44895. if (this._transparencyShadow) {
  44896. for (index = 0; index < transparentSubMeshes.length; index++) {
  44897. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  44898. }
  44899. }
  44900. };
  44901. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  44902. var _this = this;
  44903. var mesh = subMesh.getRenderingMesh();
  44904. var scene = this._scene;
  44905. var engine = scene.getEngine();
  44906. // Culling
  44907. engine.setState(subMesh.getMaterial().backFaceCulling);
  44908. // Managing instances
  44909. var batch = mesh._getInstancesRenderList(subMesh._id);
  44910. if (batch.mustReturn) {
  44911. return;
  44912. }
  44913. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44914. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  44915. engine.enableEffect(this._effect);
  44916. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44917. var material = subMesh.getMaterial();
  44918. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  44919. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  44920. this._effect.setVector3("lightPosition", this.getLight().position);
  44921. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  44922. // Alpha test
  44923. if (material && material.needAlphaTesting()) {
  44924. var alphaTexture = material.getAlphaTestTexture();
  44925. if (alphaTexture) {
  44926. this._effect.setTexture("diffuseSampler", alphaTexture);
  44927. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  44928. }
  44929. }
  44930. // Bones
  44931. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44932. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44933. }
  44934. if (this.forceBackFacesOnly) {
  44935. engine.setState(true, 0, false, true);
  44936. }
  44937. // Draw
  44938. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  44939. if (this.forceBackFacesOnly) {
  44940. engine.setState(true, 0, false, false);
  44941. }
  44942. }
  44943. else {
  44944. // Need to reset refresh rate of the shadowMap
  44945. this._shadowMap.resetRefreshCounter();
  44946. }
  44947. };
  44948. ShadowGenerator.prototype._applyFilterValues = function () {
  44949. if (this.filter === ShadowGenerator.FILTER_NONE) {
  44950. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  44951. }
  44952. else {
  44953. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44954. }
  44955. };
  44956. /**
  44957. * Boolean : true when the ShadowGenerator is finally computed.
  44958. */
  44959. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  44960. var defines = [];
  44961. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44962. defines.push("#define FLOAT");
  44963. }
  44964. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44965. defines.push("#define ESM");
  44966. }
  44967. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44968. var mesh = subMesh.getMesh();
  44969. var material = subMesh.getMaterial();
  44970. // Alpha test
  44971. if (material && material.needAlphaTesting()) {
  44972. var alphaTexture = material.getAlphaTestTexture();
  44973. if (alphaTexture) {
  44974. defines.push("#define ALPHATEST");
  44975. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44976. attribs.push(BABYLON.VertexBuffer.UVKind);
  44977. defines.push("#define UV1");
  44978. }
  44979. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44980. if (alphaTexture.coordinatesIndex === 1) {
  44981. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44982. defines.push("#define UV2");
  44983. }
  44984. }
  44985. }
  44986. }
  44987. // Bones
  44988. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44989. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44990. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44991. if (mesh.numBoneInfluencers > 4) {
  44992. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44993. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44994. }
  44995. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44996. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44997. }
  44998. else {
  44999. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45000. }
  45001. // Instances
  45002. if (useInstances) {
  45003. defines.push("#define INSTANCES");
  45004. attribs.push("world0");
  45005. attribs.push("world1");
  45006. attribs.push("world2");
  45007. attribs.push("world3");
  45008. }
  45009. // Get correct effect
  45010. var join = defines.join("\n");
  45011. if (this._cachedDefines !== join) {
  45012. this._cachedDefines = join;
  45013. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  45014. }
  45015. return this._effect.isReady();
  45016. };
  45017. /**
  45018. * This creates the defines related to the standard BJS materials.
  45019. */
  45020. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  45021. var scene = this._scene;
  45022. var light = this._light;
  45023. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  45024. return;
  45025. }
  45026. defines["SHADOW" + lightIndex] = true;
  45027. if (this.usePoissonSampling) {
  45028. defines["SHADOWPCF" + lightIndex] = true;
  45029. }
  45030. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  45031. defines["SHADOWESM" + lightIndex] = true;
  45032. }
  45033. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  45034. defines["SHADOWCLOSEESM" + lightIndex] = true;
  45035. }
  45036. if (light.needCube()) {
  45037. defines["SHADOWCUBE" + lightIndex] = true;
  45038. }
  45039. };
  45040. /**
  45041. * This binds shadow lights related to the standard BJS materials.
  45042. * It implies the unifroms available on the materials are the standard BJS ones.
  45043. */
  45044. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  45045. var light = this._light;
  45046. var scene = this._scene;
  45047. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  45048. return;
  45049. }
  45050. if (!light.needCube()) {
  45051. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  45052. }
  45053. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  45054. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  45055. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  45056. };
  45057. // Methods
  45058. /**
  45059. * Returns a Matrix object : the updated transformation matrix.
  45060. */
  45061. ShadowGenerator.prototype.getTransformMatrix = function () {
  45062. var scene = this._scene;
  45063. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  45064. return this._transformMatrix;
  45065. }
  45066. this._currentRenderID = scene.getRenderId();
  45067. this._currentFaceIndexCache = this._currentFaceIndex;
  45068. var lightPosition = this._light.position;
  45069. if (this._light.computeTransformedInformation()) {
  45070. lightPosition = this._light.transformedPosition;
  45071. }
  45072. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  45073. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  45074. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  45075. }
  45076. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  45077. this._cachedPosition = lightPosition.clone();
  45078. this._cachedDirection = this._lightDirection.clone();
  45079. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  45080. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  45081. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  45082. }
  45083. return this._transformMatrix;
  45084. };
  45085. ShadowGenerator.prototype.recreateShadowMap = function () {
  45086. // Track render list.
  45087. var renderList = this._shadowMap.renderList;
  45088. // Clean up existing data.
  45089. this._disposeRTTandPostProcesses();
  45090. // Reinitializes.
  45091. this._initializeGenerator();
  45092. // Reaffect the filter to ensure a correct fallback if necessary.
  45093. this.filter = this.filter;
  45094. // Reaffect the filter.
  45095. this._applyFilterValues();
  45096. // Reaffect Render List.
  45097. this._shadowMap.renderList = renderList;
  45098. };
  45099. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  45100. if (this._shadowMap2) {
  45101. this._shadowMap2.dispose();
  45102. this._shadowMap2 = null;
  45103. }
  45104. if (this._downSamplePostprocess) {
  45105. this._downSamplePostprocess.dispose();
  45106. this._downSamplePostprocess = null;
  45107. }
  45108. if (this._boxBlurPostprocess) {
  45109. this._boxBlurPostprocess.dispose();
  45110. this._boxBlurPostprocess = null;
  45111. }
  45112. if (this._kernelBlurXPostprocess) {
  45113. this._kernelBlurXPostprocess.dispose();
  45114. this._kernelBlurXPostprocess = null;
  45115. }
  45116. if (this._kernelBlurYPostprocess) {
  45117. this._kernelBlurYPostprocess.dispose();
  45118. this._kernelBlurYPostprocess = null;
  45119. }
  45120. this._blurPostProcesses = null;
  45121. };
  45122. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  45123. if (this._shadowMap) {
  45124. this._shadowMap.dispose();
  45125. this._shadowMap = null;
  45126. }
  45127. this._disposeBlurPostProcesses();
  45128. };
  45129. /**
  45130. * Disposes the ShadowGenerator.
  45131. * Returns nothing.
  45132. */
  45133. ShadowGenerator.prototype.dispose = function () {
  45134. this._disposeRTTandPostProcesses();
  45135. this._light._shadowGenerator = null;
  45136. this._light._markMeshesAsLightDirty();
  45137. };
  45138. /**
  45139. * Serializes the ShadowGenerator and returns a serializationObject.
  45140. */
  45141. ShadowGenerator.prototype.serialize = function () {
  45142. var serializationObject = {};
  45143. var shadowMap = this.getShadowMap();
  45144. serializationObject.lightId = this._light.id;
  45145. serializationObject.mapSize = shadowMap.getRenderSize();
  45146. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  45147. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  45148. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  45149. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  45150. serializationObject.usePoissonSampling = this.usePoissonSampling;
  45151. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  45152. serializationObject.depthScale = this.depthScale;
  45153. serializationObject.darkness = this.getDarkness();
  45154. serializationObject.blurBoxOffset = this.blurBoxOffset;
  45155. serializationObject.blurKernel = this.blurKernel;
  45156. serializationObject.blurScale = this.blurScale;
  45157. serializationObject.useKernelBlur = this.useKernelBlur;
  45158. serializationObject.transparencyShadow = this._transparencyShadow;
  45159. serializationObject.renderList = [];
  45160. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  45161. var mesh = shadowMap.renderList[meshIndex];
  45162. serializationObject.renderList.push(mesh.id);
  45163. }
  45164. return serializationObject;
  45165. };
  45166. /**
  45167. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  45168. */
  45169. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  45170. //casting to point light, as light is missing the position attr and typescript complains.
  45171. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  45172. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  45173. var shadowMap = shadowGenerator.getShadowMap();
  45174. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  45175. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  45176. meshes.forEach(function (mesh) {
  45177. shadowMap.renderList.push(mesh);
  45178. });
  45179. }
  45180. if (parsedShadowGenerator.usePoissonSampling) {
  45181. shadowGenerator.usePoissonSampling = true;
  45182. }
  45183. else if (parsedShadowGenerator.useExponentialShadowMap) {
  45184. shadowGenerator.useExponentialShadowMap = true;
  45185. }
  45186. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  45187. shadowGenerator.useBlurExponentialShadowMap = true;
  45188. }
  45189. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  45190. shadowGenerator.useCloseExponentialShadowMap = true;
  45191. }
  45192. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  45193. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  45194. }
  45195. else if (parsedShadowGenerator.useVarianceShadowMap) {
  45196. shadowGenerator.useExponentialShadowMap = true;
  45197. }
  45198. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  45199. shadowGenerator.useBlurExponentialShadowMap = true;
  45200. }
  45201. if (parsedShadowGenerator.depthScale) {
  45202. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  45203. }
  45204. if (parsedShadowGenerator.blurScale) {
  45205. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  45206. }
  45207. if (parsedShadowGenerator.blurBoxOffset) {
  45208. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  45209. }
  45210. if (parsedShadowGenerator.useKernelBlur) {
  45211. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  45212. }
  45213. if (parsedShadowGenerator.blurKernel) {
  45214. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  45215. }
  45216. if (parsedShadowGenerator.bias !== undefined) {
  45217. shadowGenerator.bias = parsedShadowGenerator.bias;
  45218. }
  45219. if (parsedShadowGenerator.darkness) {
  45220. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  45221. }
  45222. if (parsedShadowGenerator.transparencyShadow) {
  45223. shadowGenerator.setTransparencyShadow(true);
  45224. }
  45225. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  45226. return shadowGenerator;
  45227. };
  45228. return ShadowGenerator;
  45229. }());
  45230. ShadowGenerator._FILTER_NONE = 0;
  45231. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  45232. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  45233. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  45234. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  45235. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  45236. BABYLON.ShadowGenerator = ShadowGenerator;
  45237. })(BABYLON || (BABYLON = {}));
  45238. //# sourceMappingURL=babylon.shadowGenerator.js.map
  45239. var BABYLON;
  45240. (function (BABYLON) {
  45241. var DefaultLoadingScreen = (function () {
  45242. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  45243. if (_loadingText === void 0) { _loadingText = ""; }
  45244. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  45245. var _this = this;
  45246. this._renderingCanvas = _renderingCanvas;
  45247. this._loadingText = _loadingText;
  45248. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  45249. // Resize
  45250. this._resizeLoadingUI = function () {
  45251. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  45252. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  45253. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  45254. _this._loadingDiv.style.left = canvasRect.left + "px";
  45255. _this._loadingDiv.style.top = canvasRect.top + "px";
  45256. _this._loadingDiv.style.width = canvasRect.width + "px";
  45257. _this._loadingDiv.style.height = canvasRect.height + "px";
  45258. };
  45259. }
  45260. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  45261. if (this._loadingDiv) {
  45262. // Do not add a loading screen if there is already one
  45263. return;
  45264. }
  45265. this._loadingDiv = document.createElement("div");
  45266. this._loadingDiv.id = "babylonjsLoadingDiv";
  45267. this._loadingDiv.style.opacity = "0";
  45268. this._loadingDiv.style.transition = "opacity 1.5s ease";
  45269. // Loading text
  45270. this._loadingTextDiv = document.createElement("div");
  45271. this._loadingTextDiv.style.position = "absolute";
  45272. this._loadingTextDiv.style.left = "0";
  45273. this._loadingTextDiv.style.top = "50%";
  45274. this._loadingTextDiv.style.marginTop = "80px";
  45275. this._loadingTextDiv.style.width = "100%";
  45276. this._loadingTextDiv.style.height = "20px";
  45277. this._loadingTextDiv.style.fontFamily = "Arial";
  45278. this._loadingTextDiv.style.fontSize = "14px";
  45279. this._loadingTextDiv.style.color = "white";
  45280. this._loadingTextDiv.style.textAlign = "center";
  45281. this._loadingTextDiv.innerHTML = "Loading";
  45282. this._loadingDiv.appendChild(this._loadingTextDiv);
  45283. //set the predefined text
  45284. this._loadingTextDiv.innerHTML = this._loadingText;
  45285. // Generating keyframes
  45286. var style = document.createElement('style');
  45287. style.type = 'text/css';
  45288. 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 }";
  45289. style.innerHTML = keyFrames;
  45290. document.getElementsByTagName('head')[0].appendChild(style);
  45291. // Loading img
  45292. var imgBack = new Image();
  45293. 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";
  45294. imgBack.style.position = "absolute";
  45295. imgBack.style.left = "50%";
  45296. imgBack.style.top = "50%";
  45297. imgBack.style.marginLeft = "-50px";
  45298. imgBack.style.marginTop = "-50px";
  45299. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  45300. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  45301. imgBack.style.transformOrigin = "50% 50%";
  45302. imgBack.style.webkitTransformOrigin = "50% 50%";
  45303. this._loadingDiv.appendChild(imgBack);
  45304. this._resizeLoadingUI();
  45305. window.addEventListener("resize", this._resizeLoadingUI);
  45306. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  45307. document.body.appendChild(this._loadingDiv);
  45308. this._loadingDiv.style.opacity = "1";
  45309. };
  45310. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  45311. var _this = this;
  45312. if (!this._loadingDiv) {
  45313. return;
  45314. }
  45315. var onTransitionEnd = function () {
  45316. if (!_this._loadingDiv) {
  45317. return;
  45318. }
  45319. document.body.removeChild(_this._loadingDiv);
  45320. window.removeEventListener("resize", _this._resizeLoadingUI);
  45321. _this._loadingDiv = null;
  45322. };
  45323. this._loadingDiv.style.opacity = "0";
  45324. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  45325. };
  45326. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  45327. set: function (text) {
  45328. this._loadingText = text;
  45329. if (this._loadingTextDiv) {
  45330. this._loadingTextDiv.innerHTML = this._loadingText;
  45331. }
  45332. },
  45333. enumerable: true,
  45334. configurable: true
  45335. });
  45336. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  45337. get: function () {
  45338. return this._loadingDivBackgroundColor;
  45339. },
  45340. set: function (color) {
  45341. this._loadingDivBackgroundColor = color;
  45342. if (!this._loadingDiv) {
  45343. return;
  45344. }
  45345. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  45346. },
  45347. enumerable: true,
  45348. configurable: true
  45349. });
  45350. return DefaultLoadingScreen;
  45351. }());
  45352. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  45353. })(BABYLON || (BABYLON = {}));
  45354. //# sourceMappingURL=babylon.loadingScreen.js.map
  45355. var BABYLON;
  45356. (function (BABYLON) {
  45357. var SceneLoader = (function () {
  45358. function SceneLoader() {
  45359. }
  45360. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  45361. get: function () {
  45362. return 0;
  45363. },
  45364. enumerable: true,
  45365. configurable: true
  45366. });
  45367. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  45368. get: function () {
  45369. return 1;
  45370. },
  45371. enumerable: true,
  45372. configurable: true
  45373. });
  45374. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  45375. get: function () {
  45376. return 2;
  45377. },
  45378. enumerable: true,
  45379. configurable: true
  45380. });
  45381. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  45382. get: function () {
  45383. return 3;
  45384. },
  45385. enumerable: true,
  45386. configurable: true
  45387. });
  45388. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  45389. get: function () {
  45390. return SceneLoader._ForceFullSceneLoadingForIncremental;
  45391. },
  45392. set: function (value) {
  45393. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  45394. },
  45395. enumerable: true,
  45396. configurable: true
  45397. });
  45398. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  45399. get: function () {
  45400. return SceneLoader._ShowLoadingScreen;
  45401. },
  45402. set: function (value) {
  45403. SceneLoader._ShowLoadingScreen = value;
  45404. },
  45405. enumerable: true,
  45406. configurable: true
  45407. });
  45408. Object.defineProperty(SceneLoader, "loggingLevel", {
  45409. get: function () {
  45410. return SceneLoader._loggingLevel;
  45411. },
  45412. set: function (value) {
  45413. SceneLoader._loggingLevel = value;
  45414. },
  45415. enumerable: true,
  45416. configurable: true
  45417. });
  45418. SceneLoader._getDefaultPlugin = function () {
  45419. return SceneLoader._registeredPlugins[".babylon"];
  45420. };
  45421. SceneLoader._getPluginForExtension = function (extension) {
  45422. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  45423. if (registeredPlugin) {
  45424. return registeredPlugin;
  45425. }
  45426. return SceneLoader._getDefaultPlugin();
  45427. };
  45428. SceneLoader._getPluginForDirectLoad = function (data) {
  45429. for (var extension in SceneLoader._registeredPlugins) {
  45430. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  45431. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  45432. return SceneLoader._registeredPlugins[extension];
  45433. }
  45434. }
  45435. return SceneLoader._getDefaultPlugin();
  45436. };
  45437. SceneLoader._getPluginForFilename = function (sceneFilename) {
  45438. if (sceneFilename.name) {
  45439. sceneFilename = sceneFilename.name;
  45440. }
  45441. var dotPosition = sceneFilename.lastIndexOf(".");
  45442. var queryStringPosition = sceneFilename.indexOf("?");
  45443. if (queryStringPosition === -1) {
  45444. queryStringPosition = sceneFilename.length;
  45445. }
  45446. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  45447. return SceneLoader._getPluginForExtension(extension);
  45448. };
  45449. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  45450. SceneLoader._getDirectLoad = function (sceneFilename) {
  45451. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  45452. return sceneFilename.substr(5);
  45453. }
  45454. return null;
  45455. };
  45456. // Public functions
  45457. SceneLoader.GetPluginForExtension = function (extension) {
  45458. return SceneLoader._getPluginForExtension(extension).plugin;
  45459. };
  45460. SceneLoader.RegisterPlugin = function (plugin) {
  45461. if (typeof plugin.extensions === "string") {
  45462. var extension = plugin.extensions;
  45463. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  45464. plugin: plugin,
  45465. isBinary: false
  45466. };
  45467. }
  45468. else {
  45469. var extensions = plugin.extensions;
  45470. Object.keys(extensions).forEach(function (extension) {
  45471. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  45472. plugin: plugin,
  45473. isBinary: extensions[extension].isBinary
  45474. };
  45475. });
  45476. }
  45477. };
  45478. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  45479. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  45480. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  45481. return;
  45482. }
  45483. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  45484. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  45485. return;
  45486. }
  45487. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  45488. var loadingToken = {};
  45489. scene._addPendingData(loadingToken);
  45490. var manifestChecked = function (success) {
  45491. scene.database = database;
  45492. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  45493. var plugin = registeredPlugin.plugin;
  45494. var useArrayBuffer = registeredPlugin.isBinary;
  45495. var importMeshFromData = function (data) {
  45496. var meshes = [];
  45497. var particleSystems = [];
  45498. var skeletons = [];
  45499. if (scene.isDisposed) {
  45500. if (onerror) {
  45501. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  45502. }
  45503. return;
  45504. }
  45505. try {
  45506. if (plugin.importMesh) {
  45507. var syncedPlugin = plugin;
  45508. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  45509. if (onerror) {
  45510. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  45511. }
  45512. scene._removePendingData(loadingToken);
  45513. return;
  45514. }
  45515. if (onsuccess) {
  45516. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  45517. onsuccess(meshes, particleSystems, skeletons);
  45518. scene._removePendingData(loadingToken);
  45519. }
  45520. }
  45521. else {
  45522. var asyncedPlugin = plugin;
  45523. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  45524. if (onsuccess) {
  45525. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  45526. onsuccess(meshes, particleSystems, skeletons);
  45527. scene._removePendingData(loadingToken);
  45528. }
  45529. }, function () {
  45530. if (onerror) {
  45531. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  45532. }
  45533. scene._removePendingData(loadingToken);
  45534. });
  45535. }
  45536. }
  45537. catch (e) {
  45538. if (onerror) {
  45539. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  45540. }
  45541. scene._removePendingData(loadingToken);
  45542. }
  45543. };
  45544. if (directLoad) {
  45545. importMeshFromData(directLoad);
  45546. return;
  45547. }
  45548. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  45549. importMeshFromData(data);
  45550. }, progressCallBack, database, useArrayBuffer, function () {
  45551. if (onerror) {
  45552. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  45553. }
  45554. });
  45555. };
  45556. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  45557. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  45558. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  45559. }
  45560. else {
  45561. // If the scene is a data stream or offline support is not enabled, it's a direct load
  45562. manifestChecked(true);
  45563. }
  45564. };
  45565. /**
  45566. * Load a scene
  45567. * @param rootUrl a string that defines the root url for scene and resources
  45568. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  45569. * @param engine is the instance of BABYLON.Engine to use to create the scene
  45570. */
  45571. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  45572. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  45573. };
  45574. /**
  45575. * Append 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 scene is the instance of BABYLON.Scene to append to
  45579. */
  45580. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  45581. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  45582. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  45583. return;
  45584. }
  45585. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  45586. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  45587. var plugin = registeredPlugin.plugin;
  45588. var useArrayBuffer = registeredPlugin.isBinary;
  45589. var database;
  45590. var loadingToken = {};
  45591. scene._addPendingData(loadingToken);
  45592. if (SceneLoader.ShowLoadingScreen) {
  45593. scene.getEngine().displayLoadingUI();
  45594. }
  45595. var loadSceneFromData = function (data) {
  45596. scene.database = database;
  45597. if (plugin.load) {
  45598. var syncedPlugin = plugin;
  45599. if (!syncedPlugin.load(scene, data, rootUrl)) {
  45600. if (onerror) {
  45601. onerror(scene);
  45602. }
  45603. scene._removePendingData(loadingToken);
  45604. scene.getEngine().hideLoadingUI();
  45605. return;
  45606. }
  45607. if (onsuccess) {
  45608. onsuccess(scene);
  45609. }
  45610. scene._removePendingData(loadingToken);
  45611. }
  45612. else {
  45613. var asyncedPlugin = plugin;
  45614. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  45615. if (onsuccess) {
  45616. onsuccess(scene);
  45617. }
  45618. scene._removePendingData(loadingToken);
  45619. }, function () {
  45620. if (onerror) {
  45621. onerror(scene);
  45622. }
  45623. scene._removePendingData(loadingToken);
  45624. scene.getEngine().hideLoadingUI();
  45625. });
  45626. }
  45627. if (SceneLoader.ShowLoadingScreen) {
  45628. scene.executeWhenReady(function () {
  45629. scene.getEngine().hideLoadingUI();
  45630. });
  45631. }
  45632. };
  45633. var manifestChecked = function (success) {
  45634. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  45635. };
  45636. if (directLoad) {
  45637. loadSceneFromData(directLoad);
  45638. return;
  45639. }
  45640. if (rootUrl.indexOf("file:") === -1) {
  45641. if (scene.getEngine().enableOfflineSupport) {
  45642. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  45643. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  45644. }
  45645. else {
  45646. manifestChecked(true);
  45647. }
  45648. }
  45649. else {
  45650. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  45651. }
  45652. };
  45653. return SceneLoader;
  45654. }());
  45655. // Flags
  45656. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  45657. SceneLoader._ShowLoadingScreen = true;
  45658. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  45659. // Members
  45660. SceneLoader._registeredPlugins = {};
  45661. BABYLON.SceneLoader = SceneLoader;
  45662. ;
  45663. })(BABYLON || (BABYLON = {}));
  45664. //# sourceMappingURL=babylon.sceneLoader.js.map
  45665. var BABYLON;
  45666. (function (BABYLON) {
  45667. var Internals;
  45668. (function (Internals) {
  45669. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  45670. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  45671. var parsedMaterial = parsedData.materials[index];
  45672. if (parsedMaterial.id === id) {
  45673. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  45674. }
  45675. }
  45676. return null;
  45677. };
  45678. var isDescendantOf = function (mesh, names, hierarchyIds) {
  45679. names = (names instanceof Array) ? names : [names];
  45680. for (var i in names) {
  45681. if (mesh.name === names[i]) {
  45682. hierarchyIds.push(mesh.id);
  45683. return true;
  45684. }
  45685. }
  45686. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  45687. hierarchyIds.push(mesh.id);
  45688. return true;
  45689. }
  45690. return false;
  45691. };
  45692. var logOperation = function (operation, producer) {
  45693. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  45694. };
  45695. BABYLON.SceneLoader.RegisterPlugin({
  45696. extensions: ".babylon",
  45697. canDirectLoad: function (data) {
  45698. if (data.indexOf("babylon") !== -1) {
  45699. return true;
  45700. }
  45701. return false;
  45702. },
  45703. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  45704. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  45705. // when SceneLoader.debugLogging = true (default), or exception encountered.
  45706. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  45707. // and avoid problems with multiple concurrent .babylon loads.
  45708. var log = "importMesh has failed JSON parse";
  45709. try {
  45710. var parsedData = JSON.parse(data);
  45711. log = "";
  45712. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  45713. var loadedSkeletonsIds = [];
  45714. var loadedMaterialsIds = [];
  45715. var hierarchyIds = [];
  45716. var index;
  45717. var cache;
  45718. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  45719. var parsedMesh = parsedData.meshes[index];
  45720. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  45721. if (meshesNames instanceof Array) {
  45722. // Remove found mesh name from list.
  45723. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  45724. }
  45725. //Geometry?
  45726. if (parsedMesh.geometryId) {
  45727. //does the file contain geometries?
  45728. if (parsedData.geometries) {
  45729. //find the correct geometry and add it to the scene
  45730. var found = false;
  45731. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  45732. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  45733. return;
  45734. }
  45735. else {
  45736. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  45737. if (parsedGeometryData.id === parsedMesh.geometryId) {
  45738. switch (geometryType) {
  45739. case "boxes":
  45740. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  45741. break;
  45742. case "spheres":
  45743. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  45744. break;
  45745. case "cylinders":
  45746. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  45747. break;
  45748. case "toruses":
  45749. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  45750. break;
  45751. case "grounds":
  45752. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  45753. break;
  45754. case "planes":
  45755. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  45756. break;
  45757. case "torusKnots":
  45758. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  45759. break;
  45760. case "vertexData":
  45761. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  45762. break;
  45763. }
  45764. found = true;
  45765. }
  45766. });
  45767. }
  45768. });
  45769. if (!found) {
  45770. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  45771. }
  45772. }
  45773. }
  45774. // Material ?
  45775. if (parsedMesh.materialId) {
  45776. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  45777. if (!materialFound && parsedData.multiMaterials) {
  45778. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  45779. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  45780. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  45781. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  45782. var subMatId = parsedMultiMaterial.materials[matIndex];
  45783. loadedMaterialsIds.push(subMatId);
  45784. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  45785. log += "\n\tMaterial " + mat.toString(fullDetails);
  45786. }
  45787. loadedMaterialsIds.push(parsedMultiMaterial.id);
  45788. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45789. materialFound = true;
  45790. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  45791. break;
  45792. }
  45793. }
  45794. }
  45795. if (!materialFound) {
  45796. loadedMaterialsIds.push(parsedMesh.materialId);
  45797. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  45798. if (!mat) {
  45799. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  45800. }
  45801. else {
  45802. log += "\n\tMaterial " + mat.toString(fullDetails);
  45803. }
  45804. }
  45805. }
  45806. // Skeleton ?
  45807. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  45808. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  45809. if (!skeletonAlreadyLoaded) {
  45810. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  45811. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  45812. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  45813. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45814. skeletons.push(skeleton);
  45815. loadedSkeletonsIds.push(parsedSkeleton.id);
  45816. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  45817. }
  45818. }
  45819. }
  45820. }
  45821. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  45822. meshes.push(mesh);
  45823. log += "\n\tMesh " + mesh.toString(fullDetails);
  45824. }
  45825. }
  45826. // Connecting parents
  45827. var currentMesh;
  45828. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45829. currentMesh = scene.meshes[index];
  45830. if (currentMesh._waitingParentId) {
  45831. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  45832. currentMesh._waitingParentId = undefined;
  45833. }
  45834. }
  45835. // freeze and compute world matrix application
  45836. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45837. currentMesh = scene.meshes[index];
  45838. if (currentMesh._waitingFreezeWorldMatrix) {
  45839. currentMesh.freezeWorldMatrix();
  45840. currentMesh._waitingFreezeWorldMatrix = undefined;
  45841. }
  45842. else {
  45843. currentMesh.computeWorldMatrix(true);
  45844. }
  45845. }
  45846. // Particles
  45847. if (parsedData.particleSystems) {
  45848. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  45849. var parsedParticleSystem = parsedData.particleSystems[index];
  45850. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  45851. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  45852. }
  45853. }
  45854. }
  45855. return true;
  45856. }
  45857. catch (err) {
  45858. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  45859. log = null;
  45860. throw err;
  45861. }
  45862. finally {
  45863. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  45864. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  45865. }
  45866. }
  45867. },
  45868. load: function (scene, data, rootUrl) {
  45869. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  45870. // when SceneLoader.debugLogging = true (default), or exception encountered.
  45871. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  45872. // and avoid problems with multiple concurrent .babylon loads.
  45873. var log = "importScene has failed JSON parse";
  45874. try {
  45875. var parsedData = JSON.parse(data);
  45876. log = "";
  45877. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  45878. // Scene
  45879. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  45880. scene.autoClear = parsedData.autoClear;
  45881. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  45882. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  45883. if (parsedData.gravity) {
  45884. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  45885. }
  45886. // Fog
  45887. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  45888. scene.fogMode = parsedData.fogMode;
  45889. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  45890. scene.fogStart = parsedData.fogStart;
  45891. scene.fogEnd = parsedData.fogEnd;
  45892. scene.fogDensity = parsedData.fogDensity;
  45893. log += "\tFog mode for scene: ";
  45894. switch (scene.fogMode) {
  45895. // getters not compiling, so using hardcoded
  45896. case 1:
  45897. log += "exp\n";
  45898. break;
  45899. case 2:
  45900. log += "exp2\n";
  45901. break;
  45902. case 3:
  45903. log += "linear\n";
  45904. break;
  45905. }
  45906. }
  45907. //Physics
  45908. if (parsedData.physicsEnabled) {
  45909. var physicsPlugin;
  45910. if (parsedData.physicsEngine === "cannon") {
  45911. physicsPlugin = new BABYLON.CannonJSPlugin();
  45912. }
  45913. else if (parsedData.physicsEngine === "oimo") {
  45914. physicsPlugin = new BABYLON.OimoJSPlugin();
  45915. }
  45916. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  45917. //else - default engine, which is currently oimo
  45918. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  45919. scene.enablePhysics(physicsGravity, physicsPlugin);
  45920. }
  45921. // Metadata
  45922. if (parsedData.metadata !== undefined) {
  45923. scene.metadata = parsedData.metadata;
  45924. }
  45925. //collisions, if defined. otherwise, default is true
  45926. if (parsedData.collisionsEnabled != undefined) {
  45927. scene.collisionsEnabled = parsedData.collisionsEnabled;
  45928. }
  45929. scene.workerCollisions = !!parsedData.workerCollisions;
  45930. var index;
  45931. var cache;
  45932. // Lights
  45933. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  45934. var parsedLight = parsedData.lights[index];
  45935. var light = BABYLON.Light.Parse(parsedLight, scene);
  45936. log += (index === 0 ? "\n\tLights:" : "");
  45937. log += "\n\t\t" + light.toString(fullDetails);
  45938. }
  45939. // Animations
  45940. if (parsedData.animations) {
  45941. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  45942. var parsedAnimation = parsedData.animations[index];
  45943. var animation = BABYLON.Animation.Parse(parsedAnimation);
  45944. scene.animations.push(animation);
  45945. log += (index === 0 ? "\n\tAnimations:" : "");
  45946. log += "\n\t\t" + animation.toString(fullDetails);
  45947. }
  45948. }
  45949. if (parsedData.autoAnimate) {
  45950. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  45951. }
  45952. // Materials
  45953. if (parsedData.materials) {
  45954. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  45955. var parsedMaterial = parsedData.materials[index];
  45956. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  45957. log += (index === 0 ? "\n\tMaterials:" : "");
  45958. log += "\n\t\t" + mat.toString(fullDetails);
  45959. }
  45960. }
  45961. if (parsedData.multiMaterials) {
  45962. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  45963. var parsedMultiMaterial = parsedData.multiMaterials[index];
  45964. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45965. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  45966. log += "\n\t\t" + mmat.toString(fullDetails);
  45967. }
  45968. }
  45969. // Morph targets
  45970. if (parsedData.morphTargetManagers) {
  45971. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  45972. var managerData = _a[_i];
  45973. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  45974. }
  45975. }
  45976. // Skeletons
  45977. if (parsedData.skeletons) {
  45978. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  45979. var parsedSkeleton = parsedData.skeletons[index];
  45980. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45981. log += (index === 0 ? "\n\tSkeletons:" : "");
  45982. log += "\n\t\t" + skeleton.toString(fullDetails);
  45983. }
  45984. }
  45985. // Geometries
  45986. var geometries = parsedData.geometries;
  45987. if (geometries) {
  45988. // Boxes
  45989. var boxes = geometries.boxes;
  45990. if (boxes) {
  45991. for (index = 0, cache = boxes.length; index < cache; index++) {
  45992. var parsedBox = boxes[index];
  45993. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  45994. }
  45995. }
  45996. // Spheres
  45997. var spheres = geometries.spheres;
  45998. if (spheres) {
  45999. for (index = 0, cache = spheres.length; index < cache; index++) {
  46000. var parsedSphere = spheres[index];
  46001. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  46002. }
  46003. }
  46004. // Cylinders
  46005. var cylinders = geometries.cylinders;
  46006. if (cylinders) {
  46007. for (index = 0, cache = cylinders.length; index < cache; index++) {
  46008. var parsedCylinder = cylinders[index];
  46009. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  46010. }
  46011. }
  46012. // Toruses
  46013. var toruses = geometries.toruses;
  46014. if (toruses) {
  46015. for (index = 0, cache = toruses.length; index < cache; index++) {
  46016. var parsedTorus = toruses[index];
  46017. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  46018. }
  46019. }
  46020. // Grounds
  46021. var grounds = geometries.grounds;
  46022. if (grounds) {
  46023. for (index = 0, cache = grounds.length; index < cache; index++) {
  46024. var parsedGround = grounds[index];
  46025. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  46026. }
  46027. }
  46028. // Planes
  46029. var planes = geometries.planes;
  46030. if (planes) {
  46031. for (index = 0, cache = planes.length; index < cache; index++) {
  46032. var parsedPlane = planes[index];
  46033. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  46034. }
  46035. }
  46036. // TorusKnots
  46037. var torusKnots = geometries.torusKnots;
  46038. if (torusKnots) {
  46039. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  46040. var parsedTorusKnot = torusKnots[index];
  46041. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  46042. }
  46043. }
  46044. // VertexData
  46045. var vertexData = geometries.vertexData;
  46046. if (vertexData) {
  46047. for (index = 0, cache = vertexData.length; index < cache; index++) {
  46048. var parsedVertexData = vertexData[index];
  46049. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  46050. }
  46051. }
  46052. }
  46053. // Meshes
  46054. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  46055. var parsedMesh = parsedData.meshes[index];
  46056. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  46057. log += (index === 0 ? "\n\tMeshes:" : "");
  46058. log += "\n\t\t" + mesh.toString(fullDetails);
  46059. }
  46060. // Cameras
  46061. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  46062. var parsedCamera = parsedData.cameras[index];
  46063. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  46064. log += (index === 0 ? "\n\tCameras:" : "");
  46065. log += "\n\t\t" + camera.toString(fullDetails);
  46066. }
  46067. if (parsedData.activeCameraID) {
  46068. scene.setActiveCameraByID(parsedData.activeCameraID);
  46069. }
  46070. // Browsing all the graph to connect the dots
  46071. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  46072. var camera = scene.cameras[index];
  46073. if (camera._waitingParentId) {
  46074. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  46075. camera._waitingParentId = undefined;
  46076. }
  46077. }
  46078. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  46079. var light = scene.lights[index];
  46080. if (light._waitingParentId) {
  46081. light.parent = scene.getLastEntryByID(light._waitingParentId);
  46082. light._waitingParentId = undefined;
  46083. }
  46084. }
  46085. // Sounds
  46086. var loadedSounds = [];
  46087. var loadedSound;
  46088. if (BABYLON.AudioEngine && parsedData.sounds) {
  46089. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  46090. var parsedSound = parsedData.sounds[index];
  46091. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46092. if (!parsedSound.url)
  46093. parsedSound.url = parsedSound.name;
  46094. if (!loadedSounds[parsedSound.url]) {
  46095. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  46096. loadedSounds[parsedSound.url] = loadedSound;
  46097. }
  46098. else {
  46099. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  46100. }
  46101. }
  46102. else {
  46103. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  46104. }
  46105. }
  46106. }
  46107. loadedSounds = [];
  46108. // Connect parents & children and parse actions
  46109. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  46110. var mesh = scene.meshes[index];
  46111. if (mesh._waitingParentId) {
  46112. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  46113. mesh._waitingParentId = undefined;
  46114. }
  46115. if (mesh._waitingActions) {
  46116. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  46117. mesh._waitingActions = undefined;
  46118. }
  46119. }
  46120. // freeze world matrix application
  46121. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  46122. var currentMesh = scene.meshes[index];
  46123. if (currentMesh._waitingFreezeWorldMatrix) {
  46124. currentMesh.freezeWorldMatrix();
  46125. currentMesh._waitingFreezeWorldMatrix = undefined;
  46126. }
  46127. else {
  46128. currentMesh.computeWorldMatrix(true);
  46129. }
  46130. }
  46131. // Particles Systems
  46132. if (parsedData.particleSystems) {
  46133. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  46134. var parsedParticleSystem = parsedData.particleSystems[index];
  46135. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  46136. }
  46137. }
  46138. // Lens flares
  46139. if (parsedData.lensFlareSystems) {
  46140. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  46141. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  46142. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  46143. }
  46144. }
  46145. // Shadows
  46146. if (parsedData.shadowGenerators) {
  46147. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  46148. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  46149. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  46150. }
  46151. }
  46152. // Lights exclusions / inclusions
  46153. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  46154. var light = scene.lights[index];
  46155. // Excluded check
  46156. if (light._excludedMeshesIds.length > 0) {
  46157. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  46158. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  46159. if (excludedMesh) {
  46160. light.excludedMeshes.push(excludedMesh);
  46161. }
  46162. }
  46163. light._excludedMeshesIds = [];
  46164. }
  46165. // Included check
  46166. if (light._includedOnlyMeshesIds.length > 0) {
  46167. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  46168. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  46169. if (includedOnlyMesh) {
  46170. light.includedOnlyMeshes.push(includedOnlyMesh);
  46171. }
  46172. }
  46173. light._includedOnlyMeshesIds = [];
  46174. }
  46175. }
  46176. // Actions (scene)
  46177. if (parsedData.actions) {
  46178. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  46179. }
  46180. // Finish
  46181. return true;
  46182. }
  46183. catch (err) {
  46184. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  46185. log = null;
  46186. throw err;
  46187. }
  46188. finally {
  46189. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  46190. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  46191. }
  46192. }
  46193. }
  46194. });
  46195. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46196. })(BABYLON || (BABYLON = {}));
  46197. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  46198. var BABYLON;
  46199. (function (BABYLON) {
  46200. var FilesInput = (function () {
  46201. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  46202. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  46203. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  46204. this._engine = p_engine;
  46205. this._canvas = p_canvas;
  46206. this._currentScene = p_scene;
  46207. this._sceneLoadedCallback = p_sceneLoadedCallback;
  46208. this._progressCallback = p_progressCallback;
  46209. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  46210. this._textureLoadingCallback = p_textureLoadingCallback;
  46211. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  46212. }
  46213. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  46214. var _this = this;
  46215. if (p_elementToMonitor) {
  46216. this._elementToMonitor = p_elementToMonitor;
  46217. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  46218. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  46219. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  46220. }
  46221. };
  46222. FilesInput.prototype.renderFunction = function () {
  46223. if (this._additionnalRenderLoopLogicCallback) {
  46224. this._additionnalRenderLoopLogicCallback();
  46225. }
  46226. if (this._currentScene) {
  46227. if (this._textureLoadingCallback) {
  46228. var remaining = this._currentScene.getWaitingItemsCount();
  46229. if (remaining > 0) {
  46230. this._textureLoadingCallback(remaining);
  46231. }
  46232. }
  46233. this._currentScene.render();
  46234. }
  46235. };
  46236. FilesInput.prototype.drag = function (e) {
  46237. e.stopPropagation();
  46238. e.preventDefault();
  46239. };
  46240. FilesInput.prototype.drop = function (eventDrop) {
  46241. eventDrop.stopPropagation();
  46242. eventDrop.preventDefault();
  46243. this.loadFiles(eventDrop);
  46244. };
  46245. FilesInput.prototype.loadFiles = function (event) {
  46246. if (this._startingProcessingFilesCallback)
  46247. this._startingProcessingFilesCallback();
  46248. // Handling data transfer via drag'n'drop
  46249. if (event && event.dataTransfer && event.dataTransfer.files) {
  46250. this._filesToLoad = event.dataTransfer.files;
  46251. }
  46252. // Handling files from input files
  46253. if (event && event.target && event.target.files) {
  46254. this._filesToLoad = event.target.files;
  46255. }
  46256. if (this._filesToLoad && this._filesToLoad.length > 0) {
  46257. for (var i = 0; i < this._filesToLoad.length; i++) {
  46258. var name_1 = this._filesToLoad[i].name.toLowerCase();
  46259. var extension = name_1.split('.').pop();
  46260. var type = this._filesToLoad[i].type;
  46261. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  46262. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  46263. this._sceneFileToLoad = this._filesToLoad[i];
  46264. }
  46265. else {
  46266. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  46267. }
  46268. }
  46269. this.reload();
  46270. }
  46271. };
  46272. FilesInput.prototype.reload = function () {
  46273. var _this = this;
  46274. var that = this;
  46275. // If a ".babylon" file has been provided
  46276. if (this._sceneFileToLoad) {
  46277. if (this._currentScene) {
  46278. if (BABYLON.Tools.errorsCount > 0) {
  46279. BABYLON.Tools.ClearLogCache();
  46280. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  46281. }
  46282. this._engine.stopRenderLoop();
  46283. this._currentScene.dispose();
  46284. }
  46285. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  46286. that._currentScene = newScene;
  46287. // Wait for textures and shaders to be ready
  46288. that._currentScene.executeWhenReady(function () {
  46289. if (that._sceneLoadedCallback) {
  46290. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  46291. }
  46292. that._engine.runRenderLoop(function () { that.renderFunction(); });
  46293. });
  46294. }, function (progress) {
  46295. if (_this._progressCallback) {
  46296. _this._progressCallback(progress);
  46297. }
  46298. });
  46299. }
  46300. else {
  46301. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  46302. }
  46303. };
  46304. return FilesInput;
  46305. }());
  46306. FilesInput.FilesToLoad = new Array();
  46307. BABYLON.FilesInput = FilesInput;
  46308. })(BABYLON || (BABYLON = {}));
  46309. //# sourceMappingURL=babylon.filesInput.js.map
  46310. var BABYLON;
  46311. (function (BABYLON) {
  46312. /**
  46313. * This class implement a typical dictionary using a string as key and the generic type T as value.
  46314. * The underlying implementation relies on an associative array to ensure the best performances.
  46315. * The value can be anything including 'null' but except 'undefined'
  46316. */
  46317. var StringDictionary = (function () {
  46318. function StringDictionary() {
  46319. this._count = 0;
  46320. this._data = {};
  46321. }
  46322. /**
  46323. * This will clear this dictionary and copy the content from the 'source' one.
  46324. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  46325. * @param source the dictionary to take the content from and copy to this dictionary
  46326. */
  46327. StringDictionary.prototype.copyFrom = function (source) {
  46328. var _this = this;
  46329. this.clear();
  46330. source.forEach(function (t, v) { return _this.add(t, v); });
  46331. };
  46332. /**
  46333. * Get a value based from its key
  46334. * @param key the given key to get the matching value from
  46335. * @return the value if found, otherwise undefined is returned
  46336. */
  46337. StringDictionary.prototype.get = function (key) {
  46338. var val = this._data[key];
  46339. if (val !== undefined) {
  46340. return val;
  46341. }
  46342. return undefined;
  46343. };
  46344. /**
  46345. * Get a value from its key or add it if it doesn't exist.
  46346. * This method will ensure you that a given key/data will be present in the dictionary.
  46347. * @param key the given key to get the matching value from
  46348. * @param factory the factory that will create the value if the key is not present in the dictionary.
  46349. * The factory will only be invoked if there's no data for the given key.
  46350. * @return the value corresponding to the key.
  46351. */
  46352. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  46353. var val = this.get(key);
  46354. if (val !== undefined) {
  46355. return val;
  46356. }
  46357. val = factory(key);
  46358. if (val) {
  46359. this.add(key, val);
  46360. }
  46361. return val;
  46362. };
  46363. /**
  46364. * Get a value from its key if present in the dictionary otherwise add it
  46365. * @param key the key to get the value from
  46366. * @param val if there's no such key/value pair in the dictionary add it with this value
  46367. * @return the value corresponding to the key
  46368. */
  46369. StringDictionary.prototype.getOrAdd = function (key, val) {
  46370. var curVal = this.get(key);
  46371. if (curVal !== undefined) {
  46372. return curVal;
  46373. }
  46374. this.add(key, val);
  46375. return val;
  46376. };
  46377. /**
  46378. * Check if there's a given key in the dictionary
  46379. * @param key the key to check for
  46380. * @return true if the key is present, false otherwise
  46381. */
  46382. StringDictionary.prototype.contains = function (key) {
  46383. return this._data[key] !== undefined;
  46384. };
  46385. /**
  46386. * Add a new key and its corresponding value
  46387. * @param key the key to add
  46388. * @param value the value corresponding to the key
  46389. * @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
  46390. */
  46391. StringDictionary.prototype.add = function (key, value) {
  46392. if (this._data[key] !== undefined) {
  46393. return false;
  46394. }
  46395. this._data[key] = value;
  46396. ++this._count;
  46397. return true;
  46398. };
  46399. StringDictionary.prototype.set = function (key, value) {
  46400. if (this._data[key] === undefined) {
  46401. return false;
  46402. }
  46403. this._data[key] = value;
  46404. return true;
  46405. };
  46406. /**
  46407. * Get the element of the given key and remove it from the dictionary
  46408. * @param key
  46409. */
  46410. StringDictionary.prototype.getAndRemove = function (key) {
  46411. var val = this.get(key);
  46412. if (val !== undefined) {
  46413. delete this._data[key];
  46414. --this._count;
  46415. return val;
  46416. }
  46417. return null;
  46418. };
  46419. /**
  46420. * Remove a key/value from the dictionary.
  46421. * @param key the key to remove
  46422. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  46423. */
  46424. StringDictionary.prototype.remove = function (key) {
  46425. if (this.contains(key)) {
  46426. delete this._data[key];
  46427. --this._count;
  46428. return true;
  46429. }
  46430. return false;
  46431. };
  46432. /**
  46433. * Clear the whole content of the dictionary
  46434. */
  46435. StringDictionary.prototype.clear = function () {
  46436. this._data = {};
  46437. this._count = 0;
  46438. };
  46439. Object.defineProperty(StringDictionary.prototype, "count", {
  46440. get: function () {
  46441. return this._count;
  46442. },
  46443. enumerable: true,
  46444. configurable: true
  46445. });
  46446. /**
  46447. * Execute a callback on each key/val of the dictionary.
  46448. * Note that you can remove any element in this dictionary in the callback implementation
  46449. * @param callback the callback to execute on a given key/value pair
  46450. */
  46451. StringDictionary.prototype.forEach = function (callback) {
  46452. for (var cur in this._data) {
  46453. var val = this._data[cur];
  46454. callback(cur, val);
  46455. }
  46456. };
  46457. /**
  46458. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  46459. * If the callback returns null or undefined the method will iterate to the next key/value pair
  46460. * Note that you can remove any element in this dictionary in the callback implementation
  46461. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  46462. */
  46463. StringDictionary.prototype.first = function (callback) {
  46464. for (var cur in this._data) {
  46465. var val = this._data[cur];
  46466. var res = callback(cur, val);
  46467. if (res) {
  46468. return res;
  46469. }
  46470. }
  46471. return null;
  46472. };
  46473. return StringDictionary;
  46474. }());
  46475. BABYLON.StringDictionary = StringDictionary;
  46476. })(BABYLON || (BABYLON = {}));
  46477. //# sourceMappingURL=babylon.stringDictionary.js.map
  46478. var BABYLON;
  46479. (function (BABYLON) {
  46480. var Tags = (function () {
  46481. function Tags() {
  46482. }
  46483. Tags.EnableFor = function (obj) {
  46484. obj._tags = obj._tags || {};
  46485. obj.hasTags = function () {
  46486. return Tags.HasTags(obj);
  46487. };
  46488. obj.addTags = function (tagsString) {
  46489. return Tags.AddTagsTo(obj, tagsString);
  46490. };
  46491. obj.removeTags = function (tagsString) {
  46492. return Tags.RemoveTagsFrom(obj, tagsString);
  46493. };
  46494. obj.matchesTagsQuery = function (tagsQuery) {
  46495. return Tags.MatchesQuery(obj, tagsQuery);
  46496. };
  46497. };
  46498. Tags.DisableFor = function (obj) {
  46499. delete obj._tags;
  46500. delete obj.hasTags;
  46501. delete obj.addTags;
  46502. delete obj.removeTags;
  46503. delete obj.matchesTagsQuery;
  46504. };
  46505. Tags.HasTags = function (obj) {
  46506. if (!obj._tags) {
  46507. return false;
  46508. }
  46509. return !BABYLON.Tools.IsEmpty(obj._tags);
  46510. };
  46511. Tags.GetTags = function (obj, asString) {
  46512. if (asString === void 0) { asString = true; }
  46513. if (!obj._tags) {
  46514. return null;
  46515. }
  46516. if (asString) {
  46517. var tagsArray = [];
  46518. for (var tag in obj._tags) {
  46519. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  46520. tagsArray.push(tag);
  46521. }
  46522. }
  46523. return tagsArray.join(" ");
  46524. }
  46525. else {
  46526. return obj._tags;
  46527. }
  46528. };
  46529. // the tags 'true' and 'false' are reserved and cannot be used as tags
  46530. // a tag cannot start with '||', '&&', and '!'
  46531. // it cannot contain whitespaces
  46532. Tags.AddTagsTo = function (obj, tagsString) {
  46533. if (!tagsString) {
  46534. return;
  46535. }
  46536. if (typeof tagsString !== "string") {
  46537. return;
  46538. }
  46539. var tags = tagsString.split(" ");
  46540. tags.forEach(function (tag, index, array) {
  46541. Tags._AddTagTo(obj, tag);
  46542. });
  46543. };
  46544. Tags._AddTagTo = function (obj, tag) {
  46545. tag = tag.trim();
  46546. if (tag === "" || tag === "true" || tag === "false") {
  46547. return;
  46548. }
  46549. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  46550. return;
  46551. }
  46552. Tags.EnableFor(obj);
  46553. obj._tags[tag] = true;
  46554. };
  46555. Tags.RemoveTagsFrom = function (obj, tagsString) {
  46556. if (!Tags.HasTags(obj)) {
  46557. return;
  46558. }
  46559. var tags = tagsString.split(" ");
  46560. for (var t in tags) {
  46561. Tags._RemoveTagFrom(obj, tags[t]);
  46562. }
  46563. };
  46564. Tags._RemoveTagFrom = function (obj, tag) {
  46565. delete obj._tags[tag];
  46566. };
  46567. Tags.MatchesQuery = function (obj, tagsQuery) {
  46568. if (tagsQuery === undefined) {
  46569. return true;
  46570. }
  46571. if (tagsQuery === "") {
  46572. return Tags.HasTags(obj);
  46573. }
  46574. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  46575. };
  46576. return Tags;
  46577. }());
  46578. BABYLON.Tags = Tags;
  46579. })(BABYLON || (BABYLON = {}));
  46580. //# sourceMappingURL=babylon.tags.js.map
  46581. var BABYLON;
  46582. (function (BABYLON) {
  46583. var Internals;
  46584. (function (Internals) {
  46585. var AndOrNotEvaluator = (function () {
  46586. function AndOrNotEvaluator() {
  46587. }
  46588. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  46589. if (!query.match(/\([^\(\)]*\)/g)) {
  46590. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  46591. }
  46592. else {
  46593. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  46594. // remove parenthesis
  46595. r = r.slice(1, r.length - 1);
  46596. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  46597. });
  46598. }
  46599. if (query === "true") {
  46600. return true;
  46601. }
  46602. if (query === "false") {
  46603. return false;
  46604. }
  46605. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  46606. };
  46607. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  46608. evaluateCallback = evaluateCallback || (function (r) {
  46609. return r === "true" ? true : false;
  46610. });
  46611. var result;
  46612. var or = parenthesisContent.split("||");
  46613. for (var i in or) {
  46614. if (or.hasOwnProperty(i)) {
  46615. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  46616. var and = ori.split("&&");
  46617. if (and.length > 1) {
  46618. for (var j = 0; j < and.length; ++j) {
  46619. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  46620. if (andj !== "true" && andj !== "false") {
  46621. if (andj[0] === "!") {
  46622. result = !evaluateCallback(andj.substring(1));
  46623. }
  46624. else {
  46625. result = evaluateCallback(andj);
  46626. }
  46627. }
  46628. else {
  46629. result = andj === "true" ? true : false;
  46630. }
  46631. if (!result) {
  46632. ori = "false";
  46633. break;
  46634. }
  46635. }
  46636. }
  46637. if (result || ori === "true") {
  46638. result = true;
  46639. break;
  46640. }
  46641. // result equals false (or undefined)
  46642. if (ori !== "true" && ori !== "false") {
  46643. if (ori[0] === "!") {
  46644. result = !evaluateCallback(ori.substring(1));
  46645. }
  46646. else {
  46647. result = evaluateCallback(ori);
  46648. }
  46649. }
  46650. else {
  46651. result = ori === "true" ? true : false;
  46652. }
  46653. }
  46654. }
  46655. // the whole parenthesis scope is replaced by 'true' or 'false'
  46656. return result ? "true" : "false";
  46657. };
  46658. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  46659. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  46660. // remove whitespaces
  46661. r = r.replace(/[\s]/g, function () { return ""; });
  46662. return r.length % 2 ? "!" : "";
  46663. });
  46664. booleanString = booleanString.trim();
  46665. if (booleanString === "!true") {
  46666. booleanString = "false";
  46667. }
  46668. else if (booleanString === "!false") {
  46669. booleanString = "true";
  46670. }
  46671. return booleanString;
  46672. };
  46673. return AndOrNotEvaluator;
  46674. }());
  46675. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  46676. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46677. })(BABYLON || (BABYLON = {}));
  46678. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  46679. var BABYLON;
  46680. (function (BABYLON) {
  46681. var Database = (function () {
  46682. function Database(urlToScene, callbackManifestChecked) {
  46683. // Handling various flavors of prefixed version of IndexedDB
  46684. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  46685. this.callbackManifestChecked = callbackManifestChecked;
  46686. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  46687. this.db = null;
  46688. this.enableSceneOffline = false;
  46689. this.enableTexturesOffline = false;
  46690. this.manifestVersionFound = 0;
  46691. this.mustUpdateRessources = false;
  46692. this.hasReachedQuota = false;
  46693. if (!Database.IDBStorageEnabled) {
  46694. this.callbackManifestChecked(true);
  46695. }
  46696. else {
  46697. this.checkManifestFile();
  46698. }
  46699. }
  46700. Database.prototype.checkManifestFile = function () {
  46701. var _this = this;
  46702. function noManifestFile() {
  46703. that.enableSceneOffline = false;
  46704. that.enableTexturesOffline = false;
  46705. that.callbackManifestChecked(false);
  46706. }
  46707. var that = this;
  46708. var timeStampUsed = false;
  46709. var manifestURL = this.currentSceneUrl + ".manifest";
  46710. var xhr = new XMLHttpRequest();
  46711. if (navigator.onLine) {
  46712. // Adding a timestamp to by-pass browsers' cache
  46713. timeStampUsed = true;
  46714. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  46715. }
  46716. xhr.open("GET", manifestURL, true);
  46717. xhr.addEventListener("load", function () {
  46718. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  46719. try {
  46720. var manifestFile = JSON.parse(xhr.response);
  46721. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  46722. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  46723. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  46724. _this.manifestVersionFound = manifestFile.version;
  46725. }
  46726. if (_this.callbackManifestChecked) {
  46727. _this.callbackManifestChecked(true);
  46728. }
  46729. }
  46730. catch (ex) {
  46731. noManifestFile();
  46732. }
  46733. }
  46734. else {
  46735. noManifestFile();
  46736. }
  46737. }, false);
  46738. xhr.addEventListener("error", function (event) {
  46739. if (timeStampUsed) {
  46740. timeStampUsed = false;
  46741. // Let's retry without the timeStamp
  46742. // It could fail when coupled with HTML5 Offline API
  46743. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  46744. xhr.open("GET", retryManifestURL, true);
  46745. xhr.send();
  46746. }
  46747. else {
  46748. noManifestFile();
  46749. }
  46750. }, false);
  46751. try {
  46752. xhr.send();
  46753. }
  46754. catch (ex) {
  46755. BABYLON.Tools.Error("Error on XHR send request.");
  46756. that.callbackManifestChecked(false);
  46757. }
  46758. };
  46759. Database.prototype.openAsync = function (successCallback, errorCallback) {
  46760. var _this = this;
  46761. function handleError() {
  46762. that.isSupported = false;
  46763. if (errorCallback)
  46764. errorCallback();
  46765. }
  46766. var that = this;
  46767. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  46768. // Your browser doesn't support IndexedDB
  46769. this.isSupported = false;
  46770. if (errorCallback)
  46771. errorCallback();
  46772. }
  46773. else {
  46774. // If the DB hasn't been opened or created yet
  46775. if (!this.db) {
  46776. this.hasReachedQuota = false;
  46777. this.isSupported = true;
  46778. var request = this.idbFactory.open("babylonjs", 1);
  46779. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  46780. request.onerror = function (event) {
  46781. handleError();
  46782. };
  46783. // executes when a version change transaction cannot complete due to other active transactions
  46784. request.onblocked = function (event) {
  46785. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  46786. handleError();
  46787. };
  46788. // DB has been opened successfully
  46789. request.onsuccess = function (event) {
  46790. _this.db = request.result;
  46791. successCallback();
  46792. };
  46793. // Initialization of the DB. Creating Scenes & Textures stores
  46794. request.onupgradeneeded = function (event) {
  46795. _this.db = (event.target).result;
  46796. try {
  46797. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  46798. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  46799. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  46800. }
  46801. catch (ex) {
  46802. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  46803. handleError();
  46804. }
  46805. };
  46806. }
  46807. else {
  46808. if (successCallback)
  46809. successCallback();
  46810. }
  46811. }
  46812. };
  46813. Database.prototype.loadImageFromDB = function (url, image) {
  46814. var _this = this;
  46815. var completeURL = Database.ReturnFullUrlLocation(url);
  46816. var saveAndLoadImage = function () {
  46817. if (!_this.hasReachedQuota && _this.db !== null) {
  46818. // the texture is not yet in the DB, let's try to save it
  46819. _this._saveImageIntoDBAsync(completeURL, image);
  46820. }
  46821. else {
  46822. image.src = url;
  46823. }
  46824. };
  46825. if (!this.mustUpdateRessources) {
  46826. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  46827. }
  46828. else {
  46829. saveAndLoadImage();
  46830. }
  46831. };
  46832. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  46833. if (this.isSupported && this.db !== null) {
  46834. var texture;
  46835. var transaction = this.db.transaction(["textures"]);
  46836. transaction.onabort = function (event) {
  46837. image.src = url;
  46838. };
  46839. transaction.oncomplete = function (event) {
  46840. var blobTextureURL;
  46841. if (texture) {
  46842. var URL = window.URL || window.webkitURL;
  46843. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  46844. image.onerror = function () {
  46845. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  46846. image.src = url;
  46847. };
  46848. image.src = blobTextureURL;
  46849. }
  46850. else {
  46851. notInDBCallback();
  46852. }
  46853. };
  46854. var getRequest = transaction.objectStore("textures").get(url);
  46855. getRequest.onsuccess = function (event) {
  46856. texture = (event.target).result;
  46857. };
  46858. getRequest.onerror = function (event) {
  46859. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  46860. image.src = url;
  46861. };
  46862. }
  46863. else {
  46864. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46865. image.src = url;
  46866. }
  46867. };
  46868. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  46869. var _this = this;
  46870. if (this.isSupported) {
  46871. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  46872. var generateBlobUrl = function () {
  46873. var blobTextureURL;
  46874. if (blob) {
  46875. var URL = window.URL || window.webkitURL;
  46876. try {
  46877. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  46878. }
  46879. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  46880. catch (ex) {
  46881. blobTextureURL = URL.createObjectURL(blob);
  46882. }
  46883. }
  46884. image.src = blobTextureURL;
  46885. };
  46886. if (Database.IsUASupportingBlobStorage) {
  46887. var xhr = new XMLHttpRequest(), blob;
  46888. xhr.open("GET", url, true);
  46889. xhr.responseType = "blob";
  46890. xhr.addEventListener("load", function () {
  46891. if (xhr.status === 200) {
  46892. // Blob as response (XHR2)
  46893. blob = xhr.response;
  46894. var transaction = _this.db.transaction(["textures"], "readwrite");
  46895. // the transaction could abort because of a QuotaExceededError error
  46896. transaction.onabort = function (event) {
  46897. try {
  46898. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  46899. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46900. _this.hasReachedQuota = true;
  46901. }
  46902. }
  46903. catch (ex) { }
  46904. generateBlobUrl();
  46905. };
  46906. transaction.oncomplete = function (event) {
  46907. generateBlobUrl();
  46908. };
  46909. var newTexture = { textureUrl: url, data: blob };
  46910. try {
  46911. // Put the blob into the dabase
  46912. var addRequest = transaction.objectStore("textures").put(newTexture);
  46913. addRequest.onsuccess = function (event) {
  46914. };
  46915. addRequest.onerror = function (event) {
  46916. generateBlobUrl();
  46917. };
  46918. }
  46919. catch (ex) {
  46920. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  46921. if (ex.code === 25) {
  46922. Database.IsUASupportingBlobStorage = false;
  46923. }
  46924. image.src = url;
  46925. }
  46926. }
  46927. else {
  46928. image.src = url;
  46929. }
  46930. }, false);
  46931. xhr.addEventListener("error", function (event) {
  46932. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  46933. image.src = url;
  46934. }, false);
  46935. xhr.send();
  46936. }
  46937. else {
  46938. image.src = url;
  46939. }
  46940. }
  46941. else {
  46942. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46943. image.src = url;
  46944. }
  46945. };
  46946. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  46947. var _this = this;
  46948. var updateVersion = function (event) {
  46949. // the version is not yet in the DB or we need to update it
  46950. _this._saveVersionIntoDBAsync(url, versionLoaded);
  46951. };
  46952. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  46953. };
  46954. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  46955. var _this = this;
  46956. if (this.isSupported) {
  46957. var version;
  46958. try {
  46959. var transaction = this.db.transaction(["versions"]);
  46960. transaction.oncomplete = function (event) {
  46961. if (version) {
  46962. // If the version in the JSON file is > than the version in DB
  46963. if (_this.manifestVersionFound > version.data) {
  46964. _this.mustUpdateRessources = true;
  46965. updateInDBCallback();
  46966. }
  46967. else {
  46968. callback(version.data);
  46969. }
  46970. }
  46971. else {
  46972. _this.mustUpdateRessources = true;
  46973. updateInDBCallback();
  46974. }
  46975. };
  46976. transaction.onabort = function (event) {
  46977. callback(-1);
  46978. };
  46979. var getRequest = transaction.objectStore("versions").get(url);
  46980. getRequest.onsuccess = function (event) {
  46981. version = (event.target).result;
  46982. };
  46983. getRequest.onerror = function (event) {
  46984. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  46985. callback(-1);
  46986. };
  46987. }
  46988. catch (ex) {
  46989. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  46990. callback(-1);
  46991. }
  46992. }
  46993. else {
  46994. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46995. callback(-1);
  46996. }
  46997. };
  46998. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  46999. var _this = this;
  47000. if (this.isSupported && !this.hasReachedQuota) {
  47001. try {
  47002. // Open a transaction to the database
  47003. var transaction = this.db.transaction(["versions"], "readwrite");
  47004. // the transaction could abort because of a QuotaExceededError error
  47005. transaction.onabort = function (event) {
  47006. try {
  47007. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  47008. _this.hasReachedQuota = true;
  47009. }
  47010. }
  47011. catch (ex) { }
  47012. callback(-1);
  47013. };
  47014. transaction.oncomplete = function (event) {
  47015. callback(_this.manifestVersionFound);
  47016. };
  47017. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  47018. // Put the scene into the database
  47019. var addRequest = transaction.objectStore("versions").put(newVersion);
  47020. addRequest.onsuccess = function (event) {
  47021. };
  47022. addRequest.onerror = function (event) {
  47023. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  47024. };
  47025. }
  47026. catch (ex) {
  47027. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  47028. callback(-1);
  47029. }
  47030. }
  47031. else {
  47032. callback(-1);
  47033. }
  47034. };
  47035. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  47036. var _this = this;
  47037. var completeUrl = Database.ReturnFullUrlLocation(url);
  47038. var saveAndLoadFile = function (event) {
  47039. // the scene is not yet in the DB, let's try to save it
  47040. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  47041. };
  47042. this._checkVersionFromDB(completeUrl, function (version) {
  47043. if (version !== -1) {
  47044. if (!_this.mustUpdateRessources) {
  47045. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  47046. }
  47047. else {
  47048. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  47049. }
  47050. }
  47051. else {
  47052. errorCallback();
  47053. }
  47054. });
  47055. };
  47056. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  47057. if (this.isSupported) {
  47058. var targetStore;
  47059. if (url.indexOf(".babylon") !== -1) {
  47060. targetStore = "scenes";
  47061. }
  47062. else {
  47063. targetStore = "textures";
  47064. }
  47065. var file;
  47066. var transaction = this.db.transaction([targetStore]);
  47067. transaction.oncomplete = function (event) {
  47068. if (file) {
  47069. callback(file.data);
  47070. }
  47071. else {
  47072. notInDBCallback();
  47073. }
  47074. };
  47075. transaction.onabort = function (event) {
  47076. notInDBCallback();
  47077. };
  47078. var getRequest = transaction.objectStore(targetStore).get(url);
  47079. getRequest.onsuccess = function (event) {
  47080. file = (event.target).result;
  47081. };
  47082. getRequest.onerror = function (event) {
  47083. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  47084. notInDBCallback();
  47085. };
  47086. }
  47087. else {
  47088. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47089. callback();
  47090. }
  47091. };
  47092. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  47093. var _this = this;
  47094. if (this.isSupported) {
  47095. var targetStore;
  47096. if (url.indexOf(".babylon") !== -1) {
  47097. targetStore = "scenes";
  47098. }
  47099. else {
  47100. targetStore = "textures";
  47101. }
  47102. // Create XHR
  47103. var xhr = new XMLHttpRequest(), fileData;
  47104. xhr.open("GET", url, true);
  47105. if (useArrayBuffer) {
  47106. xhr.responseType = "arraybuffer";
  47107. }
  47108. xhr.onprogress = progressCallback;
  47109. xhr.addEventListener("load", function () {
  47110. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  47111. // Blob as response (XHR2)
  47112. //fileData = xhr.responseText;
  47113. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  47114. if (!_this.hasReachedQuota) {
  47115. // Open a transaction to the database
  47116. var transaction = _this.db.transaction([targetStore], "readwrite");
  47117. // the transaction could abort because of a QuotaExceededError error
  47118. transaction.onabort = function (event) {
  47119. try {
  47120. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  47121. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  47122. _this.hasReachedQuota = true;
  47123. }
  47124. }
  47125. catch (ex) { }
  47126. callback(fileData);
  47127. };
  47128. transaction.oncomplete = function (event) {
  47129. callback(fileData);
  47130. };
  47131. var newFile;
  47132. if (targetStore === "scenes") {
  47133. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  47134. }
  47135. else {
  47136. newFile = { textureUrl: url, data: fileData };
  47137. }
  47138. try {
  47139. // Put the scene into the database
  47140. var addRequest = transaction.objectStore(targetStore).put(newFile);
  47141. addRequest.onsuccess = function (event) {
  47142. };
  47143. addRequest.onerror = function (event) {
  47144. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  47145. };
  47146. }
  47147. catch (ex) {
  47148. callback(fileData);
  47149. }
  47150. }
  47151. else {
  47152. callback(fileData);
  47153. }
  47154. }
  47155. else {
  47156. callback();
  47157. }
  47158. }, false);
  47159. xhr.addEventListener("error", function (event) {
  47160. BABYLON.Tools.Error("error on XHR request.");
  47161. callback();
  47162. }, false);
  47163. xhr.send();
  47164. }
  47165. else {
  47166. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47167. callback();
  47168. }
  47169. };
  47170. return Database;
  47171. }());
  47172. Database.IsUASupportingBlobStorage = true;
  47173. Database.IDBStorageEnabled = true;
  47174. Database.parseURL = function (url) {
  47175. var a = document.createElement('a');
  47176. a.href = url;
  47177. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  47178. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  47179. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  47180. return absLocation;
  47181. };
  47182. Database.ReturnFullUrlLocation = function (url) {
  47183. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  47184. return (Database.parseURL(window.location.href) + url);
  47185. }
  47186. else {
  47187. return url;
  47188. }
  47189. };
  47190. BABYLON.Database = Database;
  47191. })(BABYLON || (BABYLON = {}));
  47192. //# sourceMappingURL=babylon.database.js.map
  47193. var BABYLON;
  47194. (function (BABYLON) {
  47195. var FresnelParameters = (function () {
  47196. function FresnelParameters() {
  47197. this._isEnabled = true;
  47198. this.leftColor = BABYLON.Color3.White();
  47199. this.rightColor = BABYLON.Color3.Black();
  47200. this.bias = 0;
  47201. this.power = 1;
  47202. }
  47203. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  47204. get: function () {
  47205. return this._isEnabled;
  47206. },
  47207. set: function (value) {
  47208. if (this._isEnabled === value) {
  47209. return;
  47210. }
  47211. this._isEnabled = value;
  47212. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  47213. },
  47214. enumerable: true,
  47215. configurable: true
  47216. });
  47217. FresnelParameters.prototype.clone = function () {
  47218. var newFresnelParameters = new FresnelParameters();
  47219. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  47220. return newFresnelParameters;
  47221. };
  47222. FresnelParameters.prototype.serialize = function () {
  47223. var serializationObject = {};
  47224. serializationObject.isEnabled = this.isEnabled;
  47225. serializationObject.leftColor = this.leftColor;
  47226. serializationObject.rightColor = this.rightColor;
  47227. serializationObject.bias = this.bias;
  47228. serializationObject.power = this.power;
  47229. return serializationObject;
  47230. };
  47231. FresnelParameters.Parse = function (parsedFresnelParameters) {
  47232. var fresnelParameters = new FresnelParameters();
  47233. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  47234. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  47235. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  47236. fresnelParameters.bias = parsedFresnelParameters.bias;
  47237. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  47238. return fresnelParameters;
  47239. };
  47240. return FresnelParameters;
  47241. }());
  47242. BABYLON.FresnelParameters = FresnelParameters;
  47243. })(BABYLON || (BABYLON = {}));
  47244. //# sourceMappingURL=babylon.fresnelParameters.js.map
  47245. var BABYLON;
  47246. (function (BABYLON) {
  47247. var MultiMaterial = (function (_super) {
  47248. __extends(MultiMaterial, _super);
  47249. function MultiMaterial(name, scene) {
  47250. var _this = _super.call(this, name, scene, true) || this;
  47251. scene.multiMaterials.push(_this);
  47252. _this.subMaterials = new Array();
  47253. return _this;
  47254. }
  47255. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  47256. get: function () {
  47257. return this._subMaterials;
  47258. },
  47259. set: function (value) {
  47260. this._subMaterials = value;
  47261. this._hookArray(value);
  47262. },
  47263. enumerable: true,
  47264. configurable: true
  47265. });
  47266. MultiMaterial.prototype._hookArray = function (array) {
  47267. var _this = this;
  47268. var oldPush = array.push;
  47269. array.push = function () {
  47270. var items = [];
  47271. for (var _i = 0; _i < arguments.length; _i++) {
  47272. items[_i] = arguments[_i];
  47273. }
  47274. var result = oldPush.apply(array, items);
  47275. _this._markAllSubMeshesAsTexturesDirty();
  47276. return result;
  47277. };
  47278. var oldSplice = array.splice;
  47279. array.splice = function (index, deleteCount) {
  47280. var deleted = oldSplice.apply(array, [index, deleteCount]);
  47281. _this._markAllSubMeshesAsTexturesDirty();
  47282. return deleted;
  47283. };
  47284. };
  47285. // Properties
  47286. MultiMaterial.prototype.getSubMaterial = function (index) {
  47287. if (index < 0 || index >= this.subMaterials.length) {
  47288. return this.getScene().defaultMaterial;
  47289. }
  47290. return this.subMaterials[index];
  47291. };
  47292. MultiMaterial.prototype.getActiveTextures = function () {
  47293. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  47294. var _a;
  47295. };
  47296. // Methods
  47297. MultiMaterial.prototype.getClassName = function () {
  47298. return "MultiMaterial";
  47299. };
  47300. MultiMaterial.prototype.isReady = function (mesh) {
  47301. for (var index = 0; index < this.subMaterials.length; index++) {
  47302. var subMaterial = this.subMaterials[index];
  47303. if (subMaterial) {
  47304. if (!this.subMaterials[index].isReady(mesh)) {
  47305. return false;
  47306. }
  47307. }
  47308. }
  47309. return true;
  47310. };
  47311. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  47312. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  47313. for (var index = 0; index < this.subMaterials.length; index++) {
  47314. var subMaterial = null;
  47315. if (cloneChildren) {
  47316. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  47317. }
  47318. else {
  47319. subMaterial = this.subMaterials[index];
  47320. }
  47321. newMultiMaterial.subMaterials.push(subMaterial);
  47322. }
  47323. return newMultiMaterial;
  47324. };
  47325. MultiMaterial.prototype.serialize = function () {
  47326. var serializationObject = {};
  47327. serializationObject.name = this.name;
  47328. serializationObject.id = this.id;
  47329. serializationObject.tags = BABYLON.Tags.GetTags(this);
  47330. serializationObject.materials = [];
  47331. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  47332. var subMat = this.subMaterials[matIndex];
  47333. if (subMat) {
  47334. serializationObject.materials.push(subMat.id);
  47335. }
  47336. else {
  47337. serializationObject.materials.push(null);
  47338. }
  47339. }
  47340. return serializationObject;
  47341. };
  47342. return MultiMaterial;
  47343. }(BABYLON.Material));
  47344. BABYLON.MultiMaterial = MultiMaterial;
  47345. })(BABYLON || (BABYLON = {}));
  47346. //# sourceMappingURL=babylon.multiMaterial.js.map
  47347. var BABYLON;
  47348. (function (BABYLON) {
  47349. var FreeCameraTouchInput = (function () {
  47350. function FreeCameraTouchInput() {
  47351. this._offsetX = null;
  47352. this._offsetY = null;
  47353. this._pointerCount = 0;
  47354. this._pointerPressed = [];
  47355. this.touchAngularSensibility = 200000.0;
  47356. this.touchMoveSensibility = 250.0;
  47357. }
  47358. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  47359. var _this = this;
  47360. var previousPosition;
  47361. if (this._pointerInput === undefined) {
  47362. this._onLostFocus = function (evt) {
  47363. _this._offsetX = null;
  47364. _this._offsetY = null;
  47365. };
  47366. this._pointerInput = function (p, s) {
  47367. var evt = p.event;
  47368. if (evt.pointerType === "mouse") {
  47369. return;
  47370. }
  47371. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  47372. if (!noPreventDefault) {
  47373. evt.preventDefault();
  47374. }
  47375. _this._pointerPressed.push(evt.pointerId);
  47376. if (_this._pointerPressed.length !== 1) {
  47377. return;
  47378. }
  47379. previousPosition = {
  47380. x: evt.clientX,
  47381. y: evt.clientY
  47382. };
  47383. }
  47384. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  47385. if (!noPreventDefault) {
  47386. evt.preventDefault();
  47387. }
  47388. var index = _this._pointerPressed.indexOf(evt.pointerId);
  47389. if (index === -1) {
  47390. return;
  47391. }
  47392. _this._pointerPressed.splice(index, 1);
  47393. if (index != 0) {
  47394. return;
  47395. }
  47396. previousPosition = null;
  47397. _this._offsetX = null;
  47398. _this._offsetY = null;
  47399. }
  47400. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47401. if (!noPreventDefault) {
  47402. evt.preventDefault();
  47403. }
  47404. if (!previousPosition) {
  47405. return;
  47406. }
  47407. var index = _this._pointerPressed.indexOf(evt.pointerId);
  47408. if (index != 0) {
  47409. return;
  47410. }
  47411. _this._offsetX = evt.clientX - previousPosition.x;
  47412. _this._offsetY = -(evt.clientY - previousPosition.y);
  47413. }
  47414. };
  47415. }
  47416. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47417. element.addEventListener("blur", this._onLostFocus);
  47418. };
  47419. FreeCameraTouchInput.prototype.detachControl = function (element) {
  47420. if (this._pointerInput && element) {
  47421. this.camera.getScene().onPointerObservable.remove(this._observer);
  47422. this._observer = null;
  47423. element.removeEventListener("blur", this._onLostFocus);
  47424. this._onLostFocus = null;
  47425. this._pointerPressed = [];
  47426. this._offsetX = null;
  47427. this._offsetY = null;
  47428. this._pointerCount = 0;
  47429. }
  47430. };
  47431. FreeCameraTouchInput.prototype.checkInputs = function () {
  47432. if (this._offsetX) {
  47433. var camera = this.camera;
  47434. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  47435. if (this._pointerPressed.length > 1) {
  47436. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  47437. }
  47438. else {
  47439. var speed = camera._computeLocalCameraSpeed();
  47440. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  47441. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  47442. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  47443. }
  47444. }
  47445. };
  47446. FreeCameraTouchInput.prototype.getTypeName = function () {
  47447. return "FreeCameraTouchInput";
  47448. };
  47449. FreeCameraTouchInput.prototype.getSimpleName = function () {
  47450. return "touch";
  47451. };
  47452. return FreeCameraTouchInput;
  47453. }());
  47454. __decorate([
  47455. BABYLON.serialize()
  47456. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  47457. __decorate([
  47458. BABYLON.serialize()
  47459. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  47460. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  47461. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  47462. })(BABYLON || (BABYLON = {}));
  47463. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  47464. /// <reference path="babylon.freeCamera.ts" />
  47465. var BABYLON;
  47466. (function (BABYLON) {
  47467. // We're mainly based on the logic defined into the FreeCamera code
  47468. var TouchCamera = (function (_super) {
  47469. __extends(TouchCamera, _super);
  47470. //-- end properties for backward compatibility for inputs
  47471. function TouchCamera(name, position, scene) {
  47472. var _this = _super.call(this, name, position, scene) || this;
  47473. _this.inputs.addTouch();
  47474. _this._setupInputs();
  47475. return _this;
  47476. }
  47477. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  47478. //-- Begin properties for backward compatibility for inputs
  47479. get: function () {
  47480. var touch = this.inputs.attached["touch"];
  47481. if (touch)
  47482. return touch.touchAngularSensibility;
  47483. },
  47484. set: function (value) {
  47485. var touch = this.inputs.attached["touch"];
  47486. if (touch)
  47487. touch.touchAngularSensibility = value;
  47488. },
  47489. enumerable: true,
  47490. configurable: true
  47491. });
  47492. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  47493. get: function () {
  47494. var touch = this.inputs.attached["touch"];
  47495. if (touch)
  47496. return touch.touchMoveSensibility;
  47497. },
  47498. set: function (value) {
  47499. var touch = this.inputs.attached["touch"];
  47500. if (touch)
  47501. touch.touchMoveSensibility = value;
  47502. },
  47503. enumerable: true,
  47504. configurable: true
  47505. });
  47506. TouchCamera.prototype.getClassName = function () {
  47507. return "TouchCamera";
  47508. };
  47509. TouchCamera.prototype._setupInputs = function () {
  47510. var mouse = this.inputs.attached["mouse"];
  47511. if (mouse) {
  47512. mouse.touchEnabled = false;
  47513. }
  47514. };
  47515. return TouchCamera;
  47516. }(BABYLON.FreeCamera));
  47517. BABYLON.TouchCamera = TouchCamera;
  47518. })(BABYLON || (BABYLON = {}));
  47519. //# sourceMappingURL=babylon.touchCamera.js.map
  47520. var BABYLON;
  47521. (function (BABYLON) {
  47522. var ProceduralTexture = (function (_super) {
  47523. __extends(ProceduralTexture, _super);
  47524. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  47525. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47526. if (isCube === void 0) { isCube = false; }
  47527. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  47528. _this.isCube = isCube;
  47529. _this.isEnabled = true;
  47530. _this._currentRefreshId = -1;
  47531. _this._refreshRate = 1;
  47532. _this._vertexBuffers = {};
  47533. _this._uniforms = new Array();
  47534. _this._samplers = new Array();
  47535. _this._textures = new Array();
  47536. _this._floats = new Array();
  47537. _this._floatsArrays = {};
  47538. _this._colors3 = new Array();
  47539. _this._colors4 = new Array();
  47540. _this._vectors2 = new Array();
  47541. _this._vectors3 = new Array();
  47542. _this._matrices = new Array();
  47543. _this._fallbackTextureUsed = false;
  47544. scene._proceduralTextures.push(_this);
  47545. _this.name = name;
  47546. _this.isRenderTarget = true;
  47547. _this._size = size;
  47548. _this._generateMipMaps = generateMipMaps;
  47549. _this.setFragment(fragment);
  47550. _this._fallbackTexture = fallbackTexture;
  47551. var engine = scene.getEngine();
  47552. if (isCube) {
  47553. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  47554. _this.setFloat("face", 0);
  47555. }
  47556. else {
  47557. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  47558. }
  47559. // VBO
  47560. var vertices = [];
  47561. vertices.push(1, 1);
  47562. vertices.push(-1, 1);
  47563. vertices.push(-1, -1);
  47564. vertices.push(1, -1);
  47565. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  47566. // Indices
  47567. var indices = [];
  47568. indices.push(0);
  47569. indices.push(1);
  47570. indices.push(2);
  47571. indices.push(0);
  47572. indices.push(2);
  47573. indices.push(3);
  47574. _this._indexBuffer = engine.createIndexBuffer(indices);
  47575. return _this;
  47576. }
  47577. ProceduralTexture.prototype.reset = function () {
  47578. if (this._effect === undefined) {
  47579. return;
  47580. }
  47581. var engine = this.getScene().getEngine();
  47582. engine._releaseEffect(this._effect);
  47583. };
  47584. ProceduralTexture.prototype.isReady = function () {
  47585. var _this = this;
  47586. var engine = this.getScene().getEngine();
  47587. var shaders;
  47588. if (!this._fragment) {
  47589. return false;
  47590. }
  47591. if (this._fallbackTextureUsed) {
  47592. return true;
  47593. }
  47594. if (this._fragment.fragmentElement !== undefined) {
  47595. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  47596. }
  47597. else {
  47598. shaders = { vertex: "procedural", fragment: this._fragment };
  47599. }
  47600. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  47601. _this.releaseInternalTexture();
  47602. if (_this._fallbackTexture) {
  47603. _this._texture = _this._fallbackTexture._texture;
  47604. _this._texture.references++;
  47605. }
  47606. _this._fallbackTextureUsed = true;
  47607. });
  47608. return this._effect.isReady();
  47609. };
  47610. ProceduralTexture.prototype.resetRefreshCounter = function () {
  47611. this._currentRefreshId = -1;
  47612. };
  47613. ProceduralTexture.prototype.setFragment = function (fragment) {
  47614. this._fragment = fragment;
  47615. };
  47616. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  47617. get: function () {
  47618. return this._refreshRate;
  47619. },
  47620. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  47621. set: function (value) {
  47622. this._refreshRate = value;
  47623. this.resetRefreshCounter();
  47624. },
  47625. enumerable: true,
  47626. configurable: true
  47627. });
  47628. ProceduralTexture.prototype._shouldRender = function () {
  47629. if (!this.isEnabled || !this.isReady() || !this._texture) {
  47630. return false;
  47631. }
  47632. if (this._fallbackTextureUsed) {
  47633. return false;
  47634. }
  47635. if (this._currentRefreshId === -1) {
  47636. this._currentRefreshId = 1;
  47637. return true;
  47638. }
  47639. if (this.refreshRate === this._currentRefreshId) {
  47640. this._currentRefreshId = 1;
  47641. return true;
  47642. }
  47643. this._currentRefreshId++;
  47644. return false;
  47645. };
  47646. ProceduralTexture.prototype.getRenderSize = function () {
  47647. return this._size;
  47648. };
  47649. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  47650. if (this._fallbackTextureUsed) {
  47651. return;
  47652. }
  47653. this.releaseInternalTexture();
  47654. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  47655. };
  47656. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  47657. if (this._uniforms.indexOf(uniformName) === -1) {
  47658. this._uniforms.push(uniformName);
  47659. }
  47660. };
  47661. ProceduralTexture.prototype.setTexture = function (name, texture) {
  47662. if (this._samplers.indexOf(name) === -1) {
  47663. this._samplers.push(name);
  47664. }
  47665. this._textures[name] = texture;
  47666. return this;
  47667. };
  47668. ProceduralTexture.prototype.setFloat = function (name, value) {
  47669. this._checkUniform(name);
  47670. this._floats[name] = value;
  47671. return this;
  47672. };
  47673. ProceduralTexture.prototype.setFloats = function (name, value) {
  47674. this._checkUniform(name);
  47675. this._floatsArrays[name] = value;
  47676. return this;
  47677. };
  47678. ProceduralTexture.prototype.setColor3 = function (name, value) {
  47679. this._checkUniform(name);
  47680. this._colors3[name] = value;
  47681. return this;
  47682. };
  47683. ProceduralTexture.prototype.setColor4 = function (name, value) {
  47684. this._checkUniform(name);
  47685. this._colors4[name] = value;
  47686. return this;
  47687. };
  47688. ProceduralTexture.prototype.setVector2 = function (name, value) {
  47689. this._checkUniform(name);
  47690. this._vectors2[name] = value;
  47691. return this;
  47692. };
  47693. ProceduralTexture.prototype.setVector3 = function (name, value) {
  47694. this._checkUniform(name);
  47695. this._vectors3[name] = value;
  47696. return this;
  47697. };
  47698. ProceduralTexture.prototype.setMatrix = function (name, value) {
  47699. this._checkUniform(name);
  47700. this._matrices[name] = value;
  47701. return this;
  47702. };
  47703. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  47704. var scene = this.getScene();
  47705. var engine = scene.getEngine();
  47706. // Render
  47707. engine.enableEffect(this._effect);
  47708. engine.setState(false);
  47709. // Texture
  47710. for (var name in this._textures) {
  47711. this._effect.setTexture(name, this._textures[name]);
  47712. }
  47713. // Float
  47714. for (name in this._floats) {
  47715. this._effect.setFloat(name, this._floats[name]);
  47716. }
  47717. // Floats
  47718. for (name in this._floatsArrays) {
  47719. this._effect.setArray(name, this._floatsArrays[name]);
  47720. }
  47721. // Color3
  47722. for (name in this._colors3) {
  47723. this._effect.setColor3(name, this._colors3[name]);
  47724. }
  47725. // Color4
  47726. for (name in this._colors4) {
  47727. var color = this._colors4[name];
  47728. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47729. }
  47730. // Vector2
  47731. for (name in this._vectors2) {
  47732. this._effect.setVector2(name, this._vectors2[name]);
  47733. }
  47734. // Vector3
  47735. for (name in this._vectors3) {
  47736. this._effect.setVector3(name, this._vectors3[name]);
  47737. }
  47738. // Matrix
  47739. for (name in this._matrices) {
  47740. this._effect.setMatrix(name, this._matrices[name]);
  47741. }
  47742. if (this.isCube) {
  47743. for (var face = 0; face < 6; face++) {
  47744. engine.bindFramebuffer(this._texture, face);
  47745. // VBOs
  47746. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  47747. this._effect.setFloat("face", face);
  47748. // Clear
  47749. engine.clear(scene.clearColor, true, true, true);
  47750. // Draw order
  47751. engine.draw(true, 0, 6);
  47752. // Mipmaps
  47753. if (face === 5) {
  47754. engine.generateMipMapsForCubemap(this._texture);
  47755. }
  47756. }
  47757. }
  47758. else {
  47759. engine.bindFramebuffer(this._texture);
  47760. // VBOs
  47761. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  47762. // Clear
  47763. engine.clear(scene.clearColor, true, true, true);
  47764. // Draw order
  47765. engine.draw(true, 0, 6);
  47766. }
  47767. // Unbind
  47768. engine.unBindFramebuffer(this._texture, this.isCube);
  47769. if (this.onGenerated) {
  47770. this.onGenerated();
  47771. }
  47772. };
  47773. ProceduralTexture.prototype.clone = function () {
  47774. var textureSize = this.getSize();
  47775. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  47776. // Base texture
  47777. newTexture.hasAlpha = this.hasAlpha;
  47778. newTexture.level = this.level;
  47779. // RenderTarget Texture
  47780. newTexture.coordinatesMode = this.coordinatesMode;
  47781. return newTexture;
  47782. };
  47783. ProceduralTexture.prototype.dispose = function () {
  47784. var index = this.getScene()._proceduralTextures.indexOf(this);
  47785. if (index >= 0) {
  47786. this.getScene()._proceduralTextures.splice(index, 1);
  47787. }
  47788. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47789. if (vertexBuffer) {
  47790. vertexBuffer.dispose();
  47791. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47792. }
  47793. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  47794. this._indexBuffer = null;
  47795. }
  47796. _super.prototype.dispose.call(this);
  47797. };
  47798. return ProceduralTexture;
  47799. }(BABYLON.Texture));
  47800. BABYLON.ProceduralTexture = ProceduralTexture;
  47801. })(BABYLON || (BABYLON = {}));
  47802. //# sourceMappingURL=babylon.proceduralTexture.js.map
  47803. /// <reference path="babylon.proceduralTexture.ts" />
  47804. var BABYLON;
  47805. (function (BABYLON) {
  47806. var CustomProceduralTexture = (function (_super) {
  47807. __extends(CustomProceduralTexture, _super);
  47808. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  47809. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  47810. _this._animate = true;
  47811. _this._time = 0;
  47812. _this._texturePath = texturePath;
  47813. //Try to load json
  47814. _this.loadJson(texturePath);
  47815. _this.refreshRate = 1;
  47816. return _this;
  47817. }
  47818. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  47819. var _this = this;
  47820. var that = this;
  47821. function noConfigFile() {
  47822. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  47823. try {
  47824. that.setFragment(that._texturePath);
  47825. }
  47826. catch (ex) {
  47827. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  47828. }
  47829. }
  47830. var configFileUrl = jsonUrl + "/config.json";
  47831. var xhr = new XMLHttpRequest();
  47832. xhr.open("GET", configFileUrl, true);
  47833. xhr.addEventListener("load", function () {
  47834. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  47835. try {
  47836. _this._config = JSON.parse(xhr.response);
  47837. _this.updateShaderUniforms();
  47838. _this.updateTextures();
  47839. _this.setFragment(_this._texturePath + "/custom");
  47840. _this._animate = _this._config.animate;
  47841. _this.refreshRate = _this._config.refreshrate;
  47842. }
  47843. catch (ex) {
  47844. noConfigFile();
  47845. }
  47846. }
  47847. else {
  47848. noConfigFile();
  47849. }
  47850. }, false);
  47851. xhr.addEventListener("error", function () {
  47852. noConfigFile();
  47853. }, false);
  47854. try {
  47855. xhr.send();
  47856. }
  47857. catch (ex) {
  47858. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  47859. }
  47860. };
  47861. CustomProceduralTexture.prototype.isReady = function () {
  47862. if (!_super.prototype.isReady.call(this)) {
  47863. return false;
  47864. }
  47865. for (var name in this._textures) {
  47866. var texture = this._textures[name];
  47867. if (!texture.isReady()) {
  47868. return false;
  47869. }
  47870. }
  47871. return true;
  47872. };
  47873. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  47874. if (this._animate) {
  47875. this._time += this.getScene().getAnimationRatio() * 0.03;
  47876. this.updateShaderUniforms();
  47877. }
  47878. _super.prototype.render.call(this, useCameraPostProcess);
  47879. };
  47880. CustomProceduralTexture.prototype.updateTextures = function () {
  47881. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  47882. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  47883. }
  47884. };
  47885. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  47886. if (this._config) {
  47887. for (var j = 0; j < this._config.uniforms.length; j++) {
  47888. var uniform = this._config.uniforms[j];
  47889. switch (uniform.type) {
  47890. case "float":
  47891. this.setFloat(uniform.name, uniform.value);
  47892. break;
  47893. case "color3":
  47894. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  47895. break;
  47896. case "color4":
  47897. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  47898. break;
  47899. case "vector2":
  47900. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  47901. break;
  47902. case "vector3":
  47903. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  47904. break;
  47905. }
  47906. }
  47907. }
  47908. this.setFloat("time", this._time);
  47909. };
  47910. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  47911. get: function () {
  47912. return this._animate;
  47913. },
  47914. set: function (value) {
  47915. this._animate = value;
  47916. },
  47917. enumerable: true,
  47918. configurable: true
  47919. });
  47920. return CustomProceduralTexture;
  47921. }(BABYLON.ProceduralTexture));
  47922. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  47923. })(BABYLON || (BABYLON = {}));
  47924. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  47925. var BABYLON;
  47926. (function (BABYLON) {
  47927. var FreeCameraGamepadInput = (function () {
  47928. function FreeCameraGamepadInput() {
  47929. this.gamepadAngularSensibility = 200;
  47930. this.gamepadMoveSensibility = 40;
  47931. // private members
  47932. this._cameraTransform = BABYLON.Matrix.Identity();
  47933. this._deltaTransform = BABYLON.Vector3.Zero();
  47934. this._vector3 = BABYLON.Vector3.Zero();
  47935. this._vector2 = BABYLON.Vector2.Zero();
  47936. }
  47937. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  47938. var _this = this;
  47939. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  47940. };
  47941. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  47942. if (this._gamepads) {
  47943. this._gamepads.dispose();
  47944. }
  47945. this.gamepad = null;
  47946. };
  47947. FreeCameraGamepadInput.prototype.checkInputs = function () {
  47948. if (this.gamepad && this.gamepad.leftStick) {
  47949. var camera = this.camera;
  47950. var LSValues = this.gamepad.leftStick;
  47951. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  47952. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  47953. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  47954. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  47955. var RSValues = this.gamepad.rightStick;
  47956. if (RSValues) {
  47957. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  47958. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  47959. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  47960. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  47961. }
  47962. else {
  47963. RSValues = { x: 0, y: 0 };
  47964. }
  47965. if (!camera.rotationQuaternion) {
  47966. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  47967. }
  47968. else {
  47969. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  47970. }
  47971. var speed = camera._computeLocalCameraSpeed() * 50.0;
  47972. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  47973. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  47974. camera.cameraDirection.addInPlace(this._deltaTransform);
  47975. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  47976. camera.cameraRotation.addInPlace(this._vector2);
  47977. }
  47978. };
  47979. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  47980. // Only the first gamepad found can control the camera
  47981. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  47982. // prioritize XBOX gamepads.
  47983. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  47984. this.gamepad = gamepad;
  47985. }
  47986. }
  47987. };
  47988. FreeCameraGamepadInput.prototype.getTypeName = function () {
  47989. return "FreeCameraGamepadInput";
  47990. };
  47991. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  47992. return "gamepad";
  47993. };
  47994. return FreeCameraGamepadInput;
  47995. }());
  47996. __decorate([
  47997. BABYLON.serialize()
  47998. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  47999. __decorate([
  48000. BABYLON.serialize()
  48001. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  48002. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  48003. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  48004. })(BABYLON || (BABYLON = {}));
  48005. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  48006. var BABYLON;
  48007. (function (BABYLON) {
  48008. var ArcRotateCameraGamepadInput = (function () {
  48009. function ArcRotateCameraGamepadInput() {
  48010. this.gamepadRotationSensibility = 80;
  48011. this.gamepadMoveSensibility = 40;
  48012. }
  48013. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  48014. var _this = this;
  48015. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  48016. };
  48017. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  48018. if (this._gamepads) {
  48019. this._gamepads.dispose();
  48020. }
  48021. this.gamepad = null;
  48022. };
  48023. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  48024. if (this.gamepad) {
  48025. var camera = this.camera;
  48026. var RSValues = this.gamepad.rightStick;
  48027. if (RSValues) {
  48028. if (RSValues.x != 0) {
  48029. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  48030. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  48031. camera.inertialAlphaOffset += normalizedRX;
  48032. }
  48033. }
  48034. if (RSValues.y != 0) {
  48035. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  48036. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  48037. camera.inertialBetaOffset += normalizedRY;
  48038. }
  48039. }
  48040. }
  48041. var LSValues = this.gamepad.leftStick;
  48042. if (LSValues && LSValues.y != 0) {
  48043. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  48044. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  48045. this.camera.inertialRadiusOffset -= normalizedLY;
  48046. }
  48047. }
  48048. }
  48049. };
  48050. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  48051. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  48052. // prioritize XBOX gamepads.
  48053. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  48054. this.gamepad = gamepad;
  48055. }
  48056. }
  48057. };
  48058. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  48059. return "ArcRotateCameraGamepadInput";
  48060. };
  48061. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  48062. return "gamepad";
  48063. };
  48064. return ArcRotateCameraGamepadInput;
  48065. }());
  48066. __decorate([
  48067. BABYLON.serialize()
  48068. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  48069. __decorate([
  48070. BABYLON.serialize()
  48071. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  48072. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  48073. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  48074. })(BABYLON || (BABYLON = {}));
  48075. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  48076. var BABYLON;
  48077. (function (BABYLON) {
  48078. var Gamepads = (function () {
  48079. function Gamepads(ongamedpadconnected, ongamedpaddisconnected) {
  48080. var _this = this;
  48081. this.babylonGamepads = [];
  48082. this.oneGamepadConnected = false;
  48083. this.isMonitoring = false;
  48084. this.gamepadEventSupported = 'GamepadEvent' in window;
  48085. this.gamepadSupport = (navigator.getGamepads ||
  48086. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  48087. this._callbackGamepadConnected = ongamedpadconnected;
  48088. this._callbackGamepadDisconnected = ongamedpaddisconnected;
  48089. if (this.gamepadSupport) {
  48090. //first add already-connected gamepads
  48091. this._updateGamepadObjects();
  48092. if (this.babylonGamepads.length) {
  48093. this._startMonitoringGamepads();
  48094. }
  48095. // Checking if the gamepad connected event is supported (like in Firefox)
  48096. if (this.gamepadEventSupported) {
  48097. this._onGamepadConnectedEvent = function (evt) {
  48098. _this._onGamepadConnected(evt.gamepad);
  48099. };
  48100. this._onGamepadDisonnectedEvent = function (evt) {
  48101. _this._onGamepadDisconnected(evt.gamepad);
  48102. };
  48103. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  48104. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  48105. }
  48106. else {
  48107. this._startMonitoringGamepads();
  48108. }
  48109. }
  48110. }
  48111. Gamepads.prototype.dispose = function () {
  48112. if (this._onGamepadConnectedEvent) {
  48113. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  48114. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  48115. this._onGamepadConnectedEvent = null;
  48116. this._onGamepadDisonnectedEvent = null;
  48117. }
  48118. this.oneGamepadConnected = false;
  48119. this._stopMonitoringGamepads();
  48120. this.babylonGamepads = [];
  48121. };
  48122. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  48123. // Protection code for Chrome which has a very buggy gamepad implementation...
  48124. // And raises a connected event on disconnection for instance
  48125. if (gamepad.index in this.babylonGamepads) {
  48126. return;
  48127. }
  48128. var newGamepad = this._addNewGamepad(gamepad);
  48129. if (this._callbackGamepadConnected)
  48130. this._callbackGamepadConnected(newGamepad);
  48131. this._startMonitoringGamepads();
  48132. };
  48133. Gamepads.prototype._addNewGamepad = function (gamepad) {
  48134. if (!this.oneGamepadConnected) {
  48135. this.oneGamepadConnected = true;
  48136. }
  48137. var newGamepad;
  48138. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  48139. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  48140. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  48141. }
  48142. else if (gamepad.pose) {
  48143. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  48144. }
  48145. else {
  48146. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  48147. }
  48148. this.babylonGamepads.push(newGamepad);
  48149. return newGamepad;
  48150. };
  48151. Gamepads.prototype._onGamepadDisconnected = function (gamepad) {
  48152. // Remove the gamepad from the list of gamepads to monitor.
  48153. for (var i in this.babylonGamepads) {
  48154. if (this.babylonGamepads[i].index == gamepad.index) {
  48155. this.babylonGamepads.splice(+i, 1);
  48156. break;
  48157. }
  48158. }
  48159. // If no gamepads are left, stop the polling loop.
  48160. if (this.babylonGamepads.length == 0) {
  48161. this._stopMonitoringGamepads();
  48162. this.oneGamepadConnected = false;
  48163. }
  48164. if (this._callbackGamepadDisconnected)
  48165. this._callbackGamepadDisconnected(gamepad);
  48166. };
  48167. Gamepads.prototype._startMonitoringGamepads = function () {
  48168. if (!this.isMonitoring) {
  48169. this.isMonitoring = true;
  48170. this._checkGamepadsStatus();
  48171. }
  48172. };
  48173. Gamepads.prototype._stopMonitoringGamepads = function () {
  48174. this.isMonitoring = false;
  48175. };
  48176. Gamepads.prototype._checkGamepadsStatus = function () {
  48177. var _this = this;
  48178. // Hack to be compatible Chrome
  48179. this._updateGamepadObjects();
  48180. for (var i in this.babylonGamepads) {
  48181. this.babylonGamepads[i].update();
  48182. }
  48183. if (this.isMonitoring) {
  48184. if (window.requestAnimationFrame) {
  48185. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48186. }
  48187. else if (window.mozRequestAnimationFrame) {
  48188. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48189. }
  48190. else if (window.webkitRequestAnimationFrame) {
  48191. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48192. }
  48193. }
  48194. };
  48195. // This function is called only on Chrome, which does not properly support
  48196. // connection/disconnection events and forces you to recopy again the gamepad object
  48197. Gamepads.prototype._updateGamepadObjects = function () {
  48198. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  48199. for (var i = 0; i < gamepads.length; i++) {
  48200. if (gamepads[i]) {
  48201. if (!(gamepads[i].index in this.babylonGamepads)) {
  48202. var newGamepad = this._addNewGamepad(gamepads[i]);
  48203. if (this._callbackGamepadConnected) {
  48204. this._callbackGamepadConnected(newGamepad);
  48205. }
  48206. }
  48207. else {
  48208. // Forced to copy again this object for Chrome for unknown reason
  48209. this.babylonGamepads[i].browserGamepad = gamepads[i];
  48210. }
  48211. }
  48212. }
  48213. };
  48214. return Gamepads;
  48215. }());
  48216. BABYLON.Gamepads = Gamepads;
  48217. var StickValues = (function () {
  48218. function StickValues(x, y) {
  48219. this.x = x;
  48220. this.y = y;
  48221. }
  48222. return StickValues;
  48223. }());
  48224. BABYLON.StickValues = StickValues;
  48225. var Gamepad = (function () {
  48226. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  48227. if (leftStickX === void 0) { leftStickX = 0; }
  48228. if (leftStickY === void 0) { leftStickY = 1; }
  48229. if (rightStickX === void 0) { rightStickX = 2; }
  48230. if (rightStickY === void 0) { rightStickY = 3; }
  48231. this.id = id;
  48232. this.index = index;
  48233. this.browserGamepad = browserGamepad;
  48234. this.type = Gamepad.GAMEPAD;
  48235. this._leftStickAxisX = leftStickX;
  48236. this._leftStickAxisY = leftStickY;
  48237. this._rightStickAxisX = rightStickX;
  48238. this._rightStickAxisY = rightStickY;
  48239. if (this.browserGamepad.axes.length >= 2) {
  48240. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  48241. }
  48242. if (this.browserGamepad.axes.length >= 4) {
  48243. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  48244. }
  48245. }
  48246. Gamepad.prototype.onleftstickchanged = function (callback) {
  48247. this._onleftstickchanged = callback;
  48248. };
  48249. Gamepad.prototype.onrightstickchanged = function (callback) {
  48250. this._onrightstickchanged = callback;
  48251. };
  48252. Object.defineProperty(Gamepad.prototype, "leftStick", {
  48253. get: function () {
  48254. return this._leftStick;
  48255. },
  48256. set: function (newValues) {
  48257. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  48258. this._onleftstickchanged(newValues);
  48259. }
  48260. this._leftStick = newValues;
  48261. },
  48262. enumerable: true,
  48263. configurable: true
  48264. });
  48265. Object.defineProperty(Gamepad.prototype, "rightStick", {
  48266. get: function () {
  48267. return this._rightStick;
  48268. },
  48269. set: function (newValues) {
  48270. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  48271. this._onrightstickchanged(newValues);
  48272. }
  48273. this._rightStick = newValues;
  48274. },
  48275. enumerable: true,
  48276. configurable: true
  48277. });
  48278. Gamepad.prototype.update = function () {
  48279. if (this._leftStick) {
  48280. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  48281. }
  48282. if (this._rightStick) {
  48283. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  48284. }
  48285. };
  48286. return Gamepad;
  48287. }());
  48288. Gamepad.GAMEPAD = 0;
  48289. Gamepad.GENERIC = 1;
  48290. Gamepad.XBOX = 2;
  48291. Gamepad.POSE_ENABLED = 3;
  48292. BABYLON.Gamepad = Gamepad;
  48293. var GenericPad = (function (_super) {
  48294. __extends(GenericPad, _super);
  48295. function GenericPad(id, index, browserGamepad) {
  48296. var _this = _super.call(this, id, index, browserGamepad) || this;
  48297. _this.type = Gamepad.GENERIC;
  48298. _this._buttons = new Array(browserGamepad.buttons.length);
  48299. return _this;
  48300. }
  48301. GenericPad.prototype.onbuttondown = function (callback) {
  48302. this._onbuttondown = callback;
  48303. };
  48304. GenericPad.prototype.onbuttonup = function (callback) {
  48305. this._onbuttonup = callback;
  48306. };
  48307. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  48308. if (newValue !== currentValue) {
  48309. if (this._onbuttondown && newValue === 1) {
  48310. this._onbuttondown(buttonIndex);
  48311. }
  48312. if (this._onbuttonup && newValue === 0) {
  48313. this._onbuttonup(buttonIndex);
  48314. }
  48315. }
  48316. return newValue;
  48317. };
  48318. GenericPad.prototype.update = function () {
  48319. _super.prototype.update.call(this);
  48320. for (var index = 0; index < this._buttons.length; index++) {
  48321. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  48322. }
  48323. };
  48324. return GenericPad;
  48325. }(Gamepad));
  48326. BABYLON.GenericPad = GenericPad;
  48327. var Xbox360Button;
  48328. (function (Xbox360Button) {
  48329. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  48330. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  48331. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  48332. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  48333. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  48334. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  48335. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  48336. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  48337. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  48338. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  48339. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  48340. var Xbox360Dpad;
  48341. (function (Xbox360Dpad) {
  48342. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  48343. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  48344. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  48345. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  48346. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  48347. var Xbox360Pad = (function (_super) {
  48348. __extends(Xbox360Pad, _super);
  48349. function Xbox360Pad(id, index, gamepad, xboxOne) {
  48350. if (xboxOne === void 0) { xboxOne = false; }
  48351. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  48352. _this._leftTrigger = 0;
  48353. _this._rightTrigger = 0;
  48354. _this._buttonA = 0;
  48355. _this._buttonB = 0;
  48356. _this._buttonX = 0;
  48357. _this._buttonY = 0;
  48358. _this._buttonBack = 0;
  48359. _this._buttonStart = 0;
  48360. _this._buttonLB = 0;
  48361. _this._buttonRB = 0;
  48362. _this._buttonLeftStick = 0;
  48363. _this._buttonRightStick = 0;
  48364. _this._dPadUp = 0;
  48365. _this._dPadDown = 0;
  48366. _this._dPadLeft = 0;
  48367. _this._dPadRight = 0;
  48368. _this._isXboxOnePad = false;
  48369. _this.type = Gamepad.XBOX;
  48370. _this._isXboxOnePad = xboxOne;
  48371. return _this;
  48372. }
  48373. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  48374. this._onlefttriggerchanged = callback;
  48375. };
  48376. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  48377. this._onrighttriggerchanged = callback;
  48378. };
  48379. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  48380. get: function () {
  48381. return this._leftTrigger;
  48382. },
  48383. set: function (newValue) {
  48384. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  48385. this._onlefttriggerchanged(newValue);
  48386. }
  48387. this._leftTrigger = newValue;
  48388. },
  48389. enumerable: true,
  48390. configurable: true
  48391. });
  48392. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  48393. get: function () {
  48394. return this._rightTrigger;
  48395. },
  48396. set: function (newValue) {
  48397. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  48398. this._onrighttriggerchanged(newValue);
  48399. }
  48400. this._rightTrigger = newValue;
  48401. },
  48402. enumerable: true,
  48403. configurable: true
  48404. });
  48405. Xbox360Pad.prototype.onbuttondown = function (callback) {
  48406. this._onbuttondown = callback;
  48407. };
  48408. Xbox360Pad.prototype.onbuttonup = function (callback) {
  48409. this._onbuttonup = callback;
  48410. };
  48411. Xbox360Pad.prototype.ondpaddown = function (callback) {
  48412. this._ondpaddown = callback;
  48413. };
  48414. Xbox360Pad.prototype.ondpadup = function (callback) {
  48415. this._ondpadup = callback;
  48416. };
  48417. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  48418. if (newValue !== currentValue) {
  48419. if (this._onbuttondown && newValue === 1) {
  48420. this._onbuttondown(buttonType);
  48421. }
  48422. if (this._onbuttonup && newValue === 0) {
  48423. this._onbuttonup(buttonType);
  48424. }
  48425. }
  48426. return newValue;
  48427. };
  48428. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  48429. if (newValue !== currentValue) {
  48430. if (this._ondpaddown && newValue === 1) {
  48431. this._ondpaddown(buttonType);
  48432. }
  48433. if (this._ondpadup && newValue === 0) {
  48434. this._ondpadup(buttonType);
  48435. }
  48436. }
  48437. return newValue;
  48438. };
  48439. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  48440. get: function () {
  48441. return this._buttonA;
  48442. },
  48443. set: function (value) {
  48444. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  48445. },
  48446. enumerable: true,
  48447. configurable: true
  48448. });
  48449. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  48450. get: function () {
  48451. return this._buttonB;
  48452. },
  48453. set: function (value) {
  48454. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  48455. },
  48456. enumerable: true,
  48457. configurable: true
  48458. });
  48459. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  48460. get: function () {
  48461. return this._buttonX;
  48462. },
  48463. set: function (value) {
  48464. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  48465. },
  48466. enumerable: true,
  48467. configurable: true
  48468. });
  48469. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  48470. get: function () {
  48471. return this._buttonY;
  48472. },
  48473. set: function (value) {
  48474. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  48475. },
  48476. enumerable: true,
  48477. configurable: true
  48478. });
  48479. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  48480. get: function () {
  48481. return this._buttonStart;
  48482. },
  48483. set: function (value) {
  48484. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  48485. },
  48486. enumerable: true,
  48487. configurable: true
  48488. });
  48489. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  48490. get: function () {
  48491. return this._buttonBack;
  48492. },
  48493. set: function (value) {
  48494. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  48495. },
  48496. enumerable: true,
  48497. configurable: true
  48498. });
  48499. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  48500. get: function () {
  48501. return this._buttonLB;
  48502. },
  48503. set: function (value) {
  48504. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  48505. },
  48506. enumerable: true,
  48507. configurable: true
  48508. });
  48509. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  48510. get: function () {
  48511. return this._buttonRB;
  48512. },
  48513. set: function (value) {
  48514. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  48515. },
  48516. enumerable: true,
  48517. configurable: true
  48518. });
  48519. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  48520. get: function () {
  48521. return this._buttonLeftStick;
  48522. },
  48523. set: function (value) {
  48524. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  48525. },
  48526. enumerable: true,
  48527. configurable: true
  48528. });
  48529. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  48530. get: function () {
  48531. return this._buttonRightStick;
  48532. },
  48533. set: function (value) {
  48534. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  48535. },
  48536. enumerable: true,
  48537. configurable: true
  48538. });
  48539. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  48540. get: function () {
  48541. return this._dPadUp;
  48542. },
  48543. set: function (value) {
  48544. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  48545. },
  48546. enumerable: true,
  48547. configurable: true
  48548. });
  48549. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  48550. get: function () {
  48551. return this._dPadDown;
  48552. },
  48553. set: function (value) {
  48554. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  48555. },
  48556. enumerable: true,
  48557. configurable: true
  48558. });
  48559. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  48560. get: function () {
  48561. return this._dPadLeft;
  48562. },
  48563. set: function (value) {
  48564. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  48565. },
  48566. enumerable: true,
  48567. configurable: true
  48568. });
  48569. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  48570. get: function () {
  48571. return this._dPadRight;
  48572. },
  48573. set: function (value) {
  48574. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  48575. },
  48576. enumerable: true,
  48577. configurable: true
  48578. });
  48579. Xbox360Pad.prototype.update = function () {
  48580. _super.prototype.update.call(this);
  48581. if (this._isXboxOnePad) {
  48582. this.buttonA = this.browserGamepad.buttons[0].value;
  48583. this.buttonB = this.browserGamepad.buttons[1].value;
  48584. this.buttonX = this.browserGamepad.buttons[2].value;
  48585. this.buttonY = this.browserGamepad.buttons[3].value;
  48586. this.buttonLB = this.browserGamepad.buttons[4].value;
  48587. this.buttonRB = this.browserGamepad.buttons[5].value;
  48588. this.leftTrigger = this.browserGamepad.axes[2];
  48589. this.rightTrigger = this.browserGamepad.axes[5];
  48590. this.buttonBack = this.browserGamepad.buttons[9].value;
  48591. this.buttonStart = this.browserGamepad.buttons[8].value;
  48592. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  48593. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  48594. this.dPadUp = this.browserGamepad.buttons[11].value;
  48595. this.dPadDown = this.browserGamepad.buttons[12].value;
  48596. this.dPadLeft = this.browserGamepad.buttons[13].value;
  48597. this.dPadRight = this.browserGamepad.buttons[14].value;
  48598. }
  48599. else {
  48600. this.buttonA = this.browserGamepad.buttons[0].value;
  48601. this.buttonB = this.browserGamepad.buttons[1].value;
  48602. this.buttonX = this.browserGamepad.buttons[2].value;
  48603. this.buttonY = this.browserGamepad.buttons[3].value;
  48604. this.buttonLB = this.browserGamepad.buttons[4].value;
  48605. this.buttonRB = this.browserGamepad.buttons[5].value;
  48606. this.leftTrigger = this.browserGamepad.buttons[6].value;
  48607. this.rightTrigger = this.browserGamepad.buttons[7].value;
  48608. this.buttonBack = this.browserGamepad.buttons[8].value;
  48609. this.buttonStart = this.browserGamepad.buttons[9].value;
  48610. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  48611. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  48612. this.dPadUp = this.browserGamepad.buttons[12].value;
  48613. this.dPadDown = this.browserGamepad.buttons[13].value;
  48614. this.dPadLeft = this.browserGamepad.buttons[14].value;
  48615. this.dPadRight = this.browserGamepad.buttons[15].value;
  48616. }
  48617. };
  48618. return Xbox360Pad;
  48619. }(Gamepad));
  48620. BABYLON.Xbox360Pad = Xbox360Pad;
  48621. })(BABYLON || (BABYLON = {}));
  48622. //# sourceMappingURL=babylon.gamepads.js.map
  48623. var BABYLON;
  48624. (function (BABYLON) {
  48625. var PoseEnabledControllerType;
  48626. (function (PoseEnabledControllerType) {
  48627. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  48628. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  48629. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  48630. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  48631. var PoseEnabledControllerHelper = (function () {
  48632. function PoseEnabledControllerHelper() {
  48633. }
  48634. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  48635. // for now, only Oculus and Vive are supported
  48636. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  48637. return new OculusTouchController(vrGamepad);
  48638. }
  48639. else {
  48640. return new ViveController(vrGamepad);
  48641. }
  48642. };
  48643. return PoseEnabledControllerHelper;
  48644. }());
  48645. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  48646. var PoseEnabledController = (function (_super) {
  48647. __extends(PoseEnabledController, _super);
  48648. function PoseEnabledController(vrGamepad) {
  48649. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  48650. _this.vrGamepad = vrGamepad;
  48651. _this.deviceScaleFactor = 1;
  48652. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  48653. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  48654. _this.controllerType = PoseEnabledControllerType.GENERIC;
  48655. _this.position = BABYLON.Vector3.Zero();
  48656. _this.rotationQuaternion = new BABYLON.Quaternion();
  48657. _this.devicePosition = BABYLON.Vector3.Zero();
  48658. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  48659. _this._calculatedPosition = BABYLON.Vector3.Zero();
  48660. _this._calculatedRotation = new BABYLON.Quaternion();
  48661. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  48662. return _this;
  48663. }
  48664. PoseEnabledController.prototype.update = function () {
  48665. _super.prototype.update.call(this);
  48666. var pose = this.vrGamepad.pose;
  48667. this.updateFromDevice(pose);
  48668. if (this._mesh) {
  48669. this._mesh.position.copyFrom(this._calculatedPosition);
  48670. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  48671. }
  48672. };
  48673. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  48674. if (poseData) {
  48675. this.rawPose = poseData;
  48676. if (poseData.position) {
  48677. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  48678. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  48679. this.devicePosition.z *= -1;
  48680. }
  48681. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  48682. this._calculatedPosition.addInPlace(this.position);
  48683. }
  48684. if (poseData.orientation) {
  48685. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  48686. if (this._mesh) {
  48687. if (this._mesh.getScene().useRightHandedSystem) {
  48688. this.deviceRotationQuaternion.z *= -1;
  48689. this.deviceRotationQuaternion.w *= -1;
  48690. }
  48691. else {
  48692. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  48693. }
  48694. }
  48695. // if the camera is set, rotate to the camera's rotation
  48696. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  48697. }
  48698. }
  48699. };
  48700. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  48701. if (this._mesh) {
  48702. this._mesh.parent = undefined;
  48703. }
  48704. this._mesh = mesh;
  48705. if (this._poseControlledCamera) {
  48706. this._mesh.parent = this._poseControlledCamera;
  48707. }
  48708. if (!this._mesh.rotationQuaternion) {
  48709. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  48710. }
  48711. };
  48712. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  48713. this._poseControlledCamera = camera;
  48714. if (this._mesh) {
  48715. this._mesh.parent = this._poseControlledCamera;
  48716. }
  48717. };
  48718. PoseEnabledController.prototype.detachMesh = function () {
  48719. this._mesh = undefined;
  48720. };
  48721. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  48722. get: function () {
  48723. return this._mesh;
  48724. },
  48725. enumerable: true,
  48726. configurable: true
  48727. });
  48728. PoseEnabledController.prototype.getForwardRay = function (length) {
  48729. if (length === void 0) { length = 100; }
  48730. if (!this.mesh) {
  48731. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  48732. }
  48733. var m = this.mesh.getWorldMatrix();
  48734. var origin = m.getTranslation();
  48735. var forward = new BABYLON.Vector3(0, 0, -1);
  48736. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  48737. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  48738. return new BABYLON.Ray(origin, direction, length);
  48739. };
  48740. return PoseEnabledController;
  48741. }(BABYLON.Gamepad));
  48742. BABYLON.PoseEnabledController = PoseEnabledController;
  48743. var WebVRController = (function (_super) {
  48744. __extends(WebVRController, _super);
  48745. function WebVRController(vrGamepad) {
  48746. var _this = _super.call(this, vrGamepad) || this;
  48747. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  48748. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  48749. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  48750. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  48751. _this.onPadStateChangedObservable = new BABYLON.Observable();
  48752. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  48753. _this.pad = { x: 0, y: 0 };
  48754. // avoid GC, store state in a tmp object
  48755. _this._changes = {
  48756. pressChanged: false,
  48757. touchChanged: false,
  48758. valueChanged: false,
  48759. changed: false
  48760. };
  48761. _this._buttons = new Array(vrGamepad.buttons.length);
  48762. _this.hand = vrGamepad.hand;
  48763. return _this;
  48764. }
  48765. WebVRController.prototype.onButtonStateChange = function (callback) {
  48766. this._onButtonStateChange = callback;
  48767. };
  48768. WebVRController.prototype.update = function () {
  48769. _super.prototype.update.call(this);
  48770. for (var index = 0; index < this._buttons.length; index++) {
  48771. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  48772. }
  48773. ;
  48774. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  48775. this.pad.x = this.leftStick.x;
  48776. this.pad.y = this.leftStick.y;
  48777. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  48778. }
  48779. };
  48780. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  48781. if (!currentState) {
  48782. this._buttons[buttonIndex] = {
  48783. pressed: newState.pressed,
  48784. touched: newState.touched,
  48785. value: newState.value
  48786. };
  48787. return;
  48788. }
  48789. this._checkChanges(newState, currentState);
  48790. if (this._changes.changed) {
  48791. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  48792. this.handleButtonChange(buttonIndex, newState, this._changes);
  48793. }
  48794. this._buttons[buttonIndex].pressed = newState.pressed;
  48795. this._buttons[buttonIndex].touched = newState.touched;
  48796. // oculus triggers are never 0, thou not touched.
  48797. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  48798. };
  48799. WebVRController.prototype._checkChanges = function (newState, currentState) {
  48800. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  48801. this._changes.touchChanged = newState.touched !== currentState.touched;
  48802. this._changes.valueChanged = newState.value !== currentState.value;
  48803. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  48804. return this._changes;
  48805. };
  48806. return WebVRController;
  48807. }(PoseEnabledController));
  48808. BABYLON.WebVRController = WebVRController;
  48809. var OculusTouchController = (function (_super) {
  48810. __extends(OculusTouchController, _super);
  48811. function OculusTouchController(vrGamepad) {
  48812. var _this = _super.call(this, vrGamepad) || this;
  48813. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  48814. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  48815. _this.controllerType = PoseEnabledControllerType.OCULUS;
  48816. return _this;
  48817. }
  48818. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  48819. var _this = this;
  48820. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  48821. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  48822. /*
  48823. Parent Mesh name: oculus_touch_left
  48824. - body
  48825. - trigger
  48826. - thumbstick
  48827. - grip
  48828. - button_y
  48829. - button_x
  48830. - button_enter
  48831. */
  48832. _this._defaultModel = newMeshes[1];
  48833. if (meshLoaded) {
  48834. meshLoaded(_this._defaultModel);
  48835. }
  48836. _this.attachToMesh(_this._defaultModel);
  48837. });
  48838. };
  48839. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  48840. // helper getters for left and right hand.
  48841. get: function () {
  48842. if (this.hand === 'right') {
  48843. return this.onMainButtonStateChangedObservable;
  48844. }
  48845. else {
  48846. throw new Error('No A button on left hand');
  48847. }
  48848. },
  48849. enumerable: true,
  48850. configurable: true
  48851. });
  48852. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  48853. get: function () {
  48854. if (this.hand === 'right') {
  48855. return this.onSecondaryButtonStateChangedObservable;
  48856. }
  48857. else {
  48858. throw new Error('No B button on left hand');
  48859. }
  48860. },
  48861. enumerable: true,
  48862. configurable: true
  48863. });
  48864. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  48865. get: function () {
  48866. if (this.hand === 'left') {
  48867. return this.onMainButtonStateChangedObservable;
  48868. }
  48869. else {
  48870. throw new Error('No X button on right hand');
  48871. }
  48872. },
  48873. enumerable: true,
  48874. configurable: true
  48875. });
  48876. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  48877. get: function () {
  48878. if (this.hand === 'left') {
  48879. return this.onSecondaryButtonStateChangedObservable;
  48880. }
  48881. else {
  48882. throw new Error('No Y button on right hand');
  48883. }
  48884. },
  48885. enumerable: true,
  48886. configurable: true
  48887. });
  48888. /*
  48889. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  48890. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  48891. 2) secondary trigger (same)
  48892. 3) A (right) X (left), touch, pressed = value
  48893. 4) B / Y
  48894. 5) thumb rest
  48895. */
  48896. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  48897. var notifyObject = state; //{ state: state, changes: changes };
  48898. var triggerDirection = this.hand === 'right' ? -1 : 1;
  48899. switch (buttonIdx) {
  48900. case 0:
  48901. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  48902. return;
  48903. case 1:
  48904. if (this._defaultModel) {
  48905. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  48906. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  48907. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  48908. }
  48909. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  48910. return;
  48911. case 2:
  48912. if (this._defaultModel) {
  48913. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  48914. }
  48915. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  48916. return;
  48917. case 3:
  48918. if (this._defaultModel) {
  48919. if (notifyObject.pressed) {
  48920. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  48921. }
  48922. else {
  48923. (this._defaultModel.getChildren()[1]).position.y = 0;
  48924. }
  48925. }
  48926. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  48927. return;
  48928. case 4:
  48929. if (this._defaultModel) {
  48930. if (notifyObject.pressed) {
  48931. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  48932. }
  48933. else {
  48934. (this._defaultModel.getChildren()[2]).position.y = 0;
  48935. }
  48936. }
  48937. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  48938. return;
  48939. case 5:
  48940. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  48941. return;
  48942. }
  48943. };
  48944. return OculusTouchController;
  48945. }(WebVRController));
  48946. BABYLON.OculusTouchController = OculusTouchController;
  48947. var ViveController = (function (_super) {
  48948. __extends(ViveController, _super);
  48949. function ViveController(vrGamepad) {
  48950. var _this = _super.call(this, vrGamepad) || this;
  48951. _this.controllerType = PoseEnabledControllerType.VIVE;
  48952. return _this;
  48953. }
  48954. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  48955. var _this = this;
  48956. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  48957. /*
  48958. Parent Mesh name: ViveWand
  48959. - body
  48960. - r_gripper
  48961. - l_gripper
  48962. - menu_button
  48963. - system_button
  48964. - trackpad
  48965. - trigger
  48966. - LED
  48967. */
  48968. _this._defaultModel = newMeshes[1];
  48969. if (meshLoaded) {
  48970. meshLoaded(_this._defaultModel);
  48971. }
  48972. _this.attachToMesh(_this._defaultModel);
  48973. });
  48974. };
  48975. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  48976. get: function () {
  48977. return this.onMainButtonStateChangedObservable;
  48978. },
  48979. enumerable: true,
  48980. configurable: true
  48981. });
  48982. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  48983. get: function () {
  48984. return this.onMainButtonStateChangedObservable;
  48985. },
  48986. enumerable: true,
  48987. configurable: true
  48988. });
  48989. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  48990. get: function () {
  48991. return this.onSecondaryButtonStateChangedObservable;
  48992. },
  48993. enumerable: true,
  48994. configurable: true
  48995. });
  48996. /**
  48997. * Vive mapping:
  48998. * 0: touchpad
  48999. * 1: trigger
  49000. * 2: left AND right buttons
  49001. * 3: menu button
  49002. */
  49003. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  49004. var notifyObject = state; //{ state: state, changes: changes };
  49005. switch (buttonIdx) {
  49006. case 0:
  49007. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  49008. return;
  49009. case 1:
  49010. if (this._defaultModel) {
  49011. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  49012. }
  49013. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  49014. return;
  49015. case 2:
  49016. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  49017. return;
  49018. case 3:
  49019. if (this._defaultModel) {
  49020. if (notifyObject.pressed) {
  49021. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  49022. }
  49023. else {
  49024. (this._defaultModel.getChildren()[2]).position.y = 0;
  49025. }
  49026. }
  49027. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  49028. return;
  49029. }
  49030. };
  49031. return ViveController;
  49032. }(WebVRController));
  49033. BABYLON.ViveController = ViveController;
  49034. })(BABYLON || (BABYLON = {}));
  49035. //# sourceMappingURL=babylon.extendedGamepad.js.map
  49036. /// <reference path="babylon.targetCamera.ts" />
  49037. var BABYLON;
  49038. (function (BABYLON) {
  49039. var FollowCamera = (function (_super) {
  49040. __extends(FollowCamera, _super);
  49041. function FollowCamera(name, position, scene, lockedTarget) {
  49042. var _this = _super.call(this, name, position, scene) || this;
  49043. _this.radius = 12;
  49044. _this.rotationOffset = 0;
  49045. _this.heightOffset = 4;
  49046. _this.cameraAcceleration = 0.05;
  49047. _this.maxCameraSpeed = 20;
  49048. _this.lockedTarget = lockedTarget;
  49049. return _this;
  49050. }
  49051. FollowCamera.prototype.getRadians = function (degrees) {
  49052. return degrees * Math.PI / 180;
  49053. };
  49054. FollowCamera.prototype.follow = function (cameraTarget) {
  49055. if (!cameraTarget)
  49056. return;
  49057. var yRotation;
  49058. if (cameraTarget.rotationQuaternion) {
  49059. var rotMatrix = new BABYLON.Matrix();
  49060. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  49061. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  49062. }
  49063. else {
  49064. yRotation = cameraTarget.rotation.y;
  49065. }
  49066. var radians = this.getRadians(this.rotationOffset) + yRotation;
  49067. var targetPosition = cameraTarget.getAbsolutePosition();
  49068. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  49069. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  49070. var dx = targetX - this.position.x;
  49071. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  49072. var dz = (targetZ) - this.position.z;
  49073. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  49074. var vy = dy * this.cameraAcceleration;
  49075. var vz = dz * this.cameraAcceleration * 2;
  49076. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  49077. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49078. }
  49079. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  49080. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49081. }
  49082. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  49083. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49084. }
  49085. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  49086. this.setTarget(targetPosition);
  49087. };
  49088. FollowCamera.prototype._checkInputs = function () {
  49089. _super.prototype._checkInputs.call(this);
  49090. this.follow(this.lockedTarget);
  49091. };
  49092. FollowCamera.prototype.getClassName = function () {
  49093. return "FollowCamera";
  49094. };
  49095. return FollowCamera;
  49096. }(BABYLON.TargetCamera));
  49097. __decorate([
  49098. BABYLON.serialize()
  49099. ], FollowCamera.prototype, "radius", void 0);
  49100. __decorate([
  49101. BABYLON.serialize()
  49102. ], FollowCamera.prototype, "rotationOffset", void 0);
  49103. __decorate([
  49104. BABYLON.serialize()
  49105. ], FollowCamera.prototype, "heightOffset", void 0);
  49106. __decorate([
  49107. BABYLON.serialize()
  49108. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  49109. __decorate([
  49110. BABYLON.serialize()
  49111. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  49112. __decorate([
  49113. BABYLON.serializeAsMeshReference("lockedTargetId")
  49114. ], FollowCamera.prototype, "lockedTarget", void 0);
  49115. BABYLON.FollowCamera = FollowCamera;
  49116. var ArcFollowCamera = (function (_super) {
  49117. __extends(ArcFollowCamera, _super);
  49118. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  49119. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  49120. _this.alpha = alpha;
  49121. _this.beta = beta;
  49122. _this.radius = radius;
  49123. _this.target = target;
  49124. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  49125. _this.follow();
  49126. return _this;
  49127. }
  49128. ArcFollowCamera.prototype.follow = function () {
  49129. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  49130. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  49131. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  49132. var targetPosition = this.target.getAbsolutePosition();
  49133. this.position = targetPosition.add(this._cartesianCoordinates);
  49134. this.setTarget(targetPosition);
  49135. };
  49136. ArcFollowCamera.prototype._checkInputs = function () {
  49137. _super.prototype._checkInputs.call(this);
  49138. this.follow();
  49139. };
  49140. ArcFollowCamera.prototype.getClassName = function () {
  49141. return "ArcFollowCamera";
  49142. };
  49143. return ArcFollowCamera;
  49144. }(BABYLON.TargetCamera));
  49145. BABYLON.ArcFollowCamera = ArcFollowCamera;
  49146. })(BABYLON || (BABYLON = {}));
  49147. //# sourceMappingURL=babylon.followCamera.js.map
  49148. /// <reference path="babylon.touchCamera.ts" />
  49149. var BABYLON;
  49150. (function (BABYLON) {
  49151. // We're mainly based on the logic defined into the FreeCamera code
  49152. var UniversalCamera = (function (_super) {
  49153. __extends(UniversalCamera, _super);
  49154. //-- end properties for backward compatibility for inputs
  49155. function UniversalCamera(name, position, scene) {
  49156. var _this = _super.call(this, name, position, scene) || this;
  49157. _this.inputs.addGamepad();
  49158. return _this;
  49159. }
  49160. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  49161. //-- Begin properties for backward compatibility for inputs
  49162. get: function () {
  49163. var gamepad = this.inputs.attached["gamepad"];
  49164. if (gamepad)
  49165. return gamepad.gamepadAngularSensibility;
  49166. },
  49167. set: function (value) {
  49168. var gamepad = this.inputs.attached["gamepad"];
  49169. if (gamepad)
  49170. gamepad.gamepadAngularSensibility = value;
  49171. },
  49172. enumerable: true,
  49173. configurable: true
  49174. });
  49175. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  49176. get: function () {
  49177. var gamepad = this.inputs.attached["gamepad"];
  49178. if (gamepad)
  49179. return gamepad.gamepadMoveSensibility;
  49180. },
  49181. set: function (value) {
  49182. var gamepad = this.inputs.attached["gamepad"];
  49183. if (gamepad)
  49184. gamepad.gamepadMoveSensibility = value;
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. UniversalCamera.prototype.getClassName = function () {
  49190. return "UniversalCamera";
  49191. };
  49192. return UniversalCamera;
  49193. }(BABYLON.TouchCamera));
  49194. BABYLON.UniversalCamera = UniversalCamera;
  49195. })(BABYLON || (BABYLON = {}));
  49196. //# sourceMappingURL=babylon.universalCamera.js.map
  49197. /// <reference path="babylon.universalCamera.ts" />
  49198. var BABYLON;
  49199. (function (BABYLON) {
  49200. // We're mainly based on the logic defined into the FreeCamera code
  49201. var GamepadCamera = (function (_super) {
  49202. __extends(GamepadCamera, _super);
  49203. //-- end properties for backward compatibility for inputs
  49204. function GamepadCamera(name, position, scene) {
  49205. return _super.call(this, name, position, scene) || this;
  49206. }
  49207. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  49208. //-- Begin properties for backward compatibility for inputs
  49209. get: function () {
  49210. var gamepad = this.inputs.attached["gamepad"];
  49211. if (gamepad)
  49212. return gamepad.gamepadAngularSensibility;
  49213. },
  49214. set: function (value) {
  49215. var gamepad = this.inputs.attached["gamepad"];
  49216. if (gamepad)
  49217. gamepad.gamepadAngularSensibility = value;
  49218. },
  49219. enumerable: true,
  49220. configurable: true
  49221. });
  49222. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  49223. get: function () {
  49224. var gamepad = this.inputs.attached["gamepad"];
  49225. if (gamepad)
  49226. return gamepad.gamepadMoveSensibility;
  49227. },
  49228. set: function (value) {
  49229. var gamepad = this.inputs.attached["gamepad"];
  49230. if (gamepad)
  49231. gamepad.gamepadMoveSensibility = value;
  49232. },
  49233. enumerable: true,
  49234. configurable: true
  49235. });
  49236. GamepadCamera.prototype.getClassName = function () {
  49237. return "GamepadCamera";
  49238. };
  49239. return GamepadCamera;
  49240. }(BABYLON.UniversalCamera));
  49241. BABYLON.GamepadCamera = GamepadCamera;
  49242. })(BABYLON || (BABYLON = {}));
  49243. //# sourceMappingURL=babylon.gamepadCamera.js.map
  49244. var BABYLON;
  49245. (function (BABYLON) {
  49246. var PostProcessRenderPipelineManager = (function () {
  49247. function PostProcessRenderPipelineManager() {
  49248. this._renderPipelines = {};
  49249. }
  49250. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  49251. this._renderPipelines[renderPipeline._name] = renderPipeline;
  49252. };
  49253. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  49254. var renderPipeline = this._renderPipelines[renderPipelineName];
  49255. if (!renderPipeline) {
  49256. return;
  49257. }
  49258. renderPipeline._attachCameras(cameras, unique);
  49259. };
  49260. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  49261. var renderPipeline = this._renderPipelines[renderPipelineName];
  49262. if (!renderPipeline) {
  49263. return;
  49264. }
  49265. renderPipeline._detachCameras(cameras);
  49266. };
  49267. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  49268. var renderPipeline = this._renderPipelines[renderPipelineName];
  49269. if (!renderPipeline) {
  49270. return;
  49271. }
  49272. renderPipeline._enableEffect(renderEffectName, cameras);
  49273. };
  49274. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  49275. var renderPipeline = this._renderPipelines[renderPipelineName];
  49276. if (!renderPipeline) {
  49277. return;
  49278. }
  49279. renderPipeline._disableEffect(renderEffectName, cameras);
  49280. };
  49281. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  49282. var renderPipeline = this._renderPipelines[renderPipelineName];
  49283. if (!renderPipeline) {
  49284. return;
  49285. }
  49286. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  49287. };
  49288. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  49289. var renderPipeline = this._renderPipelines[renderPipelineName];
  49290. if (!renderPipeline) {
  49291. return;
  49292. }
  49293. renderPipeline._disableDisplayOnlyPass(cameras);
  49294. };
  49295. PostProcessRenderPipelineManager.prototype.update = function () {
  49296. for (var renderPipelineName in this._renderPipelines) {
  49297. var pipeline = this._renderPipelines[renderPipelineName];
  49298. if (!pipeline.isSupported) {
  49299. pipeline.dispose();
  49300. delete this._renderPipelines[renderPipelineName];
  49301. }
  49302. else {
  49303. pipeline._update();
  49304. }
  49305. }
  49306. };
  49307. return PostProcessRenderPipelineManager;
  49308. }());
  49309. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  49310. })(BABYLON || (BABYLON = {}));
  49311. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  49312. var BABYLON;
  49313. (function (BABYLON) {
  49314. var PostProcessRenderPass = (function () {
  49315. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  49316. this._enabled = true;
  49317. this._refCount = 0;
  49318. this._name = name;
  49319. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  49320. this.setRenderList(renderList);
  49321. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  49322. this._renderTexture.onAfterRenderObservable.add(afterRender);
  49323. this._scene = scene;
  49324. this._renderList = renderList;
  49325. }
  49326. // private
  49327. PostProcessRenderPass.prototype._incRefCount = function () {
  49328. if (this._refCount === 0) {
  49329. this._scene.customRenderTargets.push(this._renderTexture);
  49330. }
  49331. return ++this._refCount;
  49332. };
  49333. PostProcessRenderPass.prototype._decRefCount = function () {
  49334. this._refCount--;
  49335. if (this._refCount <= 0) {
  49336. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  49337. }
  49338. return this._refCount;
  49339. };
  49340. PostProcessRenderPass.prototype._update = function () {
  49341. this.setRenderList(this._renderList);
  49342. };
  49343. // public
  49344. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  49345. this._renderTexture.renderList = renderList;
  49346. };
  49347. PostProcessRenderPass.prototype.getRenderTexture = function () {
  49348. return this._renderTexture;
  49349. };
  49350. return PostProcessRenderPass;
  49351. }());
  49352. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  49353. })(BABYLON || (BABYLON = {}));
  49354. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  49355. var BABYLON;
  49356. (function (BABYLON) {
  49357. var PostProcessRenderEffect = (function () {
  49358. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  49359. this._engine = engine;
  49360. this._name = name;
  49361. this._singleInstance = singleInstance || true;
  49362. this._getPostProcess = getPostProcess;
  49363. this._cameras = [];
  49364. this._indicesForCamera = [];
  49365. this._postProcesses = {};
  49366. this._renderPasses = {};
  49367. this._renderEffectAsPasses = {};
  49368. }
  49369. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  49370. get: function () {
  49371. for (var index in this._postProcesses) {
  49372. if (!this._postProcesses[index].isSupported) {
  49373. return false;
  49374. }
  49375. }
  49376. return true;
  49377. },
  49378. enumerable: true,
  49379. configurable: true
  49380. });
  49381. PostProcessRenderEffect.prototype._update = function () {
  49382. for (var renderPassName in this._renderPasses) {
  49383. this._renderPasses[renderPassName]._update();
  49384. }
  49385. };
  49386. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  49387. this._renderPasses[renderPass._name] = renderPass;
  49388. this._linkParameters();
  49389. };
  49390. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  49391. delete this._renderPasses[renderPass._name];
  49392. this._linkParameters();
  49393. };
  49394. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  49395. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  49396. this._linkParameters();
  49397. };
  49398. PostProcessRenderEffect.prototype.getPass = function (passName) {
  49399. for (var renderPassName in this._renderPasses) {
  49400. if (renderPassName === passName) {
  49401. return this._renderPasses[passName];
  49402. }
  49403. }
  49404. };
  49405. PostProcessRenderEffect.prototype.emptyPasses = function () {
  49406. this._renderPasses = {};
  49407. this._linkParameters();
  49408. };
  49409. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  49410. var cameraKey;
  49411. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49412. for (var i = 0; i < _cam.length; i++) {
  49413. var camera = _cam[i];
  49414. var cameraName = camera.name;
  49415. if (this._singleInstance) {
  49416. cameraKey = 0;
  49417. }
  49418. else {
  49419. cameraKey = cameraName;
  49420. }
  49421. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  49422. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  49423. if (!this._indicesForCamera[cameraName]) {
  49424. this._indicesForCamera[cameraName] = [];
  49425. }
  49426. this._indicesForCamera[cameraName].push(index);
  49427. if (this._cameras.indexOf(camera) === -1) {
  49428. this._cameras[cameraName] = camera;
  49429. }
  49430. for (var passName in this._renderPasses) {
  49431. this._renderPasses[passName]._incRefCount();
  49432. }
  49433. }
  49434. this._linkParameters();
  49435. };
  49436. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  49437. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49438. for (var i = 0; i < _cam.length; i++) {
  49439. var camera = _cam[i];
  49440. var cameraName = camera.name;
  49441. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  49442. var index = this._cameras.indexOf(cameraName);
  49443. this._indicesForCamera.splice(index, 1);
  49444. this._cameras.splice(index, 1);
  49445. for (var passName in this._renderPasses) {
  49446. this._renderPasses[passName]._decRefCount();
  49447. }
  49448. }
  49449. };
  49450. PostProcessRenderEffect.prototype._enable = function (cameras) {
  49451. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49452. for (var i = 0; i < _cam.length; i++) {
  49453. var camera = _cam[i];
  49454. var cameraName = camera.name;
  49455. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  49456. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  49457. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  49458. }
  49459. }
  49460. for (var passName in this._renderPasses) {
  49461. this._renderPasses[passName]._incRefCount();
  49462. }
  49463. }
  49464. };
  49465. PostProcessRenderEffect.prototype._disable = function (cameras) {
  49466. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49467. for (var i = 0; i < _cam.length; i++) {
  49468. var camera = _cam[i];
  49469. var cameraName = camera.Name;
  49470. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  49471. for (var passName in this._renderPasses) {
  49472. this._renderPasses[passName]._decRefCount();
  49473. }
  49474. }
  49475. };
  49476. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  49477. if (this._singleInstance) {
  49478. return this._postProcesses[0];
  49479. }
  49480. else {
  49481. return this._postProcesses[camera.name];
  49482. }
  49483. };
  49484. PostProcessRenderEffect.prototype._linkParameters = function () {
  49485. var _this = this;
  49486. for (var index in this._postProcesses) {
  49487. if (this.applyParameters) {
  49488. this.applyParameters(this._postProcesses[index]);
  49489. }
  49490. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  49491. _this._linkTextures(effect);
  49492. });
  49493. }
  49494. };
  49495. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  49496. for (var renderPassName in this._renderPasses) {
  49497. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  49498. }
  49499. for (var renderEffectName in this._renderEffectAsPasses) {
  49500. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  49501. }
  49502. };
  49503. return PostProcessRenderEffect;
  49504. }());
  49505. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  49506. })(BABYLON || (BABYLON = {}));
  49507. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  49508. var BABYLON;
  49509. (function (BABYLON) {
  49510. var PostProcessRenderPipeline = (function () {
  49511. function PostProcessRenderPipeline(engine, name) {
  49512. this._engine = engine;
  49513. this._name = name;
  49514. this._renderEffects = new Array();
  49515. this._renderEffectsForIsolatedPass = new Array();
  49516. this._cameras = [];
  49517. }
  49518. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  49519. get: function () {
  49520. for (var renderEffectName in this._renderEffects) {
  49521. if (!this._renderEffects[renderEffectName].isSupported) {
  49522. return false;
  49523. }
  49524. }
  49525. return true;
  49526. },
  49527. enumerable: true,
  49528. configurable: true
  49529. });
  49530. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  49531. this._renderEffects[renderEffect._name] = renderEffect;
  49532. };
  49533. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  49534. var renderEffects = this._renderEffects[renderEffectName];
  49535. if (!renderEffects) {
  49536. return;
  49537. }
  49538. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  49539. };
  49540. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  49541. var renderEffects = this._renderEffects[renderEffectName];
  49542. if (!renderEffects) {
  49543. return;
  49544. }
  49545. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  49546. };
  49547. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  49548. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49549. var indicesToDelete = [];
  49550. var i;
  49551. for (i = 0; i < _cam.length; i++) {
  49552. var camera = _cam[i];
  49553. var cameraName = camera.name;
  49554. if (this._cameras.indexOf(camera) === -1) {
  49555. this._cameras[cameraName] = camera;
  49556. }
  49557. else if (unique) {
  49558. indicesToDelete.push(i);
  49559. }
  49560. }
  49561. for (i = 0; i < indicesToDelete.length; i++) {
  49562. cameras.splice(indicesToDelete[i], 1);
  49563. }
  49564. for (var renderEffectName in this._renderEffects) {
  49565. this._renderEffects[renderEffectName]._attachCameras(_cam);
  49566. }
  49567. };
  49568. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  49569. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49570. for (var renderEffectName in this._renderEffects) {
  49571. this._renderEffects[renderEffectName]._detachCameras(_cam);
  49572. }
  49573. for (var i = 0; i < _cam.length; i++) {
  49574. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  49575. }
  49576. };
  49577. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  49578. var _this = this;
  49579. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49580. var pass = null;
  49581. var renderEffectName;
  49582. for (renderEffectName in this._renderEffects) {
  49583. pass = this._renderEffects[renderEffectName].getPass(passName);
  49584. if (pass != null) {
  49585. break;
  49586. }
  49587. }
  49588. if (pass === null) {
  49589. return;
  49590. }
  49591. for (renderEffectName in this._renderEffects) {
  49592. this._renderEffects[renderEffectName]._disable(_cam);
  49593. }
  49594. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  49595. for (var i = 0; i < _cam.length; i++) {
  49596. var camera = _cam[i];
  49597. var cameraName = camera.name;
  49598. 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); });
  49599. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  49600. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  49601. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  49602. }
  49603. };
  49604. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  49605. var _this = this;
  49606. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49607. for (var i = 0; i < _cam.length; i++) {
  49608. var camera = _cam[i];
  49609. var cameraName = camera.name;
  49610. 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); });
  49611. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  49612. }
  49613. for (var renderEffectName in this._renderEffects) {
  49614. this._renderEffects[renderEffectName]._enable(_cam);
  49615. }
  49616. };
  49617. PostProcessRenderPipeline.prototype._update = function () {
  49618. for (var renderEffectName in this._renderEffects) {
  49619. this._renderEffects[renderEffectName]._update();
  49620. }
  49621. for (var i = 0; i < this._cameras.length; i++) {
  49622. var cameraName = this._cameras[i].name;
  49623. if (this._renderEffectsForIsolatedPass[cameraName]) {
  49624. this._renderEffectsForIsolatedPass[cameraName]._update();
  49625. }
  49626. }
  49627. };
  49628. PostProcessRenderPipeline.prototype._reset = function () {
  49629. this._renderEffects = new Array();
  49630. this._renderEffectsForIsolatedPass = new Array();
  49631. };
  49632. PostProcessRenderPipeline.prototype.dispose = function () {
  49633. // Must be implemented by children
  49634. };
  49635. return PostProcessRenderPipeline;
  49636. }());
  49637. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  49638. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  49639. __decorate([
  49640. BABYLON.serialize()
  49641. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  49642. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  49643. })(BABYLON || (BABYLON = {}));
  49644. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  49645. var BABYLON;
  49646. (function (BABYLON) {
  49647. var DepthRenderer = (function () {
  49648. function DepthRenderer(scene, type) {
  49649. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  49650. var _this = this;
  49651. this._viewMatrix = BABYLON.Matrix.Zero();
  49652. this._projectionMatrix = BABYLON.Matrix.Zero();
  49653. this._transformMatrix = BABYLON.Matrix.Zero();
  49654. this._worldViewProjection = BABYLON.Matrix.Zero();
  49655. this._scene = scene;
  49656. var engine = scene.getEngine();
  49657. // Render target
  49658. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  49659. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49660. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49661. this._depthMap.refreshRate = 1;
  49662. this._depthMap.renderParticles = false;
  49663. this._depthMap.renderList = null;
  49664. // set default depth value to 1.0 (far away)
  49665. this._depthMap.onClearObservable.add(function (engine) {
  49666. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  49667. });
  49668. // Custom render function
  49669. var renderSubMesh = function (subMesh) {
  49670. var mesh = subMesh.getRenderingMesh();
  49671. var scene = _this._scene;
  49672. var engine = scene.getEngine();
  49673. // Culling
  49674. engine.setState(subMesh.getMaterial().backFaceCulling);
  49675. // Managing instances
  49676. var batch = mesh._getInstancesRenderList(subMesh._id);
  49677. if (batch.mustReturn) {
  49678. return;
  49679. }
  49680. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  49681. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  49682. engine.enableEffect(_this._effect);
  49683. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  49684. var material = subMesh.getMaterial();
  49685. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  49686. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  49687. // Alpha test
  49688. if (material && material.needAlphaTesting()) {
  49689. var alphaTexture = material.getAlphaTestTexture();
  49690. _this._effect.setTexture("diffuseSampler", alphaTexture);
  49691. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  49692. }
  49693. // Bones
  49694. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49695. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49696. }
  49697. // Draw
  49698. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  49699. }
  49700. };
  49701. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  49702. var index;
  49703. for (index = 0; index < opaqueSubMeshes.length; index++) {
  49704. renderSubMesh(opaqueSubMeshes.data[index]);
  49705. }
  49706. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  49707. renderSubMesh(alphaTestSubMeshes.data[index]);
  49708. }
  49709. };
  49710. }
  49711. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  49712. var material = subMesh.getMaterial();
  49713. if (material.disableDepthWrite) {
  49714. return false;
  49715. }
  49716. var defines = [];
  49717. var attribs = [BABYLON.VertexBuffer.PositionKind];
  49718. var mesh = subMesh.getMesh();
  49719. var scene = mesh.getScene();
  49720. // Alpha test
  49721. if (material && material.needAlphaTesting()) {
  49722. defines.push("#define ALPHATEST");
  49723. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49724. attribs.push(BABYLON.VertexBuffer.UVKind);
  49725. defines.push("#define UV1");
  49726. }
  49727. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49728. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49729. defines.push("#define UV2");
  49730. }
  49731. }
  49732. // Bones
  49733. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49736. if (mesh.numBoneInfluencers > 4) {
  49737. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49738. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49739. }
  49740. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49741. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49742. }
  49743. else {
  49744. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49745. }
  49746. // Instances
  49747. if (useInstances) {
  49748. defines.push("#define INSTANCES");
  49749. attribs.push("world0");
  49750. attribs.push("world1");
  49751. attribs.push("world2");
  49752. attribs.push("world3");
  49753. }
  49754. // Get correct effect
  49755. var join = defines.join("\n");
  49756. if (this._cachedDefines !== join) {
  49757. this._cachedDefines = join;
  49758. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  49759. }
  49760. return this._effect.isReady();
  49761. };
  49762. DepthRenderer.prototype.getDepthMap = function () {
  49763. return this._depthMap;
  49764. };
  49765. // Methods
  49766. DepthRenderer.prototype.dispose = function () {
  49767. this._depthMap.dispose();
  49768. };
  49769. return DepthRenderer;
  49770. }());
  49771. BABYLON.DepthRenderer = DepthRenderer;
  49772. })(BABYLON || (BABYLON = {}));
  49773. //# sourceMappingURL=babylon.depthRenderer.js.map
  49774. var BABYLON;
  49775. (function (BABYLON) {
  49776. var SSAORenderingPipeline = (function (_super) {
  49777. __extends(SSAORenderingPipeline, _super);
  49778. /**
  49779. * @constructor
  49780. * @param {string} name - The rendering pipeline name
  49781. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49782. * @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 }
  49783. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49784. */
  49785. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  49786. var _this = _super.call(this, scene.getEngine(), name) || this;
  49787. // Members
  49788. /**
  49789. * The PassPostProcess id in the pipeline that contains the original scene color
  49790. * @type {string}
  49791. */
  49792. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  49793. /**
  49794. * The SSAO PostProcess id in the pipeline
  49795. * @type {string}
  49796. */
  49797. _this.SSAORenderEffect = "SSAORenderEffect";
  49798. /**
  49799. * The horizontal blur PostProcess id in the pipeline
  49800. * @type {string}
  49801. */
  49802. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  49803. /**
  49804. * The vertical blur PostProcess id in the pipeline
  49805. * @type {string}
  49806. */
  49807. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  49808. /**
  49809. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  49810. * @type {string}
  49811. */
  49812. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  49813. /**
  49814. * The output strength of the SSAO post-process. Default value is 1.0.
  49815. * @type {number}
  49816. */
  49817. _this.totalStrength = 1.0;
  49818. /**
  49819. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  49820. * @type {number}
  49821. */
  49822. _this.radius = 0.0001;
  49823. /**
  49824. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  49825. * Must not be equal to fallOff and superior to fallOff.
  49826. * Default value is 0.975
  49827. * @type {number}
  49828. */
  49829. _this.area = 0.0075;
  49830. /**
  49831. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  49832. * Must not be equal to area and inferior to area.
  49833. * Default value is 0.0
  49834. * @type {number}
  49835. */
  49836. _this.fallOff = 0.000001;
  49837. /**
  49838. * The base color of the SSAO post-process
  49839. * The final result is "base + ssao" between [0, 1]
  49840. * @type {number}
  49841. */
  49842. _this.base = 0.5;
  49843. _this._firstUpdate = true;
  49844. _this._scene = scene;
  49845. // Set up assets
  49846. _this._createRandomTexture();
  49847. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  49848. var ssaoRatio = ratio.ssaoRatio || ratio;
  49849. var combineRatio = ratio.combineRatio || ratio;
  49850. _this._ratio = {
  49851. ssaoRatio: ssaoRatio,
  49852. combineRatio: combineRatio
  49853. };
  49854. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49855. _this._createSSAOPostProcess(ssaoRatio);
  49856. _this._createBlurPostProcess(ssaoRatio);
  49857. _this._createSSAOCombinePostProcess(combineRatio);
  49858. // Set up pipeline
  49859. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  49860. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  49861. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  49862. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  49863. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  49864. // Finish
  49865. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49866. if (cameras)
  49867. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49868. return _this;
  49869. }
  49870. // Public Methods
  49871. /**
  49872. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  49873. */
  49874. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  49875. if (disableDepthRender === void 0) { disableDepthRender = false; }
  49876. for (var i = 0; i < this._scene.cameras.length; i++) {
  49877. var camera = this._scene.cameras[i];
  49878. this._originalColorPostProcess.dispose(camera);
  49879. this._ssaoPostProcess.dispose(camera);
  49880. this._blurHPostProcess.dispose(camera);
  49881. this._blurVPostProcess.dispose(camera);
  49882. this._ssaoCombinePostProcess.dispose(camera);
  49883. }
  49884. this._randomTexture.dispose();
  49885. if (disableDepthRender)
  49886. this._scene.disableDepthRenderer();
  49887. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49888. _super.prototype.dispose.call(this);
  49889. };
  49890. // Private Methods
  49891. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  49892. var _this = this;
  49893. /*
  49894. var samplerOffsets = [
  49895. -8.0, -6.0, -4.0, -2.0,
  49896. 0.0,
  49897. 2.0, 4.0, 6.0, 8.0
  49898. ];
  49899. */
  49900. var samples = 16;
  49901. var samplerOffsets = [];
  49902. for (var i = -8; i < 8; i++) {
  49903. samplerOffsets.push(i * 2);
  49904. }
  49905. 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");
  49906. this._blurHPostProcess.onApply = function (effect) {
  49907. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  49908. effect.setTexture("depthSampler", _this._depthTexture);
  49909. if (_this._firstUpdate) {
  49910. effect.setArray("samplerOffsets", samplerOffsets);
  49911. }
  49912. };
  49913. 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");
  49914. this._blurVPostProcess.onApply = function (effect) {
  49915. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  49916. effect.setTexture("depthSampler", _this._depthTexture);
  49917. if (_this._firstUpdate) {
  49918. effect.setArray("samplerOffsets", samplerOffsets);
  49919. _this._firstUpdate = false;
  49920. }
  49921. };
  49922. };
  49923. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  49924. var _this = this;
  49925. var numSamples = 16;
  49926. var sampleSphere = [
  49927. 0.5381, 0.1856, -0.4319,
  49928. 0.1379, 0.2486, 0.4430,
  49929. 0.3371, 0.5679, -0.0057,
  49930. -0.6999, -0.0451, -0.0019,
  49931. 0.0689, -0.1598, -0.8547,
  49932. 0.0560, 0.0069, -0.1843,
  49933. -0.0146, 0.1402, 0.0762,
  49934. 0.0100, -0.1924, -0.0344,
  49935. -0.3577, -0.5301, -0.4358,
  49936. -0.3169, 0.1063, 0.0158,
  49937. 0.0103, -0.5869, 0.0046,
  49938. -0.0897, -0.4940, 0.3287,
  49939. 0.7119, -0.0154, -0.0918,
  49940. -0.0533, 0.0596, -0.5411,
  49941. 0.0352, -0.0631, 0.5460,
  49942. -0.4776, 0.2847, -0.0271
  49943. ];
  49944. var samplesFactor = 1.0 / numSamples;
  49945. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  49946. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  49947. "area", "fallOff", "base", "range", "viewport"
  49948. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  49949. var viewport = new BABYLON.Vector2(0, 0);
  49950. this._ssaoPostProcess.onApply = function (effect) {
  49951. if (_this._firstUpdate) {
  49952. effect.setArray3("sampleSphere", sampleSphere);
  49953. effect.setFloat("samplesFactor", samplesFactor);
  49954. effect.setFloat("randTextureTiles", 4.0);
  49955. }
  49956. effect.setFloat("totalStrength", _this.totalStrength);
  49957. effect.setFloat("radius", _this.radius);
  49958. effect.setFloat("area", _this.area);
  49959. effect.setFloat("fallOff", _this.fallOff);
  49960. effect.setFloat("base", _this.base);
  49961. effect.setTexture("textureSampler", _this._depthTexture);
  49962. effect.setTexture("randomSampler", _this._randomTexture);
  49963. };
  49964. };
  49965. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  49966. var _this = this;
  49967. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49968. this._ssaoCombinePostProcess.onApply = function (effect) {
  49969. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49970. };
  49971. };
  49972. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  49973. var size = 512;
  49974. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49975. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49976. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49977. var context = this._randomTexture.getContext();
  49978. var rand = function (min, max) {
  49979. return Math.random() * (max - min) + min;
  49980. };
  49981. var randVector = BABYLON.Vector3.Zero();
  49982. for (var x = 0; x < size; x++) {
  49983. for (var y = 0; y < size; y++) {
  49984. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  49985. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  49986. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  49987. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49988. context.fillRect(x, y, 1, 1);
  49989. }
  49990. }
  49991. this._randomTexture.update(false);
  49992. };
  49993. return SSAORenderingPipeline;
  49994. }(BABYLON.PostProcessRenderPipeline));
  49995. __decorate([
  49996. BABYLON.serialize()
  49997. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  49998. __decorate([
  49999. BABYLON.serialize()
  50000. ], SSAORenderingPipeline.prototype, "radius", void 0);
  50001. __decorate([
  50002. BABYLON.serialize()
  50003. ], SSAORenderingPipeline.prototype, "area", void 0);
  50004. __decorate([
  50005. BABYLON.serialize()
  50006. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  50007. __decorate([
  50008. BABYLON.serialize()
  50009. ], SSAORenderingPipeline.prototype, "base", void 0);
  50010. __decorate([
  50011. BABYLON.serialize()
  50012. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  50013. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  50014. })(BABYLON || (BABYLON = {}));
  50015. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  50016. var BABYLON;
  50017. (function (BABYLON) {
  50018. var SSAO2RenderingPipeline = (function (_super) {
  50019. __extends(SSAO2RenderingPipeline, _super);
  50020. /**
  50021. * @constructor
  50022. * @param {string} name - The rendering pipeline name
  50023. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50024. * @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 }
  50025. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50026. */
  50027. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  50028. var _this = _super.call(this, scene.getEngine(), name) || this;
  50029. // Members
  50030. /**
  50031. * The PassPostProcess id in the pipeline that contains the original scene color
  50032. * @type {string}
  50033. */
  50034. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  50035. /**
  50036. * The SSAO PostProcess id in the pipeline
  50037. * @type {string}
  50038. */
  50039. _this.SSAORenderEffect = "SSAORenderEffect";
  50040. /**
  50041. * The horizontal blur PostProcess id in the pipeline
  50042. * @type {string}
  50043. */
  50044. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  50045. /**
  50046. * The vertical blur PostProcess id in the pipeline
  50047. * @type {string}
  50048. */
  50049. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  50050. /**
  50051. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  50052. * @type {string}
  50053. */
  50054. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  50055. /**
  50056. * The output strength of the SSAO post-process. Default value is 1.0.
  50057. * @type {number}
  50058. */
  50059. _this.totalStrength = 1.0;
  50060. /**
  50061. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  50062. * @type {number}
  50063. */
  50064. _this.maxZ = 100.0;
  50065. /**
  50066. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  50067. * @type {number}
  50068. */
  50069. _this.minZAspect = 0.2;
  50070. /**
  50071. * Number of samples used for the SSAO calculations. Default value is 8
  50072. * @type {number}
  50073. */
  50074. _this._samples = 8;
  50075. /**
  50076. * Are we using bilateral blur ?
  50077. * @type {boolean}
  50078. */
  50079. _this._expensiveBlur = true;
  50080. /**
  50081. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  50082. * @type {number}
  50083. */
  50084. _this.radius = 2.0;
  50085. /**
  50086. * The base color of the SSAO post-process
  50087. * The final result is "base + ssao" between [0, 1]
  50088. * @type {number}
  50089. */
  50090. _this.base = 0.1;
  50091. _this._firstUpdate = true;
  50092. _this._scene = scene;
  50093. if (!_this.isSupported) {
  50094. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  50095. return _this;
  50096. }
  50097. var ssaoRatio = ratio.ssaoRatio || ratio;
  50098. var blurRatio = ratio.blurRatio || ratio;
  50099. _this._ratio = {
  50100. ssaoRatio: ssaoRatio,
  50101. blurRatio: blurRatio
  50102. };
  50103. // Set up assets
  50104. _this._createRandomTexture();
  50105. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  50106. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  50107. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  50108. _this._createSSAOPostProcess(1.0);
  50109. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  50110. _this._createSSAOCombinePostProcess(blurRatio);
  50111. // Set up pipeline
  50112. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  50113. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  50114. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  50115. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  50116. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  50117. // Finish
  50118. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50119. if (cameras)
  50120. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50121. return _this;
  50122. }
  50123. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  50124. get: function () {
  50125. return this._samples;
  50126. },
  50127. set: function (n) {
  50128. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  50129. this._samples = n;
  50130. this._sampleSphere = this._generateHemisphere();
  50131. this._firstUpdate = true;
  50132. },
  50133. enumerable: true,
  50134. configurable: true
  50135. });
  50136. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  50137. get: function () {
  50138. return this._expensiveBlur;
  50139. },
  50140. set: function (b) {
  50141. 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"]);
  50142. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  50143. this._expensiveBlur = b;
  50144. this._firstUpdate = true;
  50145. },
  50146. enumerable: true,
  50147. configurable: true
  50148. });
  50149. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  50150. /**
  50151. * Support test.
  50152. * @type {boolean}
  50153. */
  50154. get: function () {
  50155. var engine = BABYLON.Engine.LastCreatedEngine;
  50156. return engine.webGLVersion > 1;
  50157. },
  50158. enumerable: true,
  50159. configurable: true
  50160. });
  50161. // Public Methods
  50162. /**
  50163. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  50164. */
  50165. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  50166. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  50167. for (var i = 0; i < this._scene.cameras.length; i++) {
  50168. var camera = this._scene.cameras[i];
  50169. this._originalColorPostProcess.dispose(camera);
  50170. this._ssaoPostProcess.dispose(camera);
  50171. this._blurHPostProcess.dispose(camera);
  50172. this._blurVPostProcess.dispose(camera);
  50173. this._ssaoCombinePostProcess.dispose(camera);
  50174. }
  50175. this._randomTexture.dispose();
  50176. if (disableGeometryBufferRenderer)
  50177. this._scene.disableGeometryBufferRenderer();
  50178. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50179. _super.prototype.dispose.call(this);
  50180. };
  50181. // Private Methods
  50182. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  50183. var _this = this;
  50184. var samples = 16;
  50185. this._samplerOffsets = [];
  50186. var expensive = this.expensiveBlur;
  50187. for (var i = -8; i < 8; i++) {
  50188. this._samplerOffsets.push(i * 2 + 0.5);
  50189. }
  50190. 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");
  50191. this._blurHPostProcess.onApply = function (effect) {
  50192. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  50193. effect.setFloat("near", _this._scene.activeCamera.minZ);
  50194. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  50195. effect.setFloat("radius", _this.radius);
  50196. effect.setTexture("depthSampler", _this._depthTexture);
  50197. if (_this._firstUpdate) {
  50198. effect.setArray("samplerOffsets", _this._samplerOffsets);
  50199. }
  50200. };
  50201. 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");
  50202. this._blurVPostProcess.onApply = function (effect) {
  50203. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  50204. effect.setFloat("near", _this._scene.activeCamera.minZ);
  50205. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  50206. effect.setFloat("radius", _this.radius);
  50207. effect.setTexture("depthSampler", _this._depthTexture);
  50208. if (_this._firstUpdate) {
  50209. effect.setArray("samplerOffsets", _this._samplerOffsets);
  50210. _this._firstUpdate = false;
  50211. }
  50212. };
  50213. };
  50214. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  50215. var numSamples = this.samples;
  50216. var result = [];
  50217. var vector, scale;
  50218. var rand = function (min, max) {
  50219. return Math.random() * (max - min) + min;
  50220. };
  50221. var lerp = function (start, end, percent) {
  50222. return (start + percent * (end - start));
  50223. };
  50224. var i = 0;
  50225. var normal = new BABYLON.Vector3(0, 0, 1);
  50226. while (i < numSamples) {
  50227. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  50228. vector.normalize();
  50229. scale = i / numSamples;
  50230. scale = lerp(0.1, 1.0, scale * scale);
  50231. vector.scaleInPlace(scale);
  50232. result.push(vector.x, vector.y, vector.z);
  50233. i++;
  50234. }
  50235. return result;
  50236. };
  50237. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  50238. var _this = this;
  50239. var numSamples = this.samples;
  50240. this._sampleSphere = this._generateHemisphere();
  50241. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  50242. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  50243. "base", "range", "projection", "near", "far", "texelSize",
  50244. "xViewport", "yViewport", "maxZ", "minZAspect"
  50245. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  50246. this._ssaoPostProcess.onApply = function (effect) {
  50247. if (_this._firstUpdate) {
  50248. effect.setArray3("sampleSphere", _this._sampleSphere);
  50249. effect.setFloat("randTextureTiles", 4.0);
  50250. }
  50251. effect.setFloat("samplesFactor", 1 / _this.samples);
  50252. effect.setFloat("totalStrength", _this.totalStrength);
  50253. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  50254. effect.setFloat("radius", _this.radius);
  50255. effect.setFloat("maxZ", _this.maxZ);
  50256. effect.setFloat("minZAspect", _this.minZAspect);
  50257. effect.setFloat("base", _this.base);
  50258. effect.setFloat("near", _this._scene.activeCamera.minZ);
  50259. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  50260. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  50261. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  50262. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  50263. effect.setTexture("textureSampler", _this._depthTexture);
  50264. effect.setTexture("normalSampler", _this._normalTexture);
  50265. effect.setTexture("randomSampler", _this._randomTexture);
  50266. };
  50267. };
  50268. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  50269. var _this = this;
  50270. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50271. this._ssaoCombinePostProcess.onApply = function (effect) {
  50272. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  50273. };
  50274. };
  50275. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  50276. var size = 512;
  50277. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  50278. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50279. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50280. var context = this._randomTexture.getContext();
  50281. var rand = function (min, max) {
  50282. return Math.random() * (max - min) + min;
  50283. };
  50284. var randVector = BABYLON.Vector3.Zero();
  50285. for (var x = 0; x < size; x++) {
  50286. for (var y = 0; y < size; y++) {
  50287. randVector.x = rand(0.0, 1.0);
  50288. randVector.y = rand(0.0, 1.0);
  50289. randVector.z = 0.0;
  50290. randVector.normalize();
  50291. randVector.scaleInPlace(255);
  50292. randVector.x = Math.floor(randVector.x);
  50293. randVector.y = Math.floor(randVector.y);
  50294. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  50295. context.fillRect(x, y, 1, 1);
  50296. }
  50297. }
  50298. this._randomTexture.update(false);
  50299. };
  50300. return SSAO2RenderingPipeline;
  50301. }(BABYLON.PostProcessRenderPipeline));
  50302. __decorate([
  50303. BABYLON.serialize()
  50304. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  50305. __decorate([
  50306. BABYLON.serialize()
  50307. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  50308. __decorate([
  50309. BABYLON.serialize()
  50310. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  50311. __decorate([
  50312. BABYLON.serialize("samples")
  50313. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  50314. __decorate([
  50315. BABYLON.serialize("expensiveBlur")
  50316. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  50317. __decorate([
  50318. BABYLON.serialize()
  50319. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  50320. __decorate([
  50321. BABYLON.serialize()
  50322. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  50323. __decorate([
  50324. BABYLON.serialize()
  50325. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  50326. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  50327. })(BABYLON || (BABYLON = {}));
  50328. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  50329. // BABYLON.JS Chromatic Aberration GLSL Shader
  50330. // Author: Olivier Guyot
  50331. // Separates very slightly R, G and B colors on the edges of the screen
  50332. // Inspired by Francois Tarlier & Martins Upitis
  50333. var BABYLON;
  50334. (function (BABYLON) {
  50335. var LensRenderingPipeline = (function (_super) {
  50336. __extends(LensRenderingPipeline, _super);
  50337. /**
  50338. * @constructor
  50339. *
  50340. * Effect parameters are as follow:
  50341. * {
  50342. * chromatic_aberration: number; // from 0 to x (1 for realism)
  50343. * edge_blur: number; // from 0 to x (1 for realism)
  50344. * distortion: number; // from 0 to x (1 for realism)
  50345. * grain_amount: number; // from 0 to 1
  50346. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  50347. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  50348. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  50349. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  50350. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  50351. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  50352. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  50353. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  50354. * }
  50355. * Note: if an effect parameter is unset, effect is disabled
  50356. *
  50357. * @param {string} name - The rendering pipeline name
  50358. * @param {object} parameters - An object containing all parameters (see above)
  50359. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50360. * @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)
  50361. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50362. */
  50363. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  50364. if (ratio === void 0) { ratio = 1.0; }
  50365. var _this = _super.call(this, scene.getEngine(), name) || this;
  50366. // Lens effects can be of the following:
  50367. // - chromatic aberration (slight shift of RGB colors)
  50368. // - blur on the edge of the lens
  50369. // - lens distortion
  50370. // - depth-of-field blur & highlights enhancing
  50371. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  50372. // - grain effect (noise or custom texture)
  50373. // Two additional texture samplers are needed:
  50374. // - depth map (for depth-of-field)
  50375. // - grain texture
  50376. /**
  50377. * The chromatic aberration PostProcess id in the pipeline
  50378. * @type {string}
  50379. */
  50380. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  50381. /**
  50382. * The highlights enhancing PostProcess id in the pipeline
  50383. * @type {string}
  50384. */
  50385. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  50386. /**
  50387. * The depth-of-field PostProcess id in the pipeline
  50388. * @type {string}
  50389. */
  50390. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  50391. _this._scene = scene;
  50392. // Fetch texture samplers
  50393. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  50394. if (parameters.grain_texture) {
  50395. _this._grainTexture = parameters.grain_texture;
  50396. }
  50397. else {
  50398. _this._createGrainTexture();
  50399. }
  50400. // save parameters
  50401. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  50402. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  50403. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  50404. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  50405. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  50406. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  50407. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  50408. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  50409. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  50410. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  50411. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  50412. // Create effects
  50413. _this._createChromaticAberrationPostProcess(ratio);
  50414. _this._createHighlightsPostProcess(ratio);
  50415. _this._createDepthOfFieldPostProcess(ratio / 4);
  50416. // Set up pipeline
  50417. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  50418. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  50419. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  50420. if (_this._highlightsGain === -1) {
  50421. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  50422. }
  50423. // Finish
  50424. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50425. if (cameras) {
  50426. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50427. }
  50428. return _this;
  50429. }
  50430. // public methods (self explanatory)
  50431. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  50432. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  50433. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  50434. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  50435. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  50436. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  50437. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  50438. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  50439. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  50440. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  50441. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  50442. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  50443. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  50444. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  50445. };
  50446. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  50447. this._highlightsPostProcess.updateEffect();
  50448. };
  50449. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  50450. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  50451. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  50452. this._highlightsGain = amount;
  50453. };
  50454. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  50455. if (this._highlightsGain === -1) {
  50456. this._highlightsGain = 1.0;
  50457. }
  50458. this._highlightsThreshold = amount;
  50459. };
  50460. LensRenderingPipeline.prototype.disableHighlights = function () {
  50461. this._highlightsGain = -1;
  50462. };
  50463. /**
  50464. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  50465. */
  50466. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  50467. if (disableDepthRender === void 0) { disableDepthRender = false; }
  50468. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50469. this._chromaticAberrationPostProcess = undefined;
  50470. this._highlightsPostProcess = undefined;
  50471. this._depthOfFieldPostProcess = undefined;
  50472. this._grainTexture.dispose();
  50473. if (disableDepthRender)
  50474. this._scene.disableDepthRenderer();
  50475. };
  50476. // colors shifting and distortion
  50477. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  50478. var _this = this;
  50479. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  50480. [], // samplers
  50481. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50482. this._chromaticAberrationPostProcess.onApply = function (effect) {
  50483. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  50484. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50485. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50486. };
  50487. };
  50488. // highlights enhancing
  50489. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  50490. var _this = this;
  50491. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  50492. [], // samplers
  50493. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  50494. this._highlightsPostProcess.onApply = function (effect) {
  50495. effect.setFloat('gain', _this._highlightsGain);
  50496. effect.setFloat('threshold', _this._highlightsThreshold);
  50497. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  50498. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50499. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50500. };
  50501. };
  50502. // colors shifting and distortion
  50503. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  50504. var _this = this;
  50505. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  50506. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  50507. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  50508. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50509. this._depthOfFieldPostProcess.onApply = function (effect) {
  50510. effect.setTexture("depthSampler", _this._depthTexture);
  50511. effect.setTexture("grainSampler", _this._grainTexture);
  50512. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  50513. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  50514. effect.setFloat('grain_amount', _this._grainAmount);
  50515. effect.setBool('blur_noise', _this._blurNoise);
  50516. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50517. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50518. effect.setFloat('distortion', _this._distortion);
  50519. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  50520. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  50521. effect.setFloat('aperture', _this._dofAperture);
  50522. effect.setFloat('darken', _this._dofDarken);
  50523. effect.setFloat('edge_blur', _this._edgeBlur);
  50524. effect.setBool('highlights', (_this._highlightsGain !== -1));
  50525. effect.setFloat('near', _this._scene.activeCamera.minZ);
  50526. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  50527. };
  50528. };
  50529. // creates a black and white random noise texture, 512x512
  50530. LensRenderingPipeline.prototype._createGrainTexture = function () {
  50531. var size = 512;
  50532. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50533. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50534. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50535. var context = this._grainTexture.getContext();
  50536. var rand = function (min, max) {
  50537. return Math.random() * (max - min) + min;
  50538. };
  50539. var value;
  50540. for (var x = 0; x < size; x++) {
  50541. for (var y = 0; y < size; y++) {
  50542. value = Math.floor(rand(0.42, 0.58) * 255);
  50543. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  50544. context.fillRect(x, y, 1, 1);
  50545. }
  50546. }
  50547. this._grainTexture.update(false);
  50548. };
  50549. return LensRenderingPipeline;
  50550. }(BABYLON.PostProcessRenderPipeline));
  50551. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  50552. })(BABYLON || (BABYLON = {}));
  50553. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  50554. var BABYLON;
  50555. (function (BABYLON) {
  50556. var StandardRenderingPipeline = (function (_super) {
  50557. __extends(StandardRenderingPipeline, _super);
  50558. /**
  50559. * @constructor
  50560. * @param {string} name - The rendering pipeline name
  50561. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50562. * @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)
  50563. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  50564. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50565. */
  50566. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  50567. if (originalPostProcess === void 0) { originalPostProcess = null; }
  50568. var _this = _super.call(this, scene.getEngine(), name) || this;
  50569. _this.downSampleX4PostProcess = null;
  50570. _this.brightPassPostProcess = null;
  50571. _this.blurHPostProcesses = [];
  50572. _this.blurVPostProcesses = [];
  50573. _this.textureAdderPostProcess = null;
  50574. _this.volumetricLightPostProcess = null;
  50575. _this.volumetricLightSmoothXPostProcess = null;
  50576. _this.volumetricLightSmoothYPostProcess = null;
  50577. _this.volumetricLightMergePostProces = null;
  50578. _this.volumetricLightFinalPostProcess = null;
  50579. _this.luminancePostProcess = null;
  50580. _this.luminanceDownSamplePostProcesses = [];
  50581. _this.hdrPostProcess = null;
  50582. _this.textureAdderFinalPostProcess = null;
  50583. _this.lensFlareFinalPostProcess = null;
  50584. _this.hdrFinalPostProcess = null;
  50585. _this.lensFlarePostProcess = null;
  50586. _this.lensFlareComposePostProcess = null;
  50587. _this.motionBlurPostProcess = null;
  50588. _this.depthOfFieldPostProcess = null;
  50589. // Values
  50590. _this.brightThreshold = 1.0;
  50591. _this.blurWidth = 512.0;
  50592. _this.horizontalBlur = false;
  50593. _this.exposure = 1.0;
  50594. _this.lensTexture = null;
  50595. _this.volumetricLightCoefficient = 0.2;
  50596. _this.volumetricLightPower = 4.0;
  50597. _this.volumetricLightBlurScale = 64.0;
  50598. _this.sourceLight = null;
  50599. _this.hdrMinimumLuminance = 1.0;
  50600. _this.hdrDecreaseRate = 0.5;
  50601. _this.hdrIncreaseRate = 0.5;
  50602. _this.lensColorTexture = null;
  50603. _this.lensFlareStrength = 20.0;
  50604. _this.lensFlareGhostDispersal = 1.4;
  50605. _this.lensFlareHaloWidth = 0.7;
  50606. _this.lensFlareDistortionStrength = 16.0;
  50607. _this.lensStarTexture = null;
  50608. _this.lensFlareDirtTexture = null;
  50609. _this.depthOfFieldDistance = 10.0;
  50610. _this.depthOfFieldBlurWidth = 64.0;
  50611. _this.motionStrength = 1.0;
  50612. // IAnimatable
  50613. _this.animations = [];
  50614. _this._currentDepthOfFieldSource = null;
  50615. _this._hdrCurrentLuminance = 1.0;
  50616. // Getters and setters
  50617. _this._bloomEnabled = true;
  50618. _this._depthOfFieldEnabled = false;
  50619. _this._vlsEnabled = false;
  50620. _this._lensFlareEnabled = false;
  50621. _this._hdrEnabled = false;
  50622. _this._motionBlurEnabled = false;
  50623. _this._motionBlurSamples = 64.0;
  50624. _this._volumetricLightStepsCount = 50.0;
  50625. _this._cameras = cameras || [];
  50626. // Initialize
  50627. _this._scene = scene;
  50628. _this._basePostProcess = originalPostProcess;
  50629. _this._ratio = ratio;
  50630. // Misc
  50631. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50632. // Finish
  50633. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50634. _this._buildPipeline();
  50635. return _this;
  50636. }
  50637. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  50638. get: function () {
  50639. return this._bloomEnabled;
  50640. },
  50641. set: function (enabled) {
  50642. if (this._bloomEnabled === enabled) {
  50643. return;
  50644. }
  50645. this._bloomEnabled = enabled;
  50646. this._buildPipeline();
  50647. },
  50648. enumerable: true,
  50649. configurable: true
  50650. });
  50651. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  50652. get: function () {
  50653. return this._depthOfFieldEnabled;
  50654. },
  50655. set: function (enabled) {
  50656. if (this._depthOfFieldEnabled === enabled) {
  50657. return;
  50658. }
  50659. this._depthOfFieldEnabled = enabled;
  50660. this._buildPipeline();
  50661. },
  50662. enumerable: true,
  50663. configurable: true
  50664. });
  50665. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  50666. get: function () {
  50667. return this._lensFlareEnabled;
  50668. },
  50669. set: function (enabled) {
  50670. if (this._lensFlareEnabled === enabled) {
  50671. return;
  50672. }
  50673. this._lensFlareEnabled = enabled;
  50674. this._buildPipeline();
  50675. },
  50676. enumerable: true,
  50677. configurable: true
  50678. });
  50679. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  50680. get: function () {
  50681. return this._hdrEnabled;
  50682. },
  50683. set: function (enabled) {
  50684. if (this._hdrEnabled === enabled) {
  50685. return;
  50686. }
  50687. this._hdrEnabled = enabled;
  50688. this._buildPipeline();
  50689. },
  50690. enumerable: true,
  50691. configurable: true
  50692. });
  50693. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  50694. get: function () {
  50695. return this._vlsEnabled;
  50696. },
  50697. set: function (enabled) {
  50698. if (this._vlsEnabled === enabled) {
  50699. return;
  50700. }
  50701. if (enabled) {
  50702. var geometry = this._scene.enableGeometryBufferRenderer();
  50703. if (!geometry) {
  50704. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  50705. return;
  50706. }
  50707. }
  50708. this._vlsEnabled = enabled;
  50709. this._buildPipeline();
  50710. },
  50711. enumerable: true,
  50712. configurable: true
  50713. });
  50714. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  50715. get: function () {
  50716. return this._motionBlurEnabled;
  50717. },
  50718. set: function (enabled) {
  50719. if (this._motionBlurEnabled === enabled) {
  50720. return;
  50721. }
  50722. this._motionBlurEnabled = enabled;
  50723. this._buildPipeline();
  50724. },
  50725. enumerable: true,
  50726. configurable: true
  50727. });
  50728. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  50729. get: function () {
  50730. return this._volumetricLightStepsCount;
  50731. },
  50732. set: function (count) {
  50733. if (this.volumetricLightPostProcess) {
  50734. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  50735. }
  50736. this._volumetricLightStepsCount = count;
  50737. },
  50738. enumerable: true,
  50739. configurable: true
  50740. });
  50741. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  50742. get: function () {
  50743. return this._motionBlurSamples;
  50744. },
  50745. set: function (samples) {
  50746. if (this.motionBlurPostProcess) {
  50747. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  50748. }
  50749. this._motionBlurSamples = samples;
  50750. },
  50751. enumerable: true,
  50752. configurable: true
  50753. });
  50754. StandardRenderingPipeline.prototype._buildPipeline = function () {
  50755. var _this = this;
  50756. var ratio = this._ratio;
  50757. var scene = this._scene;
  50758. this._disposePostProcesses();
  50759. this._reset();
  50760. // Create pass post-process
  50761. if (!this._basePostProcess) {
  50762. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  50763. this.originalPostProcess.onApply = function (effect) {
  50764. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  50765. };
  50766. }
  50767. else {
  50768. this.originalPostProcess = this._basePostProcess;
  50769. }
  50770. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  50771. this._currentDepthOfFieldSource = this.originalPostProcess;
  50772. if (this._vlsEnabled) {
  50773. // Create volumetric light
  50774. this._createVolumetricLightPostProcess(scene, ratio);
  50775. // Create volumetric light final post-process
  50776. 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);
  50777. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  50778. }
  50779. if (this._bloomEnabled) {
  50780. // Create down sample X4 post-process
  50781. this._createDownSampleX4PostProcess(scene, ratio / 2);
  50782. // Create bright pass post-process
  50783. this._createBrightPassPostProcess(scene, ratio / 2);
  50784. // Create gaussian blur post-processes (down sampling blurs)
  50785. this._createBlurPostProcesses(scene, ratio / 4, 1);
  50786. // Create texture adder post-process
  50787. this._createTextureAdderPostProcess(scene, ratio);
  50788. // Create depth-of-field source post-process
  50789. 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);
  50790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  50791. }
  50792. if (this._lensFlareEnabled) {
  50793. // Create lens flare post-process
  50794. this._createLensFlarePostProcess(scene, ratio);
  50795. // Create depth-of-field source post-process post lens-flare and disable it now
  50796. 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);
  50797. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  50798. }
  50799. if (this._hdrEnabled) {
  50800. // Create luminance
  50801. this._createLuminancePostProcesses(scene, this._floatTextureType);
  50802. // Create HDR
  50803. this._createHdrPostProcess(scene, ratio);
  50804. // Create depth-of-field source post-process post hdr and disable it now
  50805. 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);
  50806. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  50807. }
  50808. if (this._depthOfFieldEnabled) {
  50809. // Create gaussian blur used by depth-of-field
  50810. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  50811. // Create depth-of-field post-process
  50812. this._createDepthOfFieldPostProcess(scene, ratio);
  50813. }
  50814. if (this._motionBlurEnabled) {
  50815. // Create motion blur post-process
  50816. this._createMotionBlurPostProcess(scene, ratio);
  50817. }
  50818. if (this._cameras !== null) {
  50819. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  50820. }
  50821. };
  50822. // Down Sample X4 Post-Processs
  50823. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  50824. var _this = this;
  50825. var downSampleX4Offsets = new Array(32);
  50826. 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);
  50827. this.downSampleX4PostProcess.onApply = function (effect) {
  50828. var id = 0;
  50829. for (var i = -2; i < 2; i++) {
  50830. for (var j = -2; j < 2; j++) {
  50831. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  50832. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  50833. id += 2;
  50834. }
  50835. }
  50836. effect.setArray2("dsOffsets", downSampleX4Offsets);
  50837. };
  50838. // Add to pipeline
  50839. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  50840. };
  50841. // Brightpass Post-Process
  50842. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  50843. var _this = this;
  50844. var brightOffsets = new Array(8);
  50845. 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);
  50846. this.brightPassPostProcess.onApply = function (effect) {
  50847. var sU = (1.0 / _this.brightPassPostProcess.width);
  50848. var sV = (1.0 / _this.brightPassPostProcess.height);
  50849. brightOffsets[0] = -0.5 * sU;
  50850. brightOffsets[1] = 0.5 * sV;
  50851. brightOffsets[2] = 0.5 * sU;
  50852. brightOffsets[3] = 0.5 * sV;
  50853. brightOffsets[4] = -0.5 * sU;
  50854. brightOffsets[5] = -0.5 * sV;
  50855. brightOffsets[6] = 0.5 * sU;
  50856. brightOffsets[7] = -0.5 * sV;
  50857. effect.setArray2("dsOffsets", brightOffsets);
  50858. effect.setFloat("brightThreshold", _this.brightThreshold);
  50859. };
  50860. // Add to pipeline
  50861. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  50862. };
  50863. // Create blur H&V post-processes
  50864. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  50865. var _this = this;
  50866. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  50867. var engine = scene.getEngine();
  50868. 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);
  50869. 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);
  50870. blurX.onActivateObservable.add(function () {
  50871. var dw = blurX.width / engine.getRenderingCanvas().width;
  50872. blurX.kernel = _this[blurWidthKey] * dw;
  50873. });
  50874. blurY.onActivateObservable.add(function () {
  50875. var dw = blurY.height / engine.getRenderingCanvas().height;
  50876. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  50877. });
  50878. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  50879. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  50880. this.blurHPostProcesses.push(blurX);
  50881. this.blurVPostProcesses.push(blurY);
  50882. };
  50883. // Create texture adder post-process
  50884. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  50885. var _this = this;
  50886. 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);
  50887. this.textureAdderPostProcess.onApply = function (effect) {
  50888. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  50889. effect.setTexture("lensSampler", _this.lensTexture);
  50890. effect.setFloat("exposure", _this.exposure);
  50891. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  50892. };
  50893. // Add to pipeline
  50894. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  50895. };
  50896. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  50897. var _this = this;
  50898. var geometryRenderer = scene.enableGeometryBufferRenderer();
  50899. geometryRenderer.enablePosition = true;
  50900. var geometry = geometryRenderer.getGBuffer();
  50901. // Base post-process
  50902. 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));
  50903. var depthValues = BABYLON.Vector2.Zero();
  50904. this.volumetricLightPostProcess.onApply = function (effect) {
  50905. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  50906. var generator = _this.sourceLight.getShadowGenerator();
  50907. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  50908. effect.setTexture("positionSampler", geometry.textures[2]);
  50909. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  50910. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  50911. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  50912. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  50913. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  50914. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  50915. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  50916. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  50917. effect.setVector2("depthValues", depthValues);
  50918. }
  50919. };
  50920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  50921. // Smooth
  50922. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  50923. // Merge
  50924. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  50925. this.volumetricLightMergePostProces.onApply = function (effect) {
  50926. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  50927. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  50928. };
  50929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  50930. };
  50931. // Create luminance
  50932. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  50933. var _this = this;
  50934. // Create luminance
  50935. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  50936. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  50937. var offsets = [];
  50938. this.luminancePostProcess.onApply = function (effect) {
  50939. var sU = (1.0 / _this.luminancePostProcess.width);
  50940. var sV = (1.0 / _this.luminancePostProcess.height);
  50941. offsets[0] = -0.5 * sU;
  50942. offsets[1] = 0.5 * sV;
  50943. offsets[2] = 0.5 * sU;
  50944. offsets[3] = 0.5 * sV;
  50945. offsets[4] = -0.5 * sU;
  50946. offsets[5] = -0.5 * sV;
  50947. offsets[6] = 0.5 * sU;
  50948. offsets[7] = -0.5 * sV;
  50949. effect.setArray2("lumOffsets", offsets);
  50950. };
  50951. // Add to pipeline
  50952. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  50953. // Create down sample luminance
  50954. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  50955. var size = Math.pow(3, i);
  50956. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  50957. if (i === 0) {
  50958. defines += "#define FINAL_DOWN_SAMPLER";
  50959. }
  50960. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  50961. this.luminanceDownSamplePostProcesses.push(postProcess);
  50962. }
  50963. // Create callbacks and add effects
  50964. var lastLuminance = this.luminancePostProcess;
  50965. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  50966. var downSampleOffsets = new Array(18);
  50967. pp.onApply = function (effect) {
  50968. var id = 0;
  50969. for (var x = -1; x < 2; x++) {
  50970. for (var y = -1; y < 2; y++) {
  50971. downSampleOffsets[id] = x / lastLuminance.width;
  50972. downSampleOffsets[id + 1] = y / lastLuminance.height;
  50973. id += 2;
  50974. }
  50975. }
  50976. effect.setArray2("dsOffsets", downSampleOffsets);
  50977. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  50978. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  50979. lastLuminance = _this.luminancePostProcess;
  50980. }
  50981. else {
  50982. lastLuminance = pp;
  50983. }
  50984. };
  50985. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  50986. pp.onAfterRender = function (effect) {
  50987. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  50988. 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);
  50989. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  50990. };
  50991. }
  50992. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  50993. });
  50994. };
  50995. // Create HDR post-process
  50996. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  50997. var _this = this;
  50998. 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);
  50999. var outputLiminance = 1;
  51000. var time = 0;
  51001. var lastTime = 0;
  51002. this.hdrPostProcess.onApply = function (effect) {
  51003. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  51004. time += scene.getEngine().getDeltaTime();
  51005. if (outputLiminance < 0) {
  51006. outputLiminance = _this._hdrCurrentLuminance;
  51007. }
  51008. else {
  51009. var dt = (lastTime - time) / 1000.0;
  51010. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  51011. outputLiminance += _this.hdrDecreaseRate * dt;
  51012. }
  51013. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  51014. outputLiminance -= _this.hdrIncreaseRate * dt;
  51015. }
  51016. else {
  51017. outputLiminance = _this._hdrCurrentLuminance;
  51018. }
  51019. }
  51020. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  51021. effect.setFloat("averageLuminance", outputLiminance);
  51022. lastTime = time;
  51023. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  51024. };
  51025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  51026. };
  51027. // Create lens flare post-process
  51028. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  51029. var _this = this;
  51030. 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);
  51031. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  51032. this._createBlurPostProcesses(scene, ratio / 4, 2);
  51033. 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);
  51034. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  51035. var resolution = new BABYLON.Vector2(0, 0);
  51036. // Lens flare
  51037. this.lensFlarePostProcess.onApply = function (effect) {
  51038. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  51039. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  51040. effect.setFloat("strength", _this.lensFlareStrength);
  51041. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  51042. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  51043. // Shift
  51044. resolution.x = _this.lensFlarePostProcess.width;
  51045. resolution.y = _this.lensFlarePostProcess.height;
  51046. effect.setVector2("resolution", resolution);
  51047. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  51048. };
  51049. // Compose
  51050. 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);
  51051. 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);
  51052. this.lensFlareComposePostProcess.onApply = function (effect) {
  51053. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  51054. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  51055. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  51056. // Lens start rotation matrix
  51057. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  51058. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  51059. 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));
  51060. camRot *= 4.0;
  51061. 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);
  51062. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  51063. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  51064. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  51065. };
  51066. };
  51067. // Create depth-of-field post-process
  51068. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  51069. var _this = this;
  51070. 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);
  51071. this.depthOfFieldPostProcess.onApply = function (effect) {
  51072. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  51073. effect.setTexture("depthSampler", _this._getDepthTexture());
  51074. effect.setFloat("distance", _this.depthOfFieldDistance);
  51075. };
  51076. // Add to pipeline
  51077. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  51078. };
  51079. // Create motion blur post-process
  51080. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  51081. var _this = this;
  51082. 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);
  51083. var motionScale = 0;
  51084. var prevViewProjection = BABYLON.Matrix.Identity();
  51085. var invViewProjection = BABYLON.Matrix.Identity();
  51086. var viewProjection = BABYLON.Matrix.Identity();
  51087. var screenSize = BABYLON.Vector2.Zero();
  51088. this.motionBlurPostProcess.onApply = function (effect) {
  51089. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  51090. viewProjection.invertToRef(invViewProjection);
  51091. effect.setMatrix("inverseViewProjection", invViewProjection);
  51092. effect.setMatrix("prevViewProjection", prevViewProjection);
  51093. prevViewProjection = viewProjection;
  51094. screenSize.x = _this.motionBlurPostProcess.width;
  51095. screenSize.y = _this.motionBlurPostProcess.height;
  51096. effect.setVector2("screenSize", screenSize);
  51097. motionScale = scene.getEngine().getFps() / 60.0;
  51098. effect.setFloat("motionScale", motionScale);
  51099. effect.setFloat("motionStrength", _this.motionStrength);
  51100. effect.setTexture("depthSampler", _this._getDepthTexture());
  51101. };
  51102. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  51103. };
  51104. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  51105. var geometry = this._scene.enableGeometryBufferRenderer();
  51106. if (geometry) {
  51107. return geometry.getGBuffer().textures[0];
  51108. }
  51109. return this._scene.enableDepthRenderer().getDepthMap();
  51110. };
  51111. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  51112. for (var i = 0; i < this._cameras.length; i++) {
  51113. var camera = this._cameras[i];
  51114. if (this.originalPostProcess) {
  51115. this.originalPostProcess.dispose(camera);
  51116. }
  51117. if (this.downSampleX4PostProcess) {
  51118. this.downSampleX4PostProcess.dispose(camera);
  51119. }
  51120. if (this.brightPassPostProcess) {
  51121. this.brightPassPostProcess.dispose(camera);
  51122. }
  51123. if (this.textureAdderPostProcess) {
  51124. this.textureAdderPostProcess.dispose(camera);
  51125. }
  51126. if (this.textureAdderFinalPostProcess) {
  51127. this.textureAdderFinalPostProcess.dispose(camera);
  51128. }
  51129. if (this.volumetricLightPostProcess) {
  51130. this.volumetricLightPostProcess.dispose(camera);
  51131. }
  51132. if (this.volumetricLightSmoothXPostProcess) {
  51133. this.volumetricLightSmoothXPostProcess.dispose(camera);
  51134. }
  51135. if (this.volumetricLightSmoothYPostProcess) {
  51136. this.volumetricLightSmoothYPostProcess.dispose(camera);
  51137. }
  51138. if (this.volumetricLightMergePostProces) {
  51139. this.volumetricLightMergePostProces.dispose(camera);
  51140. }
  51141. if (this.volumetricLightFinalPostProcess) {
  51142. this.volumetricLightFinalPostProcess.dispose(camera);
  51143. }
  51144. if (this.lensFlarePostProcess) {
  51145. this.lensFlarePostProcess.dispose(camera);
  51146. }
  51147. if (this.lensFlareComposePostProcess) {
  51148. this.lensFlareComposePostProcess.dispose(camera);
  51149. }
  51150. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  51151. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  51152. }
  51153. if (this.luminancePostProcess) {
  51154. this.luminancePostProcess.dispose(camera);
  51155. }
  51156. if (this.hdrPostProcess) {
  51157. this.hdrPostProcess.dispose(camera);
  51158. }
  51159. if (this.hdrFinalPostProcess) {
  51160. this.hdrFinalPostProcess.dispose(camera);
  51161. }
  51162. if (this.depthOfFieldPostProcess) {
  51163. this.depthOfFieldPostProcess.dispose(camera);
  51164. }
  51165. if (this.motionBlurPostProcess) {
  51166. this.motionBlurPostProcess.dispose(camera);
  51167. }
  51168. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  51169. this.blurHPostProcesses[j].dispose(camera);
  51170. }
  51171. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  51172. this.blurVPostProcesses[j].dispose(camera);
  51173. }
  51174. }
  51175. this.originalPostProcess = null;
  51176. this.downSampleX4PostProcess = null;
  51177. this.brightPassPostProcess = null;
  51178. this.textureAdderPostProcess = null;
  51179. this.textureAdderFinalPostProcess = null;
  51180. this.volumetricLightPostProcess = null;
  51181. this.volumetricLightSmoothXPostProcess = null;
  51182. this.volumetricLightSmoothYPostProcess = null;
  51183. this.volumetricLightMergePostProces = null;
  51184. this.volumetricLightFinalPostProcess = null;
  51185. this.lensFlarePostProcess = null;
  51186. this.lensFlareComposePostProcess = null;
  51187. this.luminancePostProcess = null;
  51188. this.hdrPostProcess = null;
  51189. this.hdrFinalPostProcess = null;
  51190. this.depthOfFieldPostProcess = null;
  51191. this.motionBlurPostProcess = null;
  51192. this.luminanceDownSamplePostProcesses = [];
  51193. this.blurHPostProcesses = [];
  51194. this.blurVPostProcesses = [];
  51195. };
  51196. // Dispose
  51197. StandardRenderingPipeline.prototype.dispose = function () {
  51198. this._disposePostProcesses();
  51199. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  51200. _super.prototype.dispose.call(this);
  51201. };
  51202. // Serialize rendering pipeline
  51203. StandardRenderingPipeline.prototype.serialize = function () {
  51204. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51205. serializationObject.customType = "StandardRenderingPipeline";
  51206. return serializationObject;
  51207. };
  51208. /**
  51209. * Static members
  51210. */
  51211. // Parse serialized pipeline
  51212. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  51213. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  51214. };
  51215. return StandardRenderingPipeline;
  51216. }(BABYLON.PostProcessRenderPipeline));
  51217. // Luminance steps
  51218. StandardRenderingPipeline.LuminanceSteps = 6;
  51219. __decorate([
  51220. BABYLON.serialize()
  51221. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  51222. __decorate([
  51223. BABYLON.serialize()
  51224. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  51225. __decorate([
  51226. BABYLON.serialize()
  51227. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  51228. __decorate([
  51229. BABYLON.serialize()
  51230. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  51231. __decorate([
  51232. BABYLON.serializeAsTexture("lensTexture")
  51233. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  51234. __decorate([
  51235. BABYLON.serialize()
  51236. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  51237. __decorate([
  51238. BABYLON.serialize()
  51239. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  51240. __decorate([
  51241. BABYLON.serialize()
  51242. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  51243. __decorate([
  51244. BABYLON.serialize()
  51245. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  51246. __decorate([
  51247. BABYLON.serialize()
  51248. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  51249. __decorate([
  51250. BABYLON.serialize()
  51251. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  51252. __decorate([
  51253. BABYLON.serializeAsTexture("lensColorTexture")
  51254. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  51255. __decorate([
  51256. BABYLON.serialize()
  51257. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  51258. __decorate([
  51259. BABYLON.serialize()
  51260. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  51261. __decorate([
  51262. BABYLON.serialize()
  51263. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  51264. __decorate([
  51265. BABYLON.serialize()
  51266. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  51267. __decorate([
  51268. BABYLON.serializeAsTexture("lensStarTexture")
  51269. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  51270. __decorate([
  51271. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  51272. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  51273. __decorate([
  51274. BABYLON.serialize()
  51275. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  51276. __decorate([
  51277. BABYLON.serialize()
  51278. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  51279. __decorate([
  51280. BABYLON.serialize()
  51281. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  51282. __decorate([
  51283. BABYLON.serialize()
  51284. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  51285. __decorate([
  51286. BABYLON.serialize()
  51287. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  51288. __decorate([
  51289. BABYLON.serialize()
  51290. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  51291. __decorate([
  51292. BABYLON.serialize()
  51293. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  51294. __decorate([
  51295. BABYLON.serialize()
  51296. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  51297. __decorate([
  51298. BABYLON.serialize()
  51299. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  51300. __decorate([
  51301. BABYLON.serialize()
  51302. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  51303. __decorate([
  51304. BABYLON.serialize()
  51305. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  51306. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  51307. })(BABYLON || (BABYLON = {}));
  51308. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  51309. var BABYLON;
  51310. (function (BABYLON) {
  51311. var FxaaPostProcess = (function (_super) {
  51312. __extends(FxaaPostProcess, _super);
  51313. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51314. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51315. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  51316. _this.onApplyObservable.add(function (effect) {
  51317. var texelSize = _this.texelSize;
  51318. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  51319. });
  51320. return _this;
  51321. }
  51322. return FxaaPostProcess;
  51323. }(BABYLON.PostProcess));
  51324. BABYLON.FxaaPostProcess = FxaaPostProcess;
  51325. })(BABYLON || (BABYLON = {}));
  51326. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  51327. var BABYLON;
  51328. (function (BABYLON) {
  51329. var DefaultRenderingPipeline = (function (_super) {
  51330. __extends(DefaultRenderingPipeline, _super);
  51331. /**
  51332. * @constructor
  51333. * @param {string} name - The rendering pipeline name
  51334. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51335. * @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)
  51336. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51337. */
  51338. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  51339. var _this = _super.call(this, scene.getEngine(), name) || this;
  51340. _this.PassPostProcessId = "PassPostProcessEffect";
  51341. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  51342. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  51343. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  51344. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  51345. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  51346. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  51347. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  51348. // IAnimatable
  51349. _this.animations = [];
  51350. // Values
  51351. _this._bloomEnabled = false;
  51352. _this._fxaaEnabled = false;
  51353. _this._imageProcessingEnabled = true;
  51354. _this._bloomScale = 0.6;
  51355. /**
  51356. * Specifies the size of the bloom blur kernel, relative to the final output size
  51357. */
  51358. _this.bloomKernel = 64;
  51359. /**
  51360. * Specifies the weight of the bloom in the final rendering
  51361. */
  51362. _this._bloomWeight = 0.15;
  51363. _this._cameras = cameras || [];
  51364. // Initialize
  51365. _this._scene = scene;
  51366. var caps = _this._scene.getEngine().getCaps();
  51367. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  51368. // Misc
  51369. if (_this._hdr) {
  51370. if (caps.textureHalfFloatRender) {
  51371. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51372. }
  51373. else if (caps.textureFloatRender) {
  51374. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51375. }
  51376. }
  51377. else {
  51378. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51379. }
  51380. // Attach
  51381. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51382. _this._buildPipeline();
  51383. return _this;
  51384. }
  51385. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  51386. get: function () {
  51387. return this._bloomWeight;
  51388. },
  51389. set: function (value) {
  51390. if (this._bloomWeight === value) {
  51391. return;
  51392. }
  51393. this._bloomWeight = value;
  51394. if (this._hdr && this.copyBack) {
  51395. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  51396. }
  51397. },
  51398. enumerable: true,
  51399. configurable: true
  51400. });
  51401. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  51402. get: function () {
  51403. return this._bloomScale;
  51404. },
  51405. set: function (value) {
  51406. if (this._bloomScale === value) {
  51407. return;
  51408. }
  51409. this._bloomScale = value;
  51410. this._buildPipeline();
  51411. },
  51412. enumerable: true,
  51413. configurable: true
  51414. });
  51415. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  51416. get: function () {
  51417. return this._bloomEnabled;
  51418. },
  51419. set: function (enabled) {
  51420. if (this._bloomEnabled === enabled) {
  51421. return;
  51422. }
  51423. this._bloomEnabled = enabled;
  51424. this._buildPipeline();
  51425. },
  51426. enumerable: true,
  51427. configurable: true
  51428. });
  51429. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  51430. get: function () {
  51431. return this._fxaaEnabled;
  51432. },
  51433. set: function (enabled) {
  51434. if (this._fxaaEnabled === enabled) {
  51435. return;
  51436. }
  51437. this._fxaaEnabled = enabled;
  51438. this._buildPipeline();
  51439. },
  51440. enumerable: true,
  51441. configurable: true
  51442. });
  51443. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  51444. get: function () {
  51445. return this._imageProcessingEnabled;
  51446. },
  51447. set: function (enabled) {
  51448. if (this._imageProcessingEnabled === enabled) {
  51449. return;
  51450. }
  51451. this._imageProcessingEnabled = enabled;
  51452. this._buildPipeline();
  51453. },
  51454. enumerable: true,
  51455. configurable: true
  51456. });
  51457. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  51458. var _this = this;
  51459. var engine = this._scene.getEngine();
  51460. this._disposePostProcesses();
  51461. this._reset();
  51462. if (this.bloomEnabled) {
  51463. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51464. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  51465. if (!this._hdr) {
  51466. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51467. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  51468. this.highlights.autoClear = false;
  51469. this.highlights.alwaysForcePOT = true;
  51470. }
  51471. 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);
  51472. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  51473. this.blurX.alwaysForcePOT = true;
  51474. this.blurX.autoClear = false;
  51475. this.blurX.onActivateObservable.add(function () {
  51476. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  51477. _this.blurX.kernel = _this.bloomKernel * dw;
  51478. });
  51479. 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);
  51480. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  51481. this.blurY.alwaysForcePOT = true;
  51482. this.blurY.autoClear = false;
  51483. this.blurY.onActivateObservable.add(function () {
  51484. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  51485. _this.blurY.kernel = _this.bloomKernel * dh;
  51486. });
  51487. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51488. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  51489. this.copyBack.alwaysForcePOT = true;
  51490. if (this._hdr) {
  51491. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  51492. var w = this.bloomWeight;
  51493. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  51494. }
  51495. else {
  51496. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  51497. }
  51498. this.copyBack.autoClear = false;
  51499. }
  51500. if (this._imageProcessingEnabled) {
  51501. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51502. if (this._hdr) {
  51503. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  51504. }
  51505. }
  51506. if (this.fxaaEnabled) {
  51507. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51508. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  51509. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  51510. }
  51511. else {
  51512. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51513. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  51514. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  51515. }
  51516. if (this.bloomEnabled) {
  51517. if (this._hdr) {
  51518. this.copyBack.shareOutputWith(this.blurX);
  51519. if (this.imageProcessing) {
  51520. this.imageProcessing.shareOutputWith(this.pass);
  51521. this.imageProcessing.autoClear = false;
  51522. }
  51523. else if (this.fxaa) {
  51524. this.fxaa.shareOutputWith(this.pass);
  51525. }
  51526. else {
  51527. this.finalMerge.shareOutputWith(this.pass);
  51528. }
  51529. }
  51530. else {
  51531. if (this.fxaa) {
  51532. this.fxaa.shareOutputWith(this.pass);
  51533. }
  51534. else {
  51535. this.finalMerge.shareOutputWith(this.pass);
  51536. }
  51537. }
  51538. }
  51539. if (this._cameras !== null) {
  51540. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  51541. }
  51542. };
  51543. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  51544. for (var i = 0; i < this._cameras.length; i++) {
  51545. var camera = this._cameras[i];
  51546. if (this.pass) {
  51547. this.pass.dispose(camera);
  51548. }
  51549. if (this.highlights) {
  51550. this.highlights.dispose(camera);
  51551. }
  51552. if (this.blurX) {
  51553. this.blurX.dispose(camera);
  51554. }
  51555. if (this.blurY) {
  51556. this.blurY.dispose(camera);
  51557. }
  51558. if (this.copyBack) {
  51559. this.copyBack.dispose(camera);
  51560. }
  51561. if (this.imageProcessing) {
  51562. this.imageProcessing.dispose(camera);
  51563. }
  51564. if (this.fxaa) {
  51565. this.fxaa.dispose(camera);
  51566. }
  51567. if (this.finalMerge) {
  51568. this.finalMerge.dispose(camera);
  51569. }
  51570. }
  51571. this.pass = null;
  51572. this.highlights = null;
  51573. this.blurX = null;
  51574. this.blurY = null;
  51575. this.copyBack = null;
  51576. this.imageProcessing = null;
  51577. this.fxaa = null;
  51578. this.finalMerge = null;
  51579. };
  51580. // Dispose
  51581. DefaultRenderingPipeline.prototype.dispose = function () {
  51582. this._disposePostProcesses();
  51583. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  51584. _super.prototype.dispose.call(this);
  51585. };
  51586. // Serialize rendering pipeline
  51587. DefaultRenderingPipeline.prototype.serialize = function () {
  51588. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51589. serializationObject.customType = "DefaultRenderingPipeline";
  51590. return serializationObject;
  51591. };
  51592. // Parse serialized pipeline
  51593. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  51594. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  51595. };
  51596. return DefaultRenderingPipeline;
  51597. }(BABYLON.PostProcessRenderPipeline));
  51598. __decorate([
  51599. BABYLON.serialize()
  51600. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  51601. __decorate([
  51602. BABYLON.serialize()
  51603. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  51604. __decorate([
  51605. BABYLON.serialize()
  51606. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  51607. __decorate([
  51608. BABYLON.serialize()
  51609. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  51610. __decorate([
  51611. BABYLON.serialize()
  51612. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  51613. __decorate([
  51614. BABYLON.serialize()
  51615. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  51616. __decorate([
  51617. BABYLON.serialize()
  51618. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  51619. __decorate([
  51620. BABYLON.serialize()
  51621. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  51622. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  51623. })(BABYLON || (BABYLON = {}));
  51624. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  51625. var BABYLON;
  51626. (function (BABYLON) {
  51627. var GeometryBufferRenderer = (function () {
  51628. function GeometryBufferRenderer(scene, ratio) {
  51629. if (ratio === void 0) { ratio = 1; }
  51630. this._viewMatrix = BABYLON.Matrix.Zero();
  51631. this._projectionMatrix = BABYLON.Matrix.Zero();
  51632. this._transformMatrix = BABYLON.Matrix.Zero();
  51633. this._worldViewProjection = BABYLON.Matrix.Zero();
  51634. this._enablePosition = false;
  51635. this._scene = scene;
  51636. this._ratio = ratio;
  51637. // Render target
  51638. this._createRenderTargets();
  51639. }
  51640. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  51641. set: function (meshes) {
  51642. this._multiRenderTarget.renderList = meshes;
  51643. },
  51644. enumerable: true,
  51645. configurable: true
  51646. });
  51647. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  51648. get: function () {
  51649. return this._multiRenderTarget.isSupported;
  51650. },
  51651. enumerable: true,
  51652. configurable: true
  51653. });
  51654. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  51655. get: function () {
  51656. return this._enablePosition;
  51657. },
  51658. set: function (enable) {
  51659. this._enablePosition = enable;
  51660. this.dispose();
  51661. this._createRenderTargets();
  51662. },
  51663. enumerable: true,
  51664. configurable: true
  51665. });
  51666. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  51667. var material = subMesh.getMaterial();
  51668. if (material && material.disableDepthWrite) {
  51669. return false;
  51670. }
  51671. var defines = [];
  51672. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  51673. var mesh = subMesh.getMesh();
  51674. var scene = mesh.getScene();
  51675. // Alpha test
  51676. if (material && material.needAlphaTesting()) {
  51677. defines.push("#define ALPHATEST");
  51678. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51679. attribs.push(BABYLON.VertexBuffer.UVKind);
  51680. defines.push("#define UV1");
  51681. }
  51682. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51683. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51684. defines.push("#define UV2");
  51685. }
  51686. }
  51687. // Buffers
  51688. if (this._enablePosition) {
  51689. defines.push("#define POSITION");
  51690. }
  51691. // Bones
  51692. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51693. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51694. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51695. if (mesh.numBoneInfluencers > 4) {
  51696. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51697. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51698. }
  51699. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51700. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51701. }
  51702. else {
  51703. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51704. }
  51705. // Instances
  51706. if (useInstances) {
  51707. defines.push("#define INSTANCES");
  51708. attribs.push("world0");
  51709. attribs.push("world1");
  51710. attribs.push("world2");
  51711. attribs.push("world3");
  51712. }
  51713. // Get correct effect
  51714. var join = defines.join("\n");
  51715. if (this._cachedDefines !== join) {
  51716. this._cachedDefines = join;
  51717. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  51718. }
  51719. return this._effect.isReady();
  51720. };
  51721. GeometryBufferRenderer.prototype.getGBuffer = function () {
  51722. return this._multiRenderTarget;
  51723. };
  51724. // Methods
  51725. GeometryBufferRenderer.prototype.dispose = function () {
  51726. this.getGBuffer().dispose();
  51727. };
  51728. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  51729. var _this = this;
  51730. var engine = this._scene.getEngine();
  51731. var count = this._enablePosition ? 3 : 2;
  51732. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  51733. if (!this.isSupported) {
  51734. return null;
  51735. }
  51736. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51737. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51738. this._multiRenderTarget.refreshRate = 1;
  51739. this._multiRenderTarget.renderParticles = false;
  51740. this._multiRenderTarget.renderList = null;
  51741. // set default depth value to 1.0 (far away)
  51742. this._multiRenderTarget.onClearObservable.add(function (engine) {
  51743. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  51744. });
  51745. // Custom render function
  51746. var renderSubMesh = function (subMesh) {
  51747. var mesh = subMesh.getRenderingMesh();
  51748. var scene = _this._scene;
  51749. var engine = scene.getEngine();
  51750. // Culling
  51751. engine.setState(subMesh.getMaterial().backFaceCulling);
  51752. // Managing instances
  51753. var batch = mesh._getInstancesRenderList(subMesh._id);
  51754. if (batch.mustReturn) {
  51755. return;
  51756. }
  51757. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  51758. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51759. engine.enableEffect(_this._effect);
  51760. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  51761. var material = subMesh.getMaterial();
  51762. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51763. _this._effect.setMatrix("view", scene.getViewMatrix());
  51764. // Alpha test
  51765. if (material && material.needAlphaTesting()) {
  51766. var alphaTexture = material.getAlphaTestTexture();
  51767. _this._effect.setTexture("diffuseSampler", alphaTexture);
  51768. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51769. }
  51770. // Bones
  51771. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51772. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51773. }
  51774. // Draw
  51775. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51776. }
  51777. };
  51778. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  51779. var index;
  51780. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51781. renderSubMesh(opaqueSubMeshes.data[index]);
  51782. }
  51783. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51784. renderSubMesh(alphaTestSubMeshes.data[index]);
  51785. }
  51786. };
  51787. };
  51788. return GeometryBufferRenderer;
  51789. }());
  51790. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  51791. })(BABYLON || (BABYLON = {}));
  51792. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  51793. var BABYLON;
  51794. (function (BABYLON) {
  51795. var RefractionPostProcess = (function (_super) {
  51796. __extends(RefractionPostProcess, _super);
  51797. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  51798. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  51799. _this.color = color;
  51800. _this.depth = depth;
  51801. _this.colorLevel = colorLevel;
  51802. _this.onActivateObservable.add(function (cam) {
  51803. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  51804. });
  51805. _this.onApplyObservable.add(function (effect) {
  51806. effect.setColor3("baseColor", _this.color);
  51807. effect.setFloat("depth", _this.depth);
  51808. effect.setFloat("colorLevel", _this.colorLevel);
  51809. effect.setTexture("refractionSampler", _this._refRexture);
  51810. });
  51811. return _this;
  51812. }
  51813. // Methods
  51814. RefractionPostProcess.prototype.dispose = function (camera) {
  51815. if (this._refRexture) {
  51816. this._refRexture.dispose();
  51817. }
  51818. _super.prototype.dispose.call(this, camera);
  51819. };
  51820. return RefractionPostProcess;
  51821. }(BABYLON.PostProcess));
  51822. BABYLON.RefractionPostProcess = RefractionPostProcess;
  51823. })(BABYLON || (BABYLON = {}));
  51824. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  51825. var BABYLON;
  51826. (function (BABYLON) {
  51827. var BlackAndWhitePostProcess = (function (_super) {
  51828. __extends(BlackAndWhitePostProcess, _super);
  51829. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  51830. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  51831. _this.degree = 1;
  51832. _this.onApplyObservable.add(function (effect) {
  51833. effect.setFloat("degree", _this.degree);
  51834. });
  51835. return _this;
  51836. }
  51837. return BlackAndWhitePostProcess;
  51838. }(BABYLON.PostProcess));
  51839. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  51840. })(BABYLON || (BABYLON = {}));
  51841. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  51842. var BABYLON;
  51843. (function (BABYLON) {
  51844. var ConvolutionPostProcess = (function (_super) {
  51845. __extends(ConvolutionPostProcess, _super);
  51846. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  51847. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  51848. _this.kernel = kernel;
  51849. _this.onApply = function (effect) {
  51850. effect.setFloat2("screenSize", _this.width, _this.height);
  51851. effect.setArray("kernel", _this.kernel);
  51852. };
  51853. return _this;
  51854. }
  51855. return ConvolutionPostProcess;
  51856. }(BABYLON.PostProcess));
  51857. // Statics
  51858. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  51859. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  51860. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  51861. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  51862. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  51863. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  51864. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  51865. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  51866. })(BABYLON || (BABYLON = {}));
  51867. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  51868. var BABYLON;
  51869. (function (BABYLON) {
  51870. var FilterPostProcess = (function (_super) {
  51871. __extends(FilterPostProcess, _super);
  51872. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  51873. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  51874. _this.kernelMatrix = kernelMatrix;
  51875. _this.onApply = function (effect) {
  51876. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  51877. };
  51878. return _this;
  51879. }
  51880. return FilterPostProcess;
  51881. }(BABYLON.PostProcess));
  51882. BABYLON.FilterPostProcess = FilterPostProcess;
  51883. })(BABYLON || (BABYLON = {}));
  51884. //# sourceMappingURL=babylon.filterPostProcess.js.map
  51885. var BABYLON;
  51886. (function (BABYLON) {
  51887. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  51888. var VolumetricLightScatteringPostProcess = (function (_super) {
  51889. __extends(VolumetricLightScatteringPostProcess, _super);
  51890. /**
  51891. * @constructor
  51892. * @param {string} name - The post-process name
  51893. * @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)
  51894. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  51895. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  51896. * @param {number} samples - The post-process quality, default 100
  51897. * @param {number} samplingMode - The post-process filtering mode
  51898. * @param {BABYLON.Engine} engine - The babylon engine
  51899. * @param {boolean} reusable - If the post-process is reusable
  51900. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  51901. */
  51902. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  51903. if (samples === void 0) { samples = 100; }
  51904. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51905. 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;
  51906. _this._screenCoordinates = BABYLON.Vector2.Zero();
  51907. /**
  51908. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  51909. * @type {Vector3}
  51910. */
  51911. _this.customMeshPosition = BABYLON.Vector3.Zero();
  51912. /**
  51913. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  51914. * @type {boolean}
  51915. */
  51916. _this.useCustomMeshPosition = false;
  51917. /**
  51918. * If the post-process should inverse the light scattering direction
  51919. * @type {boolean}
  51920. */
  51921. _this.invert = true;
  51922. /**
  51923. * Array containing the excluded meshes not rendered in the internal pass
  51924. */
  51925. _this.excludedMeshes = new Array();
  51926. /**
  51927. * Controls the overall intensity of the post-process
  51928. * @type {number}
  51929. */
  51930. _this.exposure = 0.3;
  51931. /**
  51932. * Dissipates each sample's contribution in range [0, 1]
  51933. * @type {number}
  51934. */
  51935. _this.decay = 0.96815;
  51936. /**
  51937. * Controls the overall intensity of each sample
  51938. * @type {number}
  51939. */
  51940. _this.weight = 0.58767;
  51941. /**
  51942. * Controls the density of each sample
  51943. * @type {number}
  51944. */
  51945. _this.density = 0.926;
  51946. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  51947. var engine = scene.getEngine();
  51948. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  51949. // Configure mesh
  51950. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  51951. // Configure
  51952. _this._createPass(scene, ratio.passRatio || ratio);
  51953. _this.onActivate = function (camera) {
  51954. if (!_this.isSupported) {
  51955. _this.dispose(camera);
  51956. }
  51957. _this.onActivate = null;
  51958. };
  51959. _this.onApplyObservable.add(function (effect) {
  51960. _this._updateMeshScreenCoordinates(scene);
  51961. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  51962. effect.setFloat("exposure", _this.exposure);
  51963. effect.setFloat("decay", _this.decay);
  51964. effect.setFloat("weight", _this.weight);
  51965. effect.setFloat("density", _this.density);
  51966. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  51967. });
  51968. return _this;
  51969. }
  51970. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  51971. get: function () {
  51972. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51973. return false;
  51974. },
  51975. set: function (useDiffuseColor) {
  51976. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51977. },
  51978. enumerable: true,
  51979. configurable: true
  51980. });
  51981. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  51982. var mesh = subMesh.getMesh();
  51983. // Render this.mesh as default
  51984. if (mesh === this.mesh) {
  51985. return mesh.material.isReady(mesh);
  51986. }
  51987. var defines = [];
  51988. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51989. var material = subMesh.getMaterial();
  51990. var needUV = false;
  51991. // Alpha test
  51992. if (material) {
  51993. if (material.needAlphaTesting()) {
  51994. defines.push("#define ALPHATEST");
  51995. }
  51996. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51997. attribs.push(BABYLON.VertexBuffer.UVKind);
  51998. defines.push("#define UV1");
  51999. }
  52000. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52001. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52002. defines.push("#define UV2");
  52003. }
  52004. }
  52005. // Bones
  52006. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52007. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52008. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52009. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52010. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52011. }
  52012. else {
  52013. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52014. }
  52015. // Instances
  52016. if (useInstances) {
  52017. defines.push("#define INSTANCES");
  52018. attribs.push("world0");
  52019. attribs.push("world1");
  52020. attribs.push("world2");
  52021. attribs.push("world3");
  52022. }
  52023. // Get correct effect
  52024. var join = defines.join("\n");
  52025. if (this._cachedDefines !== join) {
  52026. this._cachedDefines = join;
  52027. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  52028. }
  52029. return this._volumetricLightScatteringPass.isReady();
  52030. };
  52031. /**
  52032. * Sets the new light position for light scattering effect
  52033. * @param {BABYLON.Vector3} The new custom light position
  52034. */
  52035. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  52036. this.customMeshPosition = position;
  52037. };
  52038. /**
  52039. * Returns the light position for light scattering effect
  52040. * @return {BABYLON.Vector3} The custom light position
  52041. */
  52042. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  52043. return this.customMeshPosition;
  52044. };
  52045. /**
  52046. * Disposes the internal assets and detaches the post-process from the camera
  52047. */
  52048. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  52049. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  52050. if (rttIndex !== -1) {
  52051. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  52052. }
  52053. this._volumetricLightScatteringRTT.dispose();
  52054. _super.prototype.dispose.call(this, camera);
  52055. };
  52056. /**
  52057. * Returns the render target texture used by the post-process
  52058. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52059. */
  52060. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52061. return this._volumetricLightScatteringRTT;
  52062. };
  52063. // Private methods
  52064. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52065. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52066. return true;
  52067. }
  52068. return false;
  52069. };
  52070. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52071. var _this = this;
  52072. var engine = scene.getEngine();
  52073. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52074. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52075. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52076. this._volumetricLightScatteringRTT.renderList = null;
  52077. this._volumetricLightScatteringRTT.renderParticles = false;
  52078. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52079. // Custom render function for submeshes
  52080. var renderSubMesh = function (subMesh) {
  52081. var mesh = subMesh.getRenderingMesh();
  52082. if (_this._meshExcluded(mesh)) {
  52083. return;
  52084. }
  52085. var scene = mesh.getScene();
  52086. var engine = scene.getEngine();
  52087. // Culling
  52088. engine.setState(subMesh.getMaterial().backFaceCulling);
  52089. // Managing instances
  52090. var batch = mesh._getInstancesRenderList(subMesh._id);
  52091. if (batch.mustReturn) {
  52092. return;
  52093. }
  52094. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  52095. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52096. var effect = _this._volumetricLightScatteringPass;
  52097. if (mesh === _this.mesh) {
  52098. if (subMesh.effect) {
  52099. effect = subMesh.effect;
  52100. }
  52101. else {
  52102. effect = subMesh.getMaterial().getEffect();
  52103. }
  52104. }
  52105. engine.enableEffect(effect);
  52106. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52107. if (mesh === _this.mesh) {
  52108. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52109. }
  52110. else {
  52111. var material = subMesh.getMaterial();
  52112. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52113. // Alpha test
  52114. if (material && material.needAlphaTesting()) {
  52115. var alphaTexture = material.getAlphaTestTexture();
  52116. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52117. if (alphaTexture) {
  52118. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52119. }
  52120. }
  52121. // Bones
  52122. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52123. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52124. }
  52125. }
  52126. // Draw
  52127. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52128. }
  52129. };
  52130. // Render target texture callbacks
  52131. var savedSceneClearColor;
  52132. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52133. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52134. savedSceneClearColor = scene.clearColor;
  52135. scene.clearColor = sceneClearColor;
  52136. });
  52137. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52138. scene.clearColor = savedSceneClearColor;
  52139. });
  52140. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52141. var engine = scene.getEngine();
  52142. var index;
  52143. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52144. renderSubMesh(opaqueSubMeshes.data[index]);
  52145. }
  52146. engine.setAlphaTesting(true);
  52147. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52148. renderSubMesh(alphaTestSubMeshes.data[index]);
  52149. }
  52150. engine.setAlphaTesting(false);
  52151. if (transparentSubMeshes.length) {
  52152. // Sort sub meshes
  52153. for (index = 0; index < transparentSubMeshes.length; index++) {
  52154. var submesh = transparentSubMeshes.data[index];
  52155. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52156. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52157. }
  52158. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  52159. sortedArray.sort(function (a, b) {
  52160. // Alpha index first
  52161. if (a._alphaIndex > b._alphaIndex) {
  52162. return 1;
  52163. }
  52164. if (a._alphaIndex < b._alphaIndex) {
  52165. return -1;
  52166. }
  52167. // Then distance to camera
  52168. if (a._distanceToCamera < b._distanceToCamera) {
  52169. return 1;
  52170. }
  52171. if (a._distanceToCamera > b._distanceToCamera) {
  52172. return -1;
  52173. }
  52174. return 0;
  52175. });
  52176. // Render sub meshes
  52177. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52178. for (index = 0; index < sortedArray.length; index++) {
  52179. renderSubMesh(sortedArray[index]);
  52180. }
  52181. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52182. }
  52183. };
  52184. };
  52185. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  52186. var transform = scene.getTransformMatrix();
  52187. var meshPosition;
  52188. if (this.useCustomMeshPosition) {
  52189. meshPosition = this.customMeshPosition;
  52190. }
  52191. else if (this.attachedNode) {
  52192. meshPosition = this.attachedNode.position;
  52193. }
  52194. else {
  52195. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  52196. }
  52197. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  52198. this._screenCoordinates.x = pos.x / this._viewPort.width;
  52199. this._screenCoordinates.y = pos.y / this._viewPort.height;
  52200. if (this.invert)
  52201. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  52202. };
  52203. // Static methods
  52204. /**
  52205. * Creates a default mesh for the Volumeric Light Scattering post-process
  52206. * @param {string} The mesh name
  52207. * @param {BABYLON.Scene} The scene where to create the mesh
  52208. * @return {BABYLON.Mesh} the default mesh
  52209. */
  52210. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  52211. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  52212. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  52213. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  52214. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  52215. mesh.material = material;
  52216. return mesh;
  52217. };
  52218. return VolumetricLightScatteringPostProcess;
  52219. }(BABYLON.PostProcess));
  52220. __decorate([
  52221. BABYLON.serializeAsVector3()
  52222. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  52223. __decorate([
  52224. BABYLON.serialize()
  52225. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  52226. __decorate([
  52227. BABYLON.serialize()
  52228. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  52229. __decorate([
  52230. BABYLON.serializeAsMeshReference()
  52231. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  52232. __decorate([
  52233. BABYLON.serialize()
  52234. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  52235. __decorate([
  52236. BABYLON.serialize()
  52237. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  52238. __decorate([
  52239. BABYLON.serialize()
  52240. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  52241. __decorate([
  52242. BABYLON.serialize()
  52243. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  52244. __decorate([
  52245. BABYLON.serialize()
  52246. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  52247. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  52248. })(BABYLON || (BABYLON = {}));
  52249. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  52250. //
  52251. // This post-process allows the modification of rendered colors by using
  52252. // a 'look-up table' (LUT). This effect is also called Color Grading.
  52253. //
  52254. // The object needs to be provided an url to a texture containing the color
  52255. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  52256. // Use an image editing software to tweak the LUT to match your needs.
  52257. //
  52258. // For an example of a color LUT, see here:
  52259. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  52260. // For explanations on color grading, see here:
  52261. // http://udn.epicgames.com/Three/ColorGrading.html
  52262. //
  52263. var BABYLON;
  52264. (function (BABYLON) {
  52265. var ColorCorrectionPostProcess = (function (_super) {
  52266. __extends(ColorCorrectionPostProcess, _super);
  52267. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  52268. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  52269. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52270. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  52271. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52272. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52273. _this.onApply = function (effect) {
  52274. effect.setTexture("colorTable", _this._colorTableTexture);
  52275. };
  52276. return _this;
  52277. }
  52278. return ColorCorrectionPostProcess;
  52279. }(BABYLON.PostProcess));
  52280. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  52281. })(BABYLON || (BABYLON = {}));
  52282. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  52283. var BABYLON;
  52284. (function (BABYLON) {
  52285. var TonemappingOperator;
  52286. (function (TonemappingOperator) {
  52287. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  52288. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  52289. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  52290. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  52291. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  52292. ;
  52293. var TonemapPostProcess = (function (_super) {
  52294. __extends(TonemapPostProcess, _super);
  52295. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  52296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52297. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52298. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  52299. _this._operator = _operator;
  52300. _this.exposureAdjustment = exposureAdjustment;
  52301. var defines = "#define ";
  52302. if (_this._operator === TonemappingOperator.Hable)
  52303. defines += "HABLE_TONEMAPPING";
  52304. else if (_this._operator === TonemappingOperator.Reinhard)
  52305. defines += "REINHARD_TONEMAPPING";
  52306. else if (_this._operator === TonemappingOperator.HejiDawson)
  52307. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  52308. else if (_this._operator === TonemappingOperator.Photographic)
  52309. defines += "PHOTOGRAPHIC_TONEMAPPING";
  52310. //sadly a second call to create the effect.
  52311. _this.updateEffect(defines);
  52312. _this.onApply = function (effect) {
  52313. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  52314. };
  52315. return _this;
  52316. }
  52317. return TonemapPostProcess;
  52318. }(BABYLON.PostProcess));
  52319. BABYLON.TonemapPostProcess = TonemapPostProcess;
  52320. })(BABYLON || (BABYLON = {}));
  52321. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  52322. var BABYLON;
  52323. (function (BABYLON) {
  52324. var DisplayPassPostProcess = (function (_super) {
  52325. __extends(DisplayPassPostProcess, _super);
  52326. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  52327. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  52328. }
  52329. return DisplayPassPostProcess;
  52330. }(BABYLON.PostProcess));
  52331. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  52332. })(BABYLON || (BABYLON = {}));
  52333. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  52334. var BABYLON;
  52335. (function (BABYLON) {
  52336. var HighlightsPostProcess = (function (_super) {
  52337. __extends(HighlightsPostProcess, _super);
  52338. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52339. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52340. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  52341. }
  52342. return HighlightsPostProcess;
  52343. }(BABYLON.PostProcess));
  52344. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  52345. })(BABYLON || (BABYLON = {}));
  52346. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  52347. var BABYLON;
  52348. (function (BABYLON) {
  52349. var ImageProcessingPostProcess = (function (_super) {
  52350. __extends(ImageProcessingPostProcess, _super);
  52351. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52352. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52353. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  52354. _this._fromLinearSpace = true;
  52355. /**
  52356. * Defines cache preventing GC.
  52357. */
  52358. _this._defines = {
  52359. IMAGEPROCESSING: false,
  52360. VIGNETTE: false,
  52361. VIGNETTEBLENDMODEMULTIPLY: false,
  52362. VIGNETTEBLENDMODEOPAQUE: false,
  52363. TONEMAPPING: false,
  52364. CONTRAST: false,
  52365. COLORCURVES: false,
  52366. COLORGRADING: false,
  52367. FROMLINEARSPACE: false,
  52368. SAMPLER3DGREENDEPTH: false,
  52369. SAMPLER3DBGRMAP: false,
  52370. IMAGEPROCESSINGPOSTPROCESS: false,
  52371. EXPOSURE: false,
  52372. };
  52373. // Setup the default processing configuration to the scene.
  52374. _this._attachImageProcessingConfiguration(null);
  52375. _this.imageProcessingConfiguration.applyByPostProcess = true;
  52376. _this._updateParameters();
  52377. _this.onApply = function (effect) {
  52378. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  52379. };
  52380. return _this;
  52381. }
  52382. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  52383. /**
  52384. * Gets the image processing configuration used either in this material.
  52385. */
  52386. get: function () {
  52387. return this._imageProcessingConfiguration;
  52388. },
  52389. /**
  52390. * Sets the Default image processing configuration used either in the this material.
  52391. *
  52392. * If sets to null, the scene one is in use.
  52393. */
  52394. set: function (value) {
  52395. this._attachImageProcessingConfiguration(value);
  52396. },
  52397. enumerable: true,
  52398. configurable: true
  52399. });
  52400. /**
  52401. * Attaches a new image processing configuration to the PBR Material.
  52402. * @param configuration
  52403. */
  52404. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration) {
  52405. var _this = this;
  52406. if (configuration === this._imageProcessingConfiguration) {
  52407. return;
  52408. }
  52409. // Detaches observer.
  52410. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  52411. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  52412. }
  52413. // Pick the scene configuration if needed.
  52414. if (!configuration) {
  52415. var camera = this.getCamera();
  52416. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  52417. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  52418. }
  52419. else {
  52420. this._imageProcessingConfiguration = configuration;
  52421. }
  52422. // Attaches observer.
  52423. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  52424. _this._updateParameters();
  52425. });
  52426. // Ensure the effect will be rebuilt.
  52427. this._updateParameters();
  52428. };
  52429. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  52430. /**
  52431. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  52432. */
  52433. get: function () {
  52434. return this.imageProcessingConfiguration.colorCurves;
  52435. },
  52436. /**
  52437. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  52438. */
  52439. set: function (value) {
  52440. this.imageProcessingConfiguration.colorCurves = value;
  52441. },
  52442. enumerable: true,
  52443. configurable: true
  52444. });
  52445. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  52446. /**
  52447. * Gets wether the color curves effect is enabled.
  52448. */
  52449. get: function () {
  52450. return this.imageProcessingConfiguration.colorCurvesEnabled;
  52451. },
  52452. /**
  52453. * Sets wether the color curves effect is enabled.
  52454. */
  52455. set: function (value) {
  52456. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  52457. },
  52458. enumerable: true,
  52459. configurable: true
  52460. });
  52461. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  52462. /**
  52463. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  52464. */
  52465. get: function () {
  52466. return this.imageProcessingConfiguration.colorGradingTexture;
  52467. },
  52468. /**
  52469. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  52470. */
  52471. set: function (value) {
  52472. this.imageProcessingConfiguration.colorGradingTexture = value;
  52473. },
  52474. enumerable: true,
  52475. configurable: true
  52476. });
  52477. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  52478. /**
  52479. * Gets wether the color grading effect is enabled.
  52480. */
  52481. get: function () {
  52482. return this.imageProcessingConfiguration.colorGradingEnabled;
  52483. },
  52484. /**
  52485. * Gets wether the color grading effect is enabled.
  52486. */
  52487. set: function (value) {
  52488. this.imageProcessingConfiguration.colorGradingEnabled = value;
  52489. },
  52490. enumerable: true,
  52491. configurable: true
  52492. });
  52493. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  52494. /**
  52495. * Gets exposure used in the effect.
  52496. */
  52497. get: function () {
  52498. return this.imageProcessingConfiguration.exposure;
  52499. },
  52500. /**
  52501. * Sets exposure used in the effect.
  52502. */
  52503. set: function (value) {
  52504. this.imageProcessingConfiguration.exposure = value;
  52505. },
  52506. enumerable: true,
  52507. configurable: true
  52508. });
  52509. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  52510. /**
  52511. * Gets wether tonemapping is enabled or not.
  52512. */
  52513. get: function () {
  52514. return this._imageProcessingConfiguration.toneMappingEnabled;
  52515. },
  52516. /**
  52517. * Sets wether tonemapping is enabled or not
  52518. */
  52519. set: function (value) {
  52520. this._imageProcessingConfiguration.toneMappingEnabled = value;
  52521. },
  52522. enumerable: true,
  52523. configurable: true
  52524. });
  52525. ;
  52526. ;
  52527. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  52528. /**
  52529. * Gets contrast used in the effect.
  52530. */
  52531. get: function () {
  52532. return this.imageProcessingConfiguration.contrast;
  52533. },
  52534. /**
  52535. * Sets contrast used in the effect.
  52536. */
  52537. set: function (value) {
  52538. this.imageProcessingConfiguration.contrast = value;
  52539. },
  52540. enumerable: true,
  52541. configurable: true
  52542. });
  52543. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  52544. /**
  52545. * Gets Vignette stretch size.
  52546. */
  52547. get: function () {
  52548. return this.imageProcessingConfiguration.vignetteStretch;
  52549. },
  52550. /**
  52551. * Sets Vignette stretch size.
  52552. */
  52553. set: function (value) {
  52554. this.imageProcessingConfiguration.vignetteStretch = value;
  52555. },
  52556. enumerable: true,
  52557. configurable: true
  52558. });
  52559. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  52560. /**
  52561. * Gets Vignette centre X Offset.
  52562. */
  52563. get: function () {
  52564. return this.imageProcessingConfiguration.vignetteCentreX;
  52565. },
  52566. /**
  52567. * Sets Vignette centre X Offset.
  52568. */
  52569. set: function (value) {
  52570. this.imageProcessingConfiguration.vignetteCentreX = value;
  52571. },
  52572. enumerable: true,
  52573. configurable: true
  52574. });
  52575. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  52576. /**
  52577. * Gets Vignette centre Y Offset.
  52578. */
  52579. get: function () {
  52580. return this.imageProcessingConfiguration.vignetteCentreY;
  52581. },
  52582. /**
  52583. * Sets Vignette centre Y Offset.
  52584. */
  52585. set: function (value) {
  52586. this.imageProcessingConfiguration.vignetteCentreY = value;
  52587. },
  52588. enumerable: true,
  52589. configurable: true
  52590. });
  52591. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  52592. /**
  52593. * Gets Vignette weight or intensity of the vignette effect.
  52594. */
  52595. get: function () {
  52596. return this.imageProcessingConfiguration.vignetteWeight;
  52597. },
  52598. /**
  52599. * Sets Vignette weight or intensity of the vignette effect.
  52600. */
  52601. set: function (value) {
  52602. this.imageProcessingConfiguration.vignetteWeight = value;
  52603. },
  52604. enumerable: true,
  52605. configurable: true
  52606. });
  52607. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  52608. /**
  52609. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  52610. * if vignetteEnabled is set to true.
  52611. */
  52612. get: function () {
  52613. return this.imageProcessingConfiguration.vignetteColor;
  52614. },
  52615. /**
  52616. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  52617. * if vignetteEnabled is set to true.
  52618. */
  52619. set: function (value) {
  52620. this.imageProcessingConfiguration.vignetteColor = value;
  52621. },
  52622. enumerable: true,
  52623. configurable: true
  52624. });
  52625. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  52626. /**
  52627. * Gets Camera field of view used by the Vignette effect.
  52628. */
  52629. get: function () {
  52630. return this.imageProcessingConfiguration.vignetteCameraFov;
  52631. },
  52632. /**
  52633. * Sets Camera field of view used by the Vignette effect.
  52634. */
  52635. set: function (value) {
  52636. this.imageProcessingConfiguration.vignetteCameraFov = value;
  52637. },
  52638. enumerable: true,
  52639. configurable: true
  52640. });
  52641. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  52642. /**
  52643. * Gets the vignette blend mode allowing different kind of effect.
  52644. */
  52645. get: function () {
  52646. return this.imageProcessingConfiguration.vignetteBlendMode;
  52647. },
  52648. /**
  52649. * Sets the vignette blend mode allowing different kind of effect.
  52650. */
  52651. set: function (value) {
  52652. this.imageProcessingConfiguration.vignetteBlendMode = value;
  52653. },
  52654. enumerable: true,
  52655. configurable: true
  52656. });
  52657. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  52658. /**
  52659. * Gets wether the vignette effect is enabled.
  52660. */
  52661. get: function () {
  52662. return this.imageProcessingConfiguration.vignetteEnabled;
  52663. },
  52664. /**
  52665. * Sets wether the vignette effect is enabled.
  52666. */
  52667. set: function (value) {
  52668. this.imageProcessingConfiguration.vignetteEnabled = value;
  52669. },
  52670. enumerable: true,
  52671. configurable: true
  52672. });
  52673. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  52674. /**
  52675. * Gets wether the input of the processing is in Gamma or Linear Space.
  52676. */
  52677. get: function () {
  52678. return this._fromLinearSpace;
  52679. },
  52680. /**
  52681. * Sets wether the input of the processing is in Gamma or Linear Space.
  52682. */
  52683. set: function (value) {
  52684. if (this._fromLinearSpace === value) {
  52685. return;
  52686. }
  52687. this._fromLinearSpace = value;
  52688. this._updateParameters();
  52689. },
  52690. enumerable: true,
  52691. configurable: true
  52692. });
  52693. ImageProcessingPostProcess.prototype._updateParameters = function () {
  52694. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  52695. this.imageProcessingConfiguration.prepareDefines(this._defines);
  52696. var defines = "";
  52697. for (var define in this._defines) {
  52698. if (this._defines[define]) {
  52699. defines += "#define " + define + ";\r\n";
  52700. }
  52701. }
  52702. var samplers = ["textureSampler"];
  52703. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  52704. var uniforms = ["scale"];
  52705. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  52706. this.updateEffect(defines, uniforms, samplers);
  52707. };
  52708. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  52709. _super.prototype.dispose.call(this, camera);
  52710. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  52711. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  52712. }
  52713. this.imageProcessingConfiguration.applyByPostProcess = false;
  52714. };
  52715. return ImageProcessingPostProcess;
  52716. }(BABYLON.PostProcess));
  52717. __decorate([
  52718. BABYLON.serialize()
  52719. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  52720. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  52721. })(BABYLON || (BABYLON = {}));
  52722. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  52723. var BABYLON;
  52724. (function (BABYLON) {
  52725. var BlurPostProcess = (function (_super) {
  52726. __extends(BlurPostProcess, _super);
  52727. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  52728. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52729. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52730. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  52731. _this.direction = direction;
  52732. _this._packedFloat = false;
  52733. _this.onApplyObservable.add(function (effect) {
  52734. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  52735. });
  52736. _this.kernel = kernel;
  52737. return _this;
  52738. }
  52739. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  52740. /**
  52741. * Gets the length in pixels of the blur sample region
  52742. */
  52743. get: function () {
  52744. return this._idealKernel;
  52745. },
  52746. /**
  52747. * Sets the length in pixels of the blur sample region
  52748. */
  52749. set: function (v) {
  52750. if (this._idealKernel === v) {
  52751. return;
  52752. }
  52753. v = Math.max(v, 1);
  52754. this._idealKernel = v;
  52755. this._kernel = this._nearestBestKernel(v);
  52756. this._updateParameters();
  52757. },
  52758. enumerable: true,
  52759. configurable: true
  52760. });
  52761. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  52762. /**
  52763. * Gets wether or not the blur is unpacking/repacking floats
  52764. */
  52765. get: function () {
  52766. return this._packedFloat;
  52767. },
  52768. /**
  52769. * Sets wether or not the blur needs to unpack/repack floats
  52770. */
  52771. set: function (v) {
  52772. if (this._packedFloat === v) {
  52773. return;
  52774. }
  52775. this._packedFloat = v;
  52776. this._updateParameters();
  52777. },
  52778. enumerable: true,
  52779. configurable: true
  52780. });
  52781. BlurPostProcess.prototype._updateParameters = function () {
  52782. // Generate sampling offsets and weights
  52783. var N = this._kernel;
  52784. var centerIndex = (N - 1) / 2;
  52785. // Generate Gaussian sampling weights over kernel
  52786. var offsets = [];
  52787. var weights = [];
  52788. var totalWeight = 0;
  52789. for (var i = 0; i < N; i++) {
  52790. var u = i / (N - 1);
  52791. var w = this._gaussianWeight(u * 2.0 - 1);
  52792. offsets[i] = (i - centerIndex);
  52793. weights[i] = w;
  52794. totalWeight += w;
  52795. }
  52796. // Normalize weights
  52797. for (var i = 0; i < weights.length; i++) {
  52798. weights[i] /= totalWeight;
  52799. }
  52800. // Optimize: combine samples to take advantage of hardware linear sampling
  52801. // Walk from left to center, combining pairs (symmetrically)
  52802. var linearSamplingWeights = [];
  52803. var linearSamplingOffsets = [];
  52804. var linearSamplingMap = [];
  52805. for (var i = 0; i <= centerIndex; i += 2) {
  52806. var j = Math.min(i + 1, Math.floor(centerIndex));
  52807. var singleCenterSample = i === j;
  52808. if (singleCenterSample) {
  52809. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  52810. }
  52811. else {
  52812. var sharedCell = j === centerIndex;
  52813. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  52814. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  52815. if (offsetLinear === 0) {
  52816. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  52817. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  52818. }
  52819. else {
  52820. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  52821. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  52822. }
  52823. }
  52824. }
  52825. for (var i = 0; i < linearSamplingMap.length; i++) {
  52826. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  52827. linearSamplingWeights[i] = linearSamplingMap[i].w;
  52828. }
  52829. // Replace with optimized
  52830. offsets = linearSamplingOffsets;
  52831. weights = linearSamplingWeights;
  52832. // Generate shaders
  52833. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  52834. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  52835. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  52836. var defines = "";
  52837. for (var i = 0; i < varyingCount; i++) {
  52838. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  52839. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  52840. }
  52841. var depCount = 0;
  52842. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  52843. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  52844. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  52845. depCount++;
  52846. }
  52847. if (this.packedFloat) {
  52848. defines += "#define PACKEDFLOAT 1";
  52849. }
  52850. this.updateEffect(defines, null, null, {
  52851. varyingCount: varyingCount,
  52852. depCount: depCount
  52853. });
  52854. };
  52855. /**
  52856. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  52857. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  52858. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  52859. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  52860. * The gaps between physical kernels are compensated for in the weighting of the samples
  52861. * @param idealKernel Ideal blur kernel.
  52862. * @return Nearest best kernel.
  52863. */
  52864. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  52865. var v = Math.round(idealKernel);
  52866. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  52867. var k = _a[_i];
  52868. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  52869. return Math.max(k, 3);
  52870. }
  52871. }
  52872. return Math.max(v, 3);
  52873. };
  52874. /**
  52875. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  52876. * @param x The point on the Gaussian distribution to sample.
  52877. * @return the value of the Gaussian function at x.
  52878. */
  52879. BlurPostProcess.prototype._gaussianWeight = function (x) {
  52880. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  52881. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  52882. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  52883. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  52884. // truncated at around 1.3% of peak strength.
  52885. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  52886. var sigma = (1 / 3);
  52887. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  52888. var exponent = -((x * x) / (2.0 * sigma * sigma));
  52889. var weight = (1.0 / denominator) * Math.exp(exponent);
  52890. return weight;
  52891. };
  52892. /**
  52893. * Generates a string that can be used as a floating point number in GLSL.
  52894. * @param x Value to print.
  52895. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  52896. * @return GLSL float string.
  52897. */
  52898. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  52899. if (decimalFigures === void 0) { decimalFigures = 8; }
  52900. return x.toFixed(decimalFigures).replace(/0+$/, '');
  52901. };
  52902. return BlurPostProcess;
  52903. }(BABYLON.PostProcess));
  52904. BABYLON.BlurPostProcess = BlurPostProcess;
  52905. })(BABYLON || (BABYLON = {}));
  52906. //# sourceMappingURL=babylon.blurPostProcess.js.map
  52907. /// <reference path="..\babylon.node.ts" />
  52908. var BABYLON;
  52909. (function (BABYLON) {
  52910. var Bone = (function (_super) {
  52911. __extends(Bone, _super);
  52912. function Bone(name, skeleton, parentBone, matrix, restPose) {
  52913. if (parentBone === void 0) { parentBone = null; }
  52914. var _this = _super.call(this, name, skeleton.getScene()) || this;
  52915. _this.name = name;
  52916. _this.children = new Array();
  52917. _this.animations = new Array();
  52918. _this._worldTransform = new BABYLON.Matrix();
  52919. _this._absoluteTransform = new BABYLON.Matrix();
  52920. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  52921. _this._scaleMatrix = BABYLON.Matrix.Identity();
  52922. _this._scaleVector = BABYLON.Vector3.One();
  52923. _this._negateScaleChildren = BABYLON.Vector3.One();
  52924. _this._scalingDeterminant = 1;
  52925. _this._skeleton = skeleton;
  52926. _this._localMatrix = matrix ? matrix : BABYLON.Matrix.Identity();
  52927. _this._baseMatrix = _this._localMatrix.clone();
  52928. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  52929. skeleton.bones.push(_this);
  52930. _this.setParent(parentBone, false);
  52931. _this._updateDifferenceMatrix();
  52932. return _this;
  52933. }
  52934. Object.defineProperty(Bone.prototype, "_matrix", {
  52935. get: function () {
  52936. return this._localMatrix;
  52937. },
  52938. set: function (val) {
  52939. if (this._localMatrix) {
  52940. this._localMatrix.copyFrom(val);
  52941. }
  52942. else {
  52943. this._localMatrix = val;
  52944. }
  52945. },
  52946. enumerable: true,
  52947. configurable: true
  52948. });
  52949. // Members
  52950. Bone.prototype.getSkeleton = function () {
  52951. return this._skeleton;
  52952. };
  52953. Bone.prototype.getParent = function () {
  52954. return this._parent;
  52955. };
  52956. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  52957. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  52958. if (this._parent === parent) {
  52959. return;
  52960. }
  52961. if (this._parent) {
  52962. var index = this._parent.children.indexOf(this);
  52963. if (index !== -1) {
  52964. this._parent.children.splice(index);
  52965. }
  52966. }
  52967. this._parent = parent;
  52968. if (this._parent) {
  52969. this._parent.children.push(this);
  52970. }
  52971. if (updateDifferenceMatrix) {
  52972. this._updateDifferenceMatrix();
  52973. }
  52974. };
  52975. Bone.prototype.getLocalMatrix = function () {
  52976. return this._localMatrix;
  52977. };
  52978. Bone.prototype.getBaseMatrix = function () {
  52979. return this._baseMatrix;
  52980. };
  52981. Bone.prototype.getRestPose = function () {
  52982. return this._restPose;
  52983. };
  52984. Bone.prototype.returnToRest = function () {
  52985. this.updateMatrix(this._restPose.clone());
  52986. };
  52987. Bone.prototype.getWorldMatrix = function () {
  52988. return this._worldTransform;
  52989. };
  52990. Bone.prototype.getInvertedAbsoluteTransform = function () {
  52991. return this._invertedAbsoluteTransform;
  52992. };
  52993. Bone.prototype.getAbsoluteTransform = function () {
  52994. return this._absoluteTransform;
  52995. };
  52996. Object.defineProperty(Bone.prototype, "position", {
  52997. // Properties (matches AbstractMesh properties)
  52998. get: function () {
  52999. return this.getPosition();
  53000. },
  53001. set: function (newPosition) {
  53002. this.setPosition(newPosition);
  53003. },
  53004. enumerable: true,
  53005. configurable: true
  53006. });
  53007. Object.defineProperty(Bone.prototype, "rotation", {
  53008. get: function () {
  53009. return this.getRotation();
  53010. },
  53011. set: function (newRotation) {
  53012. this.setRotation(newRotation);
  53013. },
  53014. enumerable: true,
  53015. configurable: true
  53016. });
  53017. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  53018. get: function () {
  53019. return this.getRotationQuaternion();
  53020. },
  53021. set: function (newRotation) {
  53022. this.setRotationQuaternion(newRotation);
  53023. },
  53024. enumerable: true,
  53025. configurable: true
  53026. });
  53027. Object.defineProperty(Bone.prototype, "scaling", {
  53028. get: function () {
  53029. return this.getScale();
  53030. },
  53031. set: function (newScaling) {
  53032. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  53033. },
  53034. enumerable: true,
  53035. configurable: true
  53036. });
  53037. // Methods
  53038. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  53039. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  53040. this._baseMatrix = matrix.clone();
  53041. this._localMatrix = matrix.clone();
  53042. this._skeleton._markAsDirty();
  53043. if (updateDifferenceMatrix) {
  53044. this._updateDifferenceMatrix();
  53045. }
  53046. };
  53047. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  53048. if (!rootMatrix) {
  53049. rootMatrix = this._baseMatrix;
  53050. }
  53051. if (this._parent) {
  53052. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  53053. }
  53054. else {
  53055. this._absoluteTransform.copyFrom(rootMatrix);
  53056. }
  53057. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  53058. for (var index = 0; index < this.children.length; index++) {
  53059. this.children[index]._updateDifferenceMatrix();
  53060. }
  53061. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  53062. };
  53063. Bone.prototype.markAsDirty = function () {
  53064. this._currentRenderId++;
  53065. this._skeleton._markAsDirty();
  53066. };
  53067. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  53068. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  53069. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  53070. // all animation may be coming from a library skeleton, so may need to create animation
  53071. if (this.animations.length === 0) {
  53072. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  53073. this.animations[0].setKeys([]);
  53074. }
  53075. // get animation info / verify there is such a range from the source bone
  53076. var sourceRange = source.animations[0].getRange(rangeName);
  53077. if (!sourceRange) {
  53078. return false;
  53079. }
  53080. var from = sourceRange.from;
  53081. var to = sourceRange.to;
  53082. var sourceKeys = source.animations[0].getKeys();
  53083. // rescaling prep
  53084. var sourceBoneLength = source.length;
  53085. var sourceParent = source.getParent();
  53086. var parent = this.getParent();
  53087. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  53088. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  53089. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  53090. var destKeys = this.animations[0].getKeys();
  53091. // loop vars declaration
  53092. var orig;
  53093. var origTranslation;
  53094. var mat;
  53095. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  53096. orig = sourceKeys[key];
  53097. if (orig.frame >= from && orig.frame <= to) {
  53098. if (rescaleAsRequired) {
  53099. mat = orig.value.clone();
  53100. // scale based on parent ratio, when bone has parent
  53101. if (parentScalingReqd) {
  53102. origTranslation = mat.getTranslation();
  53103. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  53104. // scale based on skeleton dimension ratio when root bone, and value is passed
  53105. }
  53106. else if (dimensionsScalingReqd) {
  53107. origTranslation = mat.getTranslation();
  53108. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  53109. // use original when root bone, and no data for skelDimensionsRatio
  53110. }
  53111. else {
  53112. mat = orig.value;
  53113. }
  53114. }
  53115. else {
  53116. mat = orig.value;
  53117. }
  53118. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  53119. }
  53120. }
  53121. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  53122. return true;
  53123. };
  53124. /**
  53125. * Translate the bone in local or world space.
  53126. * @param vec The amount to translate the bone.
  53127. * @param space The space that the translation is in.
  53128. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53129. */
  53130. Bone.prototype.translate = function (vec, space, mesh) {
  53131. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53132. var lm = this.getLocalMatrix();
  53133. if (space == BABYLON.Space.LOCAL) {
  53134. lm.m[12] += vec.x;
  53135. lm.m[13] += vec.y;
  53136. lm.m[14] += vec.z;
  53137. }
  53138. else {
  53139. var wm;
  53140. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53141. if (mesh) {
  53142. wm = mesh.getWorldMatrix();
  53143. }
  53144. this._skeleton.computeAbsoluteTransforms();
  53145. var tmat = Bone._tmpMats[0];
  53146. var tvec = Bone._tmpVecs[0];
  53147. if (mesh) {
  53148. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53149. tmat.multiplyToRef(wm, tmat);
  53150. }
  53151. else {
  53152. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53153. }
  53154. tmat.m[12] = 0;
  53155. tmat.m[13] = 0;
  53156. tmat.m[14] = 0;
  53157. tmat.invert();
  53158. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  53159. lm.m[12] += tvec.x;
  53160. lm.m[13] += tvec.y;
  53161. lm.m[14] += tvec.z;
  53162. }
  53163. this.markAsDirty();
  53164. };
  53165. /**
  53166. * Set the postion of the bone in local or world space.
  53167. * @param position The position to set the bone.
  53168. * @param space The space that the position is in.
  53169. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53170. */
  53171. Bone.prototype.setPosition = function (position, space, mesh) {
  53172. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53173. var lm = this.getLocalMatrix();
  53174. if (space == BABYLON.Space.LOCAL) {
  53175. lm.m[12] = position.x;
  53176. lm.m[13] = position.y;
  53177. lm.m[14] = position.z;
  53178. }
  53179. else {
  53180. var wm;
  53181. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53182. if (mesh) {
  53183. wm = mesh.getWorldMatrix();
  53184. }
  53185. this._skeleton.computeAbsoluteTransforms();
  53186. var tmat = Bone._tmpMats[0];
  53187. var vec = Bone._tmpVecs[0];
  53188. if (mesh) {
  53189. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53190. tmat.multiplyToRef(wm, tmat);
  53191. }
  53192. else {
  53193. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53194. }
  53195. tmat.invert();
  53196. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  53197. lm.m[12] = vec.x;
  53198. lm.m[13] = vec.y;
  53199. lm.m[14] = vec.z;
  53200. }
  53201. this.markAsDirty();
  53202. };
  53203. /**
  53204. * Set the absolute postion of the bone (world space).
  53205. * @param position The position to set the bone.
  53206. * @param mesh The mesh that this bone is attached to.
  53207. */
  53208. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  53209. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  53210. };
  53211. /**
  53212. * Set the scale of the bone on the x, y and z axes.
  53213. * @param x The scale of the bone on the x axis.
  53214. * @param x The scale of the bone on the y axis.
  53215. * @param z The scale of the bone on the z axis.
  53216. * @param scaleChildren Set this to true if children of the bone should be scaled.
  53217. */
  53218. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  53219. if (scaleChildren === void 0) { scaleChildren = false; }
  53220. if (this.animations[0] && !this.animations[0].isStopped()) {
  53221. if (!scaleChildren) {
  53222. this._negateScaleChildren.x = 1 / x;
  53223. this._negateScaleChildren.y = 1 / y;
  53224. this._negateScaleChildren.z = 1 / z;
  53225. }
  53226. this._syncScaleVector();
  53227. }
  53228. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  53229. };
  53230. /**
  53231. * Scale the bone on the x, y and z axes.
  53232. * @param x The amount to scale the bone on the x axis.
  53233. * @param x The amount to scale the bone on the y axis.
  53234. * @param z The amount to scale the bone on the z axis.
  53235. * @param scaleChildren Set this to true if children of the bone should be scaled.
  53236. */
  53237. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  53238. if (scaleChildren === void 0) { scaleChildren = false; }
  53239. var locMat = this.getLocalMatrix();
  53240. var origLocMat = Bone._tmpMats[0];
  53241. origLocMat.copyFrom(locMat);
  53242. var origLocMatInv = Bone._tmpMats[1];
  53243. origLocMatInv.copyFrom(origLocMat);
  53244. origLocMatInv.invert();
  53245. var scaleMat = Bone._tmpMats[2];
  53246. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  53247. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  53248. this._scaleVector.x *= x;
  53249. this._scaleVector.y *= y;
  53250. this._scaleVector.z *= z;
  53251. locMat.multiplyToRef(origLocMatInv, locMat);
  53252. locMat.multiplyToRef(scaleMat, locMat);
  53253. locMat.multiplyToRef(origLocMat, locMat);
  53254. var parent = this.getParent();
  53255. if (parent) {
  53256. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  53257. }
  53258. else {
  53259. this.getAbsoluteTransform().copyFrom(locMat);
  53260. }
  53261. var len = this.children.length;
  53262. scaleMat.invert();
  53263. for (var i = 0; i < len; i++) {
  53264. var child = this.children[i];
  53265. var cm = child.getLocalMatrix();
  53266. cm.multiplyToRef(scaleMat, cm);
  53267. var lm = child.getLocalMatrix();
  53268. lm.m[12] *= x;
  53269. lm.m[13] *= y;
  53270. lm.m[14] *= z;
  53271. }
  53272. this.computeAbsoluteTransforms();
  53273. if (scaleChildren) {
  53274. for (var i = 0; i < len; i++) {
  53275. this.children[i].scale(x, y, z, scaleChildren);
  53276. }
  53277. }
  53278. this.markAsDirty();
  53279. };
  53280. /**
  53281. * Set the yaw, pitch, and roll of the bone in local or world space.
  53282. * @param yaw The rotation of the bone on the y axis.
  53283. * @param pitch The rotation of the bone on the x axis.
  53284. * @param roll The rotation of the bone on the z axis.
  53285. * @param space The space that the axes of rotation are in.
  53286. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53287. */
  53288. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  53289. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53290. var rotMat = Bone._tmpMats[0];
  53291. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  53292. var rotMatInv = Bone._tmpMats[1];
  53293. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53294. rotMatInv.multiplyToRef(rotMat, rotMat);
  53295. this._rotateWithMatrix(rotMat, space, mesh);
  53296. };
  53297. /**
  53298. * Rotate the bone on an axis in local or world space.
  53299. * @param axis The axis to rotate the bone on.
  53300. * @param amount The amount to rotate the bone.
  53301. * @param space The space that the axis is in.
  53302. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53303. */
  53304. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  53305. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53306. var rmat = Bone._tmpMats[0];
  53307. rmat.m[12] = 0;
  53308. rmat.m[13] = 0;
  53309. rmat.m[14] = 0;
  53310. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  53311. this._rotateWithMatrix(rmat, space, mesh);
  53312. };
  53313. /**
  53314. * Set the rotation of the bone to a particular axis angle in local or world space.
  53315. * @param axis The axis to rotate the bone on.
  53316. * @param angle The angle that the bone should be rotated to.
  53317. * @param space The space that the axis is in.
  53318. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53319. */
  53320. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  53321. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53322. var rotMat = Bone._tmpMats[0];
  53323. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  53324. var rotMatInv = Bone._tmpMats[1];
  53325. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53326. rotMatInv.multiplyToRef(rotMat, rotMat);
  53327. this._rotateWithMatrix(rotMat, space, mesh);
  53328. };
  53329. /**
  53330. * Set the euler rotation of the bone in local of world space.
  53331. * @param rotation The euler rotation that the bone should be set to.
  53332. * @param space The space that the rotation is in.
  53333. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53334. */
  53335. Bone.prototype.setRotation = function (rotation, space, mesh) {
  53336. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53337. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  53338. };
  53339. /**
  53340. * Set the quaternion rotation of the bone in local of world space.
  53341. * @param quat The quaternion rotation that the bone should be set to.
  53342. * @param space The space that the rotation is in.
  53343. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53344. */
  53345. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  53346. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53347. var rotMatInv = Bone._tmpMats[0];
  53348. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53349. var rotMat = Bone._tmpMats[1];
  53350. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  53351. rotMatInv.multiplyToRef(rotMat, rotMat);
  53352. this._rotateWithMatrix(rotMat, space, mesh);
  53353. };
  53354. /**
  53355. * Set the rotation matrix of the bone in local of world space.
  53356. * @param rotMat The rotation matrix that the bone should be set to.
  53357. * @param space The space that the rotation is in.
  53358. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53359. */
  53360. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  53361. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53362. var rotMatInv = Bone._tmpMats[0];
  53363. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53364. var rotMat2 = Bone._tmpMats[1];
  53365. rotMat2.copyFrom(rotMat);
  53366. rotMatInv.multiplyToRef(rotMat, rotMat2);
  53367. this._rotateWithMatrix(rotMat2, space, mesh);
  53368. };
  53369. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  53370. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53371. var lmat = this.getLocalMatrix();
  53372. var lx = lmat.m[12];
  53373. var ly = lmat.m[13];
  53374. var lz = lmat.m[14];
  53375. var parent = this.getParent();
  53376. var parentScale = Bone._tmpMats[3];
  53377. var parentScaleInv = Bone._tmpMats[4];
  53378. if (parent) {
  53379. if (space == BABYLON.Space.WORLD) {
  53380. if (mesh) {
  53381. parentScale.copyFrom(mesh.getWorldMatrix());
  53382. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  53383. }
  53384. else {
  53385. parentScale.copyFrom(parent.getAbsoluteTransform());
  53386. }
  53387. }
  53388. else {
  53389. parentScale = parent._scaleMatrix;
  53390. }
  53391. parentScaleInv.copyFrom(parentScale);
  53392. parentScaleInv.invert();
  53393. lmat.multiplyToRef(parentScale, lmat);
  53394. lmat.multiplyToRef(rmat, lmat);
  53395. lmat.multiplyToRef(parentScaleInv, lmat);
  53396. }
  53397. else {
  53398. if (space == BABYLON.Space.WORLD && mesh) {
  53399. parentScale.copyFrom(mesh.getWorldMatrix());
  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. lmat.multiplyToRef(rmat, lmat);
  53408. }
  53409. }
  53410. lmat.m[12] = lx;
  53411. lmat.m[13] = ly;
  53412. lmat.m[14] = lz;
  53413. this.computeAbsoluteTransforms();
  53414. this.markAsDirty();
  53415. };
  53416. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  53417. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53418. if (space == BABYLON.Space.WORLD) {
  53419. var scaleMatrix = Bone._tmpMats[2];
  53420. scaleMatrix.copyFrom(this._scaleMatrix);
  53421. rotMatInv.copyFrom(this.getAbsoluteTransform());
  53422. if (mesh) {
  53423. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  53424. var meshScale = Bone._tmpMats[3];
  53425. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  53426. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  53427. }
  53428. rotMatInv.invert();
  53429. scaleMatrix.m[0] *= this._scalingDeterminant;
  53430. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  53431. }
  53432. else {
  53433. rotMatInv.copyFrom(this.getLocalMatrix());
  53434. rotMatInv.invert();
  53435. var scaleMatrix = Bone._tmpMats[2];
  53436. scaleMatrix.copyFrom(this._scaleMatrix);
  53437. if (this._parent) {
  53438. var pscaleMatrix = Bone._tmpMats[3];
  53439. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  53440. pscaleMatrix.invert();
  53441. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  53442. }
  53443. else {
  53444. scaleMatrix.m[0] *= this._scalingDeterminant;
  53445. }
  53446. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  53447. }
  53448. };
  53449. /**
  53450. * Get the scale of the bone
  53451. * @returns the scale of the bone
  53452. */
  53453. Bone.prototype.getScale = function () {
  53454. return this._scaleVector.clone();
  53455. };
  53456. /**
  53457. * Copy the scale of the bone to a vector3.
  53458. * @param result The vector3 to copy the scale to
  53459. */
  53460. Bone.prototype.getScaleToRef = function (result) {
  53461. result.copyFrom(this._scaleVector);
  53462. };
  53463. /**
  53464. * Get the position of the bone in local or world space.
  53465. * @param space The space that the returned position is in.
  53466. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53467. * @returns The position of the bone
  53468. */
  53469. Bone.prototype.getPosition = function (space, mesh) {
  53470. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53471. var pos = BABYLON.Vector3.Zero();
  53472. this.getPositionToRef(space, mesh, pos);
  53473. return pos;
  53474. };
  53475. /**
  53476. * Copy the position of the bone to a vector3 in local or world space.
  53477. * @param space The space that the returned position is in.
  53478. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53479. * @param result The vector3 to copy the position to.
  53480. */
  53481. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  53482. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53483. if (space == BABYLON.Space.LOCAL) {
  53484. var lm = this.getLocalMatrix();
  53485. result.x = lm.m[12];
  53486. result.y = lm.m[13];
  53487. result.z = lm.m[14];
  53488. }
  53489. else {
  53490. var wm;
  53491. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53492. if (mesh) {
  53493. wm = mesh.getWorldMatrix();
  53494. }
  53495. this._skeleton.computeAbsoluteTransforms();
  53496. var tmat = Bone._tmpMats[0];
  53497. if (mesh) {
  53498. tmat.copyFrom(this.getAbsoluteTransform());
  53499. tmat.multiplyToRef(wm, tmat);
  53500. }
  53501. else {
  53502. tmat = this.getAbsoluteTransform();
  53503. }
  53504. result.x = tmat.m[12];
  53505. result.y = tmat.m[13];
  53506. result.z = tmat.m[14];
  53507. }
  53508. };
  53509. /**
  53510. * Get the absolute position of the bone (world space).
  53511. * @param mesh The mesh that this bone is attached to.
  53512. * @returns The absolute position of the bone
  53513. */
  53514. Bone.prototype.getAbsolutePosition = function (mesh) {
  53515. var pos = BABYLON.Vector3.Zero();
  53516. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  53517. return pos;
  53518. };
  53519. /**
  53520. * Copy the absolute position of the bone (world space) to the result param.
  53521. * @param mesh The mesh that this bone is attached to.
  53522. * @param result The vector3 to copy the absolute position to.
  53523. */
  53524. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  53525. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  53526. };
  53527. /**
  53528. * Compute the absolute transforms of this bone and its children.
  53529. */
  53530. Bone.prototype.computeAbsoluteTransforms = function () {
  53531. if (this._parent) {
  53532. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  53533. }
  53534. else {
  53535. this._absoluteTransform.copyFrom(this._localMatrix);
  53536. var poseMatrix = this._skeleton.getPoseMatrix();
  53537. if (poseMatrix) {
  53538. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  53539. }
  53540. }
  53541. var children = this.children;
  53542. var len = children.length;
  53543. for (var i = 0; i < len; i++) {
  53544. children[i].computeAbsoluteTransforms();
  53545. }
  53546. };
  53547. Bone.prototype._syncScaleVector = function () {
  53548. var lm = this.getLocalMatrix();
  53549. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  53550. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  53551. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  53552. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  53553. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  53554. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  53555. this._scaleVector.x = xs * Math.sqrt(xsq);
  53556. this._scaleVector.y = ys * Math.sqrt(ysq);
  53557. this._scaleVector.z = zs * Math.sqrt(zsq);
  53558. if (this._parent) {
  53559. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  53560. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  53561. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  53562. }
  53563. 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);
  53564. };
  53565. /**
  53566. * Get the world direction from an axis that is in the local space of the bone.
  53567. * @param localAxis The local direction that is used to compute the world direction.
  53568. * @param mesh The mesh that this bone is attached to.
  53569. * @returns The world direction
  53570. */
  53571. Bone.prototype.getDirection = function (localAxis, mesh) {
  53572. var result = BABYLON.Vector3.Zero();
  53573. this.getDirectionToRef(localAxis, mesh, result);
  53574. return result;
  53575. };
  53576. /**
  53577. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  53578. * @param localAxis The local direction that is used to compute the world direction.
  53579. * @param mesh The mesh that this bone is attached to.
  53580. * @param result The vector3 that the world direction will be copied to.
  53581. */
  53582. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  53583. var wm;
  53584. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53585. if (mesh) {
  53586. wm = mesh.getWorldMatrix();
  53587. }
  53588. this._skeleton.computeAbsoluteTransforms();
  53589. var mat = Bone._tmpMats[0];
  53590. mat.copyFrom(this.getAbsoluteTransform());
  53591. if (mesh) {
  53592. mat.multiplyToRef(wm, mat);
  53593. }
  53594. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  53595. result.normalize();
  53596. };
  53597. /**
  53598. * Get the euler rotation of the bone in local or world space.
  53599. * @param space The space that the rotation should be in.
  53600. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53601. * @returns The euler rotation
  53602. */
  53603. Bone.prototype.getRotation = function (space, mesh) {
  53604. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53605. var result = BABYLON.Vector3.Zero();
  53606. this.getRotationToRef(space, mesh, result);
  53607. return result;
  53608. };
  53609. /**
  53610. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  53611. * @param space The space that the rotation should be in.
  53612. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53613. * @param result The vector3 that the rotation should be copied to.
  53614. */
  53615. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  53616. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53617. var quat = Bone._tmpQuat;
  53618. this.getRotationQuaternionToRef(space, mesh, quat);
  53619. quat.toEulerAnglesToRef(result);
  53620. };
  53621. /**
  53622. * Get the quaternion rotation of the bone in either local or world space.
  53623. * @param space The space that the rotation should be in.
  53624. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53625. * @returns The quaternion rotation
  53626. */
  53627. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  53628. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53629. var result = BABYLON.Quaternion.Identity();
  53630. this.getRotationQuaternionToRef(space, mesh, result);
  53631. return result;
  53632. };
  53633. /**
  53634. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  53635. * @param space The space that the rotation should be in.
  53636. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53637. * @param result The quaternion that the rotation should be copied to.
  53638. */
  53639. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  53640. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53641. if (space == BABYLON.Space.LOCAL) {
  53642. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  53643. }
  53644. else {
  53645. var mat = Bone._tmpMats[0];
  53646. var amat = this.getAbsoluteTransform();
  53647. if (mesh) {
  53648. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  53649. }
  53650. else {
  53651. mat.copyFrom(amat);
  53652. }
  53653. mat.m[0] *= this._scalingDeterminant;
  53654. mat.m[1] *= this._scalingDeterminant;
  53655. mat.m[2] *= this._scalingDeterminant;
  53656. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  53657. }
  53658. };
  53659. /**
  53660. * Get the rotation matrix of the bone in local or world space.
  53661. * @param space The space that the rotation should be in.
  53662. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53663. * @returns The rotation matrix
  53664. */
  53665. Bone.prototype.getRotationMatrix = function (space, mesh) {
  53666. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53667. var result = BABYLON.Matrix.Identity();
  53668. this.getRotationMatrixToRef(space, mesh, result);
  53669. return result;
  53670. };
  53671. /**
  53672. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  53673. * @param space The space that the rotation should be in.
  53674. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53675. * @param result The quaternion that the rotation should be copied to.
  53676. */
  53677. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  53678. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53679. if (space == BABYLON.Space.LOCAL) {
  53680. this.getLocalMatrix().getRotationMatrixToRef(result);
  53681. }
  53682. else {
  53683. var mat = Bone._tmpMats[0];
  53684. var amat = this.getAbsoluteTransform();
  53685. if (mesh) {
  53686. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  53687. }
  53688. else {
  53689. mat.copyFrom(amat);
  53690. }
  53691. mat.m[0] *= this._scalingDeterminant;
  53692. mat.m[1] *= this._scalingDeterminant;
  53693. mat.m[2] *= this._scalingDeterminant;
  53694. mat.getRotationMatrixToRef(result);
  53695. }
  53696. };
  53697. /**
  53698. * Get the world position of a point that is in the local space of the bone.
  53699. * @param position The local position
  53700. * @param mesh The mesh that this bone is attached to.
  53701. * @returns The world position
  53702. */
  53703. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  53704. var result = BABYLON.Vector3.Zero();
  53705. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  53706. return result;
  53707. };
  53708. /**
  53709. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  53710. * @param position The local position
  53711. * @param mesh The mesh that this bone is attached to.
  53712. * @param result The vector3 that the world position should be copied to.
  53713. */
  53714. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  53715. var wm;
  53716. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53717. if (mesh) {
  53718. wm = mesh.getWorldMatrix();
  53719. }
  53720. this._skeleton.computeAbsoluteTransforms();
  53721. var tmat = Bone._tmpMats[0];
  53722. if (mesh) {
  53723. tmat.copyFrom(this.getAbsoluteTransform());
  53724. tmat.multiplyToRef(wm, tmat);
  53725. }
  53726. else {
  53727. tmat = this.getAbsoluteTransform();
  53728. }
  53729. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  53730. };
  53731. /**
  53732. * Get the local position of a point that is in world space.
  53733. * @param position The world position
  53734. * @param mesh The mesh that this bone is attached to.
  53735. * @returns The local position
  53736. */
  53737. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  53738. var result = BABYLON.Vector3.Zero();
  53739. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  53740. return result;
  53741. };
  53742. /**
  53743. * Get the local position of a point that is in world space and copy it to the result param.
  53744. * @param position The world position
  53745. * @param mesh The mesh that this bone is attached to.
  53746. * @param result The vector3 that the local position should be copied to.
  53747. */
  53748. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  53749. var wm;
  53750. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53751. if (mesh) {
  53752. wm = mesh.getWorldMatrix();
  53753. }
  53754. this._skeleton.computeAbsoluteTransforms();
  53755. var tmat = Bone._tmpMats[0];
  53756. tmat.copyFrom(this.getAbsoluteTransform());
  53757. if (mesh) {
  53758. tmat.multiplyToRef(wm, tmat);
  53759. }
  53760. tmat.invert();
  53761. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  53762. };
  53763. return Bone;
  53764. }(BABYLON.Node));
  53765. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  53766. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  53767. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  53768. BABYLON.Bone = Bone;
  53769. })(BABYLON || (BABYLON = {}));
  53770. //# sourceMappingURL=babylon.bone.js.map
  53771. var BABYLON;
  53772. (function (BABYLON) {
  53773. var BoneIKController = (function () {
  53774. function BoneIKController(mesh, bone, options) {
  53775. this.targetPosition = BABYLON.Vector3.Zero();
  53776. this.poleTargetPosition = BABYLON.Vector3.Zero();
  53777. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  53778. this.poleAngle = 0;
  53779. this.slerpAmount = 1;
  53780. this._bone1Quat = BABYLON.Quaternion.Identity();
  53781. this._bone1Mat = BABYLON.Matrix.Identity();
  53782. this._bone2Ang = Math.PI;
  53783. this._maxAngle = Math.PI;
  53784. this._rightHandedSystem = false;
  53785. this._bendAxis = BABYLON.Vector3.Right();
  53786. this._slerping = false;
  53787. this._adjustRoll = 0;
  53788. this._bone2 = bone;
  53789. this._bone1 = bone.getParent();
  53790. this.mesh = mesh;
  53791. var bonePos = bone.getPosition();
  53792. if (bone.getAbsoluteTransform().determinant() > 0) {
  53793. this._rightHandedSystem = true;
  53794. this._bendAxis.x = 0;
  53795. this._bendAxis.y = 0;
  53796. this._bendAxis.z = -1;
  53797. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  53798. this._adjustRoll = Math.PI * .5;
  53799. this._bendAxis.z = 1;
  53800. }
  53801. }
  53802. if (this._bone1.length) {
  53803. var boneScale1 = this._bone1.getScale();
  53804. var boneScale2 = this._bone2.getScale();
  53805. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  53806. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  53807. }
  53808. else if (this._bone1.children[0]) {
  53809. mesh.computeWorldMatrix(true);
  53810. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  53811. var pos2 = this._bone2.getAbsolutePosition(mesh);
  53812. var pos3 = this._bone1.getAbsolutePosition(mesh);
  53813. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  53814. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  53815. }
  53816. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  53817. this.maxAngle = Math.PI;
  53818. if (options) {
  53819. if (options.targetMesh) {
  53820. this.targetMesh = options.targetMesh;
  53821. this.targetMesh.computeWorldMatrix(true);
  53822. }
  53823. if (options.poleTargetMesh) {
  53824. this.poleTargetMesh = options.poleTargetMesh;
  53825. this.poleTargetMesh.computeWorldMatrix(true);
  53826. }
  53827. else if (options.poleTargetBone) {
  53828. this.poleTargetBone = options.poleTargetBone;
  53829. }
  53830. else if (this._bone1.getParent()) {
  53831. this.poleTargetBone = this._bone1.getParent();
  53832. }
  53833. if (options.poleTargetLocalOffset) {
  53834. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  53835. }
  53836. if (options.poleAngle) {
  53837. this.poleAngle = options.poleAngle;
  53838. }
  53839. if (options.bendAxis) {
  53840. this._bendAxis.copyFrom(options.bendAxis);
  53841. }
  53842. if (options.maxAngle) {
  53843. this.maxAngle = options.maxAngle;
  53844. }
  53845. if (options.slerpAmount) {
  53846. this.slerpAmount = options.slerpAmount;
  53847. }
  53848. }
  53849. }
  53850. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  53851. get: function () {
  53852. return this._maxAngle;
  53853. },
  53854. set: function (value) {
  53855. this._setMaxAngle(value);
  53856. },
  53857. enumerable: true,
  53858. configurable: true
  53859. });
  53860. BoneIKController.prototype._setMaxAngle = function (ang) {
  53861. if (ang < 0) {
  53862. ang = 0;
  53863. }
  53864. if (ang > Math.PI || ang == undefined) {
  53865. ang = Math.PI;
  53866. }
  53867. this._maxAngle = ang;
  53868. var a = this._bone1Length;
  53869. var b = this._bone2Length;
  53870. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  53871. };
  53872. BoneIKController.prototype.update = function () {
  53873. var bone1 = this._bone1;
  53874. var target = this.targetPosition;
  53875. var poleTarget = this.poleTargetPosition;
  53876. var mat1 = BoneIKController._tmpMats[0];
  53877. var mat2 = BoneIKController._tmpMats[1];
  53878. if (this.targetMesh) {
  53879. target.copyFrom(this.targetMesh.getAbsolutePosition());
  53880. }
  53881. if (this.poleTargetBone) {
  53882. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  53883. }
  53884. else if (this.poleTargetMesh) {
  53885. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  53886. }
  53887. var bonePos = BoneIKController._tmpVecs[0];
  53888. var zaxis = BoneIKController._tmpVecs[1];
  53889. var xaxis = BoneIKController._tmpVecs[2];
  53890. var yaxis = BoneIKController._tmpVecs[3];
  53891. var upAxis = BoneIKController._tmpVecs[4];
  53892. var _tmpQuat = BoneIKController._tmpQuat;
  53893. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  53894. poleTarget.subtractToRef(bonePos, upAxis);
  53895. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  53896. upAxis.y = 1;
  53897. }
  53898. else {
  53899. upAxis.normalize();
  53900. }
  53901. target.subtractToRef(bonePos, yaxis);
  53902. yaxis.normalize();
  53903. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  53904. zaxis.normalize();
  53905. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  53906. xaxis.normalize();
  53907. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  53908. var a = this._bone1Length;
  53909. var b = this._bone2Length;
  53910. var c = BABYLON.Vector3.Distance(bonePos, target);
  53911. if (this._maxReach > 0) {
  53912. c = Math.min(this._maxReach, c);
  53913. }
  53914. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  53915. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  53916. if (acosa > 1) {
  53917. acosa = 1;
  53918. }
  53919. if (acosb > 1) {
  53920. acosb = 1;
  53921. }
  53922. if (acosa < -1) {
  53923. acosa = -1;
  53924. }
  53925. if (acosb < -1) {
  53926. acosb = -1;
  53927. }
  53928. var angA = Math.acos(acosa);
  53929. var angB = Math.acos(acosb);
  53930. var angC = -angA - angB;
  53931. if (this._rightHandedSystem) {
  53932. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  53933. mat2.multiplyToRef(mat1, mat1);
  53934. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  53935. mat2.multiplyToRef(mat1, mat1);
  53936. }
  53937. else {
  53938. var _tmpVec = BoneIKController._tmpVecs[5];
  53939. _tmpVec.copyFrom(this._bendAxis);
  53940. _tmpVec.x *= -1;
  53941. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  53942. mat2.multiplyToRef(mat1, mat1);
  53943. }
  53944. if (this.poleAngle) {
  53945. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  53946. mat1.multiplyToRef(mat2, mat1);
  53947. }
  53948. if (this.slerpAmount < 1) {
  53949. if (!this._slerping) {
  53950. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  53951. }
  53952. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  53953. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  53954. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  53955. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  53956. this._slerping = true;
  53957. }
  53958. else {
  53959. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  53960. this._bone1Mat.copyFrom(mat1);
  53961. this._slerping = false;
  53962. }
  53963. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  53964. this._bone2Ang = angC;
  53965. };
  53966. return BoneIKController;
  53967. }());
  53968. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  53969. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  53970. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  53971. BABYLON.BoneIKController = BoneIKController;
  53972. })(BABYLON || (BABYLON = {}));
  53973. //# sourceMappingURL=babylon.boneIKController.js.map
  53974. var BABYLON;
  53975. (function (BABYLON) {
  53976. var BoneLookController = (function () {
  53977. /**
  53978. * Create a BoneLookController
  53979. * @param mesh the mesh that the bone belongs to
  53980. * @param bone the bone that will be looking to the target
  53981. * @param target the target Vector3 to look at
  53982. * @param settings optional settings:
  53983. * - maxYaw: the maximum angle the bone will yaw to
  53984. * - minYaw: the minimum angle the bone will yaw to
  53985. * - maxPitch: the maximum angle the bone will pitch to
  53986. * - minPitch: the minimum angle the bone will yaw to
  53987. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  53988. * - upAxis: the up axis of the coordinate system
  53989. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  53990. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  53991. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  53992. * - adjustYaw: used to make an adjustment to the yaw of the bone
  53993. * - adjustPitch: used to make an adjustment to the pitch of the bone
  53994. * - adjustRoll: used to make an adjustment to the roll of the bone
  53995. **/
  53996. function BoneLookController(mesh, bone, target, options) {
  53997. /**
  53998. * The up axis of the coordinate system that is used when the bone is rotated.
  53999. */
  54000. this.upAxis = BABYLON.Vector3.Up();
  54001. /**
  54002. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  54003. */
  54004. this.upAxisSpace = BABYLON.Space.LOCAL;
  54005. /**
  54006. * Used to make an adjustment to the yaw of the bone.
  54007. */
  54008. this.adjustYaw = 0;
  54009. /**
  54010. * Used to make an adjustment to the pitch of the bone.
  54011. */
  54012. this.adjustPitch = 0;
  54013. /**
  54014. * Used to make an adjustment to the roll of the bone.
  54015. */
  54016. this.adjustRoll = 0;
  54017. /**
  54018. * 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).
  54019. */
  54020. this.slerpAmount = 1;
  54021. this._boneQuat = BABYLON.Quaternion.Identity();
  54022. this._slerping = false;
  54023. this._firstFrameSkipped = false;
  54024. this._fowardAxis = BABYLON.Vector3.Forward();
  54025. this.mesh = mesh;
  54026. this.bone = bone;
  54027. this.target = target;
  54028. if (options) {
  54029. if (options.adjustYaw) {
  54030. this.adjustYaw = options.adjustYaw;
  54031. }
  54032. if (options.adjustPitch) {
  54033. this.adjustPitch = options.adjustPitch;
  54034. }
  54035. if (options.adjustRoll) {
  54036. this.adjustRoll = options.adjustRoll;
  54037. }
  54038. if (options.maxYaw != null) {
  54039. this.maxYaw = options.maxYaw;
  54040. }
  54041. else {
  54042. this.maxYaw = Math.PI;
  54043. }
  54044. if (options.minYaw != null) {
  54045. this.minYaw = options.minYaw;
  54046. }
  54047. else {
  54048. this.minYaw = -Math.PI;
  54049. }
  54050. if (options.maxPitch != null) {
  54051. this.maxPitch = options.maxPitch;
  54052. }
  54053. else {
  54054. this.maxPitch = Math.PI;
  54055. }
  54056. if (options.minPitch != null) {
  54057. this.minPitch = options.minPitch;
  54058. }
  54059. else {
  54060. this.minPitch = -Math.PI;
  54061. }
  54062. if (options.slerpAmount != null) {
  54063. this.slerpAmount = options.slerpAmount;
  54064. }
  54065. if (options.upAxis != null) {
  54066. this.upAxis = options.upAxis;
  54067. }
  54068. if (options.upAxisSpace != null) {
  54069. this.upAxisSpace = options.upAxisSpace;
  54070. }
  54071. if (options.yawAxis != null || options.pitchAxis != null) {
  54072. var newYawAxis = BABYLON.Axis.Y;
  54073. var newPitchAxis = BABYLON.Axis.X;
  54074. if (options.yawAxis != null) {
  54075. newYawAxis = options.yawAxis.clone();
  54076. newYawAxis.normalize();
  54077. }
  54078. if (options.pitchAxis != null) {
  54079. newPitchAxis = options.pitchAxis.clone();
  54080. newPitchAxis.normalize();
  54081. }
  54082. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  54083. this._transformYawPitch = BABYLON.Matrix.Identity();
  54084. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  54085. this._transformYawPitchInv = this._transformYawPitch.clone();
  54086. this._transformYawPitch.invert();
  54087. }
  54088. }
  54089. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  54090. this.upAxisSpace = BABYLON.Space.LOCAL;
  54091. }
  54092. }
  54093. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  54094. /**
  54095. * Get/set the minimum yaw angle that the bone can look to.
  54096. */
  54097. get: function () {
  54098. return this._minYaw;
  54099. },
  54100. set: function (value) {
  54101. this._minYaw = value;
  54102. this._minYawSin = Math.sin(value);
  54103. this._minYawCos = Math.cos(value);
  54104. if (this._maxYaw != null) {
  54105. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  54106. this._yawRange = this._maxYaw - this._minYaw;
  54107. }
  54108. },
  54109. enumerable: true,
  54110. configurable: true
  54111. });
  54112. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  54113. /**
  54114. * Get/set the maximum yaw angle that the bone can look to.
  54115. */
  54116. get: function () {
  54117. return this._maxYaw;
  54118. },
  54119. set: function (value) {
  54120. this._maxYaw = value;
  54121. this._maxYawSin = Math.sin(value);
  54122. this._maxYawCos = Math.cos(value);
  54123. if (this._minYaw != null) {
  54124. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  54125. this._yawRange = this._maxYaw - this._minYaw;
  54126. }
  54127. },
  54128. enumerable: true,
  54129. configurable: true
  54130. });
  54131. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  54132. /**
  54133. * Get/set the minimum pitch angle that the bone can look to.
  54134. */
  54135. get: function () {
  54136. return this._minPitch;
  54137. },
  54138. set: function (value) {
  54139. this._minPitch = value;
  54140. this._minPitchTan = Math.tan(value);
  54141. },
  54142. enumerable: true,
  54143. configurable: true
  54144. });
  54145. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  54146. /**
  54147. * Get/set the maximum pitch angle that the bone can look to.
  54148. */
  54149. get: function () {
  54150. return this._maxPitch;
  54151. },
  54152. set: function (value) {
  54153. this._maxPitch = value;
  54154. this._maxPitchTan = Math.tan(value);
  54155. },
  54156. enumerable: true,
  54157. configurable: true
  54158. });
  54159. /**
  54160. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  54161. */
  54162. BoneLookController.prototype.update = function () {
  54163. //skip the first frame when slerping so that the mesh rotation is correct
  54164. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  54165. this._firstFrameSkipped = true;
  54166. return;
  54167. }
  54168. var bone = this.bone;
  54169. var bonePos = BoneLookController._tmpVecs[0];
  54170. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  54171. var target = this.target;
  54172. var _tmpMat1 = BoneLookController._tmpMats[0];
  54173. var _tmpMat2 = BoneLookController._tmpMats[1];
  54174. var mesh = this.mesh;
  54175. var parentBone = bone.getParent();
  54176. var upAxis = BoneLookController._tmpVecs[1];
  54177. upAxis.copyFrom(this.upAxis);
  54178. if (this.upAxisSpace == BABYLON.Space.BONE) {
  54179. if (this._transformYawPitch) {
  54180. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  54181. }
  54182. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  54183. }
  54184. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  54185. mesh.getDirectionToRef(upAxis, upAxis);
  54186. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  54187. upAxis.normalize();
  54188. }
  54189. }
  54190. var checkYaw = false;
  54191. var checkPitch = false;
  54192. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  54193. checkYaw = true;
  54194. }
  54195. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  54196. checkPitch = true;
  54197. }
  54198. if (checkYaw || checkPitch) {
  54199. var spaceMat = BoneLookController._tmpMats[2];
  54200. var spaceMatInv = BoneLookController._tmpMats[3];
  54201. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  54202. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  54203. }
  54204. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  54205. spaceMat.copyFrom(mesh.getWorldMatrix());
  54206. }
  54207. else {
  54208. var forwardAxis = BoneLookController._tmpVecs[2];
  54209. forwardAxis.copyFrom(this._fowardAxis);
  54210. if (this._transformYawPitch) {
  54211. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  54212. }
  54213. if (parentBone) {
  54214. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  54215. }
  54216. else {
  54217. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  54218. }
  54219. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  54220. rightAxis.normalize();
  54221. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  54222. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  54223. }
  54224. spaceMat.invertToRef(spaceMatInv);
  54225. var xzlen;
  54226. if (checkPitch) {
  54227. var localTarget = BoneLookController._tmpVecs[3];
  54228. target.subtractToRef(bonePos, localTarget);
  54229. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  54230. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  54231. var pitch = Math.atan2(localTarget.y, xzlen);
  54232. var newPitch = pitch;
  54233. if (pitch > this._maxPitch) {
  54234. localTarget.y = this._maxPitchTan * xzlen;
  54235. newPitch = this._maxPitch;
  54236. }
  54237. else if (pitch < this._minPitch) {
  54238. localTarget.y = this._minPitchTan * xzlen;
  54239. newPitch = this._minPitch;
  54240. }
  54241. if (pitch != newPitch) {
  54242. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  54243. localTarget.addInPlace(bonePos);
  54244. target = localTarget;
  54245. }
  54246. }
  54247. if (checkYaw) {
  54248. var localTarget = BoneLookController._tmpVecs[4];
  54249. target.subtractToRef(bonePos, localTarget);
  54250. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  54251. var yaw = Math.atan2(localTarget.x, localTarget.z);
  54252. var newYaw = yaw;
  54253. if (yaw > this._maxYaw || yaw < this._minYaw) {
  54254. if (xzlen == null) {
  54255. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  54256. }
  54257. if (this._yawRange > Math.PI) {
  54258. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  54259. localTarget.z = this._maxYawCos * xzlen;
  54260. localTarget.x = this._maxYawSin * xzlen;
  54261. newYaw = this._maxYaw;
  54262. }
  54263. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  54264. localTarget.z = this._minYawCos * xzlen;
  54265. localTarget.x = this._minYawSin * xzlen;
  54266. newYaw = this._minYaw;
  54267. }
  54268. }
  54269. else {
  54270. if (yaw > this._maxYaw) {
  54271. localTarget.z = this._maxYawCos * xzlen;
  54272. localTarget.x = this._maxYawSin * xzlen;
  54273. newYaw = this._maxYaw;
  54274. }
  54275. else if (yaw < this._minYaw) {
  54276. localTarget.z = this._minYawCos * xzlen;
  54277. localTarget.x = this._minYawSin * xzlen;
  54278. newYaw = this._minYaw;
  54279. }
  54280. }
  54281. }
  54282. if (this._slerping && this._yawRange > Math.PI) {
  54283. //are we going to be crossing into the min/max region?
  54284. var boneFwd = BoneLookController._tmpVecs[8];
  54285. boneFwd.copyFrom(BABYLON.Axis.Z);
  54286. if (this._transformYawPitch) {
  54287. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  54288. }
  54289. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  54290. this._boneQuat.toRotationMatrix(boneRotMat);
  54291. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  54292. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  54293. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  54294. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  54295. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  54296. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  54297. if (angBtwTar > angBtwMidYaw) {
  54298. if (xzlen == null) {
  54299. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  54300. }
  54301. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  54302. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  54303. if (angBtwMin < angBtwMax) {
  54304. newYaw = boneYaw + Math.PI * .75;
  54305. localTarget.z = Math.cos(newYaw) * xzlen;
  54306. localTarget.x = Math.sin(newYaw) * xzlen;
  54307. }
  54308. else {
  54309. newYaw = boneYaw - Math.PI * .75;
  54310. localTarget.z = Math.cos(newYaw) * xzlen;
  54311. localTarget.x = Math.sin(newYaw) * xzlen;
  54312. }
  54313. }
  54314. }
  54315. if (yaw != newYaw) {
  54316. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  54317. localTarget.addInPlace(bonePos);
  54318. target = localTarget;
  54319. }
  54320. }
  54321. }
  54322. var zaxis = BoneLookController._tmpVecs[5];
  54323. var xaxis = BoneLookController._tmpVecs[6];
  54324. var yaxis = BoneLookController._tmpVecs[7];
  54325. var _tmpQuat = BoneLookController._tmpQuat;
  54326. target.subtractToRef(bonePos, zaxis);
  54327. zaxis.normalize();
  54328. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  54329. xaxis.normalize();
  54330. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  54331. yaxis.normalize();
  54332. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  54333. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  54334. return;
  54335. }
  54336. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  54337. return;
  54338. }
  54339. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  54340. return;
  54341. }
  54342. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  54343. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  54344. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  54345. }
  54346. if (this.slerpAmount < 1) {
  54347. if (!this._slerping) {
  54348. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  54349. }
  54350. if (this._transformYawPitch) {
  54351. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  54352. }
  54353. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  54354. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  54355. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  54356. this._slerping = true;
  54357. }
  54358. else {
  54359. if (this._transformYawPitch) {
  54360. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  54361. }
  54362. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  54363. this._slerping = false;
  54364. }
  54365. };
  54366. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  54367. var angDiff = ang2 - ang1;
  54368. angDiff %= Math.PI * 2;
  54369. if (angDiff > Math.PI) {
  54370. angDiff -= Math.PI * 2;
  54371. }
  54372. else if (angDiff < -Math.PI) {
  54373. angDiff += Math.PI * 2;
  54374. }
  54375. return angDiff;
  54376. };
  54377. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  54378. ang1 %= (2 * Math.PI);
  54379. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  54380. ang2 %= (2 * Math.PI);
  54381. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  54382. var ab = 0;
  54383. if (ang1 < ang2) {
  54384. ab = ang2 - ang1;
  54385. }
  54386. else {
  54387. ab = ang1 - ang2;
  54388. }
  54389. if (ab > Math.PI) {
  54390. ab = Math.PI * 2 - ab;
  54391. }
  54392. return ab;
  54393. };
  54394. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  54395. ang %= (2 * Math.PI);
  54396. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  54397. ang1 %= (2 * Math.PI);
  54398. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  54399. ang2 %= (2 * Math.PI);
  54400. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  54401. if (ang1 < ang2) {
  54402. if (ang > ang1 && ang < ang2) {
  54403. return true;
  54404. }
  54405. }
  54406. else {
  54407. if (ang > ang2 && ang < ang1) {
  54408. return true;
  54409. }
  54410. }
  54411. return false;
  54412. };
  54413. return BoneLookController;
  54414. }());
  54415. 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()];
  54416. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  54417. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  54418. BABYLON.BoneLookController = BoneLookController;
  54419. })(BABYLON || (BABYLON = {}));
  54420. //# sourceMappingURL=babylon.boneLookController.js.map
  54421. var BABYLON;
  54422. (function (BABYLON) {
  54423. var Skeleton = (function () {
  54424. function Skeleton(name, id, scene) {
  54425. this.name = name;
  54426. this.id = id;
  54427. this.bones = new Array();
  54428. this.needInitialSkinMatrix = false;
  54429. this._isDirty = true;
  54430. this._meshesWithPoseMatrix = new Array();
  54431. this._identity = BABYLON.Matrix.Identity();
  54432. this._ranges = {};
  54433. this._lastAbsoluteTransformsUpdateId = -1;
  54434. // Events
  54435. /**
  54436. * An event triggered before computing the skeleton's matrices
  54437. * @type {BABYLON.Observable}
  54438. */
  54439. this.onBeforeComputeObservable = new BABYLON.Observable();
  54440. this.bones = [];
  54441. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54442. scene.skeletons.push(this);
  54443. //make sure it will recalculate the matrix next time prepare is called.
  54444. this._isDirty = true;
  54445. }
  54446. // Members
  54447. Skeleton.prototype.getTransformMatrices = function (mesh) {
  54448. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  54449. return mesh._bonesTransformMatrices;
  54450. }
  54451. if (!this._transformMatrices) {
  54452. this.prepare();
  54453. }
  54454. return this._transformMatrices;
  54455. };
  54456. Skeleton.prototype.getScene = function () {
  54457. return this._scene;
  54458. };
  54459. // Methods
  54460. /**
  54461. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  54462. */
  54463. Skeleton.prototype.toString = function (fullDetails) {
  54464. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  54465. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  54466. if (fullDetails) {
  54467. ret += ", Ranges: {";
  54468. var first = true;
  54469. for (var name_1 in this._ranges) {
  54470. if (first) {
  54471. ret += ", ";
  54472. first = false;
  54473. }
  54474. ret += name_1;
  54475. }
  54476. ret += "}";
  54477. }
  54478. return ret;
  54479. };
  54480. /**
  54481. * Get bone's index searching by name
  54482. * @param {string} name is bone's name to search for
  54483. * @return {number} Indice of the bone. Returns -1 if not found
  54484. */
  54485. Skeleton.prototype.getBoneIndexByName = function (name) {
  54486. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  54487. if (this.bones[boneIndex].name === name) {
  54488. return boneIndex;
  54489. }
  54490. }
  54491. return -1;
  54492. };
  54493. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  54494. // check name not already in use
  54495. if (!this._ranges[name]) {
  54496. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  54497. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  54498. if (this.bones[i].animations[0]) {
  54499. this.bones[i].animations[0].createRange(name, from, to);
  54500. }
  54501. }
  54502. }
  54503. };
  54504. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  54505. if (deleteFrames === void 0) { deleteFrames = true; }
  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].deleteRange(name, deleteFrames);
  54509. }
  54510. }
  54511. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  54512. };
  54513. Skeleton.prototype.getAnimationRange = function (name) {
  54514. return this._ranges[name];
  54515. };
  54516. /**
  54517. * Returns as an Array, all AnimationRanges defined on this skeleton
  54518. */
  54519. Skeleton.prototype.getAnimationRanges = function () {
  54520. var animationRanges = [];
  54521. var name;
  54522. var i = 0;
  54523. for (name in this._ranges) {
  54524. animationRanges[i] = this._ranges[name];
  54525. i++;
  54526. }
  54527. return animationRanges;
  54528. };
  54529. /**
  54530. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  54531. */
  54532. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  54533. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  54534. if (this._ranges[name] || !source.getAnimationRange(name)) {
  54535. return false;
  54536. }
  54537. var ret = true;
  54538. var frameOffset = this._getHighestAnimationFrame() + 1;
  54539. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  54540. var boneDict = {};
  54541. var sourceBones = source.bones;
  54542. var nBones;
  54543. var i;
  54544. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  54545. boneDict[sourceBones[i].name] = sourceBones[i];
  54546. }
  54547. if (this.bones.length !== sourceBones.length) {
  54548. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  54549. ret = false;
  54550. }
  54551. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  54552. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  54553. var boneName = this.bones[i].name;
  54554. var sourceBone = boneDict[boneName];
  54555. if (sourceBone) {
  54556. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  54557. }
  54558. else {
  54559. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  54560. ret = false;
  54561. }
  54562. }
  54563. // do not call createAnimationRange(), since it also is done to bones, which was already done
  54564. var range = source.getAnimationRange(name);
  54565. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  54566. return ret;
  54567. };
  54568. Skeleton.prototype.returnToRest = function () {
  54569. for (var index = 0; index < this.bones.length; index++) {
  54570. this.bones[index].returnToRest();
  54571. }
  54572. };
  54573. Skeleton.prototype._getHighestAnimationFrame = function () {
  54574. var ret = 0;
  54575. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  54576. if (this.bones[i].animations[0]) {
  54577. var highest = this.bones[i].animations[0].getHighestFrame();
  54578. if (ret < highest) {
  54579. ret = highest;
  54580. }
  54581. }
  54582. }
  54583. return ret;
  54584. };
  54585. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  54586. var range = this.getAnimationRange(name);
  54587. if (!range) {
  54588. return null;
  54589. }
  54590. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  54591. };
  54592. Skeleton.prototype._markAsDirty = function () {
  54593. this._isDirty = true;
  54594. };
  54595. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  54596. this._meshesWithPoseMatrix.push(mesh);
  54597. };
  54598. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  54599. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  54600. if (index > -1) {
  54601. this._meshesWithPoseMatrix.splice(index, 1);
  54602. }
  54603. };
  54604. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  54605. this.onBeforeComputeObservable.notifyObservers(this);
  54606. for (var index = 0; index < this.bones.length; index++) {
  54607. var bone = this.bones[index];
  54608. var parentBone = bone.getParent();
  54609. if (parentBone) {
  54610. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  54611. }
  54612. else {
  54613. if (initialSkinMatrix) {
  54614. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  54615. }
  54616. else {
  54617. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  54618. }
  54619. }
  54620. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  54621. }
  54622. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  54623. };
  54624. Skeleton.prototype.prepare = function () {
  54625. if (!this._isDirty) {
  54626. return;
  54627. }
  54628. if (this.needInitialSkinMatrix) {
  54629. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  54630. var mesh = this._meshesWithPoseMatrix[index];
  54631. var poseMatrix = mesh.getPoseMatrix();
  54632. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  54633. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  54634. }
  54635. if (this._synchronizedWithMesh !== mesh) {
  54636. this._synchronizedWithMesh = mesh;
  54637. // Prepare bones
  54638. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  54639. var bone = this.bones[boneIndex];
  54640. if (!bone.getParent()) {
  54641. var matrix = bone.getBaseMatrix();
  54642. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  54643. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  54644. }
  54645. }
  54646. }
  54647. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  54648. }
  54649. }
  54650. else {
  54651. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  54652. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  54653. }
  54654. this._computeTransformMatrices(this._transformMatrices, null);
  54655. }
  54656. this._isDirty = false;
  54657. this._scene._activeBones.addCount(this.bones.length, false);
  54658. };
  54659. Skeleton.prototype.getAnimatables = function () {
  54660. if (!this._animatables || this._animatables.length !== this.bones.length) {
  54661. this._animatables = [];
  54662. for (var index = 0; index < this.bones.length; index++) {
  54663. this._animatables.push(this.bones[index]);
  54664. }
  54665. }
  54666. return this._animatables;
  54667. };
  54668. Skeleton.prototype.clone = function (name, id) {
  54669. var result = new Skeleton(name, id || name, this._scene);
  54670. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  54671. for (var index = 0; index < this.bones.length; index++) {
  54672. var source = this.bones[index];
  54673. var parentBone = null;
  54674. if (source.getParent()) {
  54675. var parentIndex = this.bones.indexOf(source.getParent());
  54676. parentBone = result.bones[parentIndex];
  54677. }
  54678. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  54679. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  54680. }
  54681. if (this._ranges) {
  54682. result._ranges = {};
  54683. for (var rangeName in this._ranges) {
  54684. result._ranges[rangeName] = this._ranges[rangeName].clone();
  54685. }
  54686. }
  54687. this._isDirty = true;
  54688. return result;
  54689. };
  54690. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  54691. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  54692. this.bones.forEach(function (bone) {
  54693. bone.animations.forEach(function (animation) {
  54694. animation.enableBlending = true;
  54695. animation.blendingSpeed = blendingSpeed;
  54696. });
  54697. });
  54698. };
  54699. Skeleton.prototype.dispose = function () {
  54700. this._meshesWithPoseMatrix = [];
  54701. // Animations
  54702. this.getScene().stopAnimation(this);
  54703. // Remove from scene
  54704. this.getScene().removeSkeleton(this);
  54705. };
  54706. Skeleton.prototype.serialize = function () {
  54707. var serializationObject = {};
  54708. serializationObject.name = this.name;
  54709. serializationObject.id = this.id;
  54710. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  54711. serializationObject.bones = [];
  54712. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  54713. for (var index = 0; index < this.bones.length; index++) {
  54714. var bone = this.bones[index];
  54715. var serializedBone = {
  54716. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  54717. name: bone.name,
  54718. matrix: bone.getBaseMatrix().toArray(),
  54719. rest: bone.getRestPose().toArray()
  54720. };
  54721. serializationObject.bones.push(serializedBone);
  54722. if (bone.length) {
  54723. serializedBone.length = bone.length;
  54724. }
  54725. if (bone.animations && bone.animations.length > 0) {
  54726. serializedBone.animation = bone.animations[0].serialize();
  54727. }
  54728. serializationObject.ranges = [];
  54729. for (var name in this._ranges) {
  54730. var range = {};
  54731. range.name = name;
  54732. range.from = this._ranges[name].from;
  54733. range.to = this._ranges[name].to;
  54734. serializationObject.ranges.push(range);
  54735. }
  54736. }
  54737. return serializationObject;
  54738. };
  54739. Skeleton.Parse = function (parsedSkeleton, scene) {
  54740. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  54741. if (parsedSkeleton.dimensionsAtRest) {
  54742. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  54743. }
  54744. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  54745. var index;
  54746. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  54747. var parsedBone = parsedSkeleton.bones[index];
  54748. var parentBone = null;
  54749. if (parsedBone.parentBoneIndex > -1) {
  54750. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  54751. }
  54752. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  54753. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  54754. if (parsedBone.length) {
  54755. bone.length = parsedBone.length;
  54756. }
  54757. if (parsedBone.animation) {
  54758. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  54759. }
  54760. }
  54761. // placed after bones, so createAnimationRange can cascade down
  54762. if (parsedSkeleton.ranges) {
  54763. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  54764. var data = parsedSkeleton.ranges[index];
  54765. skeleton.createAnimationRange(data.name, data.from, data.to);
  54766. }
  54767. }
  54768. return skeleton;
  54769. };
  54770. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  54771. if (forceUpdate === void 0) { forceUpdate = false; }
  54772. var renderId = this._scene.getRenderId();
  54773. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  54774. this.bones[0].computeAbsoluteTransforms();
  54775. this._lastAbsoluteTransformsUpdateId = renderId;
  54776. }
  54777. };
  54778. Skeleton.prototype.getPoseMatrix = function () {
  54779. var poseMatrix;
  54780. if (this._meshesWithPoseMatrix.length > 0) {
  54781. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  54782. }
  54783. return poseMatrix;
  54784. };
  54785. return Skeleton;
  54786. }());
  54787. BABYLON.Skeleton = Skeleton;
  54788. })(BABYLON || (BABYLON = {}));
  54789. //# sourceMappingURL=babylon.skeleton.js.map
  54790. var BABYLON;
  54791. (function (BABYLON) {
  54792. var Internals;
  54793. (function (Internals) {
  54794. var FileFaceOrientation = (function () {
  54795. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  54796. this.name = name;
  54797. this.worldAxisForNormal = worldAxisForNormal;
  54798. this.worldAxisForFileX = worldAxisForFileX;
  54799. this.worldAxisForFileY = worldAxisForFileY;
  54800. }
  54801. return FileFaceOrientation;
  54802. }());
  54803. ;
  54804. /**
  54805. * Helper class dealing with the extraction of spherical polynomial dataArray
  54806. * from a cube map.
  54807. */
  54808. var CubeMapToSphericalPolynomialTools = (function () {
  54809. function CubeMapToSphericalPolynomialTools() {
  54810. }
  54811. /**
  54812. * Converts a cubemap to the according Spherical Polynomial data.
  54813. * This extracts the first 3 orders only as they are the only one used in the lighting.
  54814. *
  54815. * @param cubeInfo The Cube map to extract the information from.
  54816. * @return The Spherical Polynomial data.
  54817. */
  54818. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  54819. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  54820. var totalSolidAngle = 0.0;
  54821. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  54822. var du = 2.0 / cubeInfo.size;
  54823. var dv = du;
  54824. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  54825. var minUV = du * 0.5 - 1.0;
  54826. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54827. var fileFace = this.FileFaces[faceIndex];
  54828. var dataArray = cubeInfo[fileFace.name];
  54829. var v = minUV;
  54830. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  54831. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  54832. // Because SP is still linear, so summation is fine in that basis.
  54833. for (var y = 0; y < cubeInfo.size; y++) {
  54834. var u = minUV;
  54835. for (var x = 0; x < cubeInfo.size; x++) {
  54836. // World direction (not normalised)
  54837. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  54838. worldDirection.normalize();
  54839. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  54840. if (1) {
  54841. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  54842. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  54843. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  54844. var color = new BABYLON.Color3(r, g, b);
  54845. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54846. }
  54847. else {
  54848. if (faceIndex == 0) {
  54849. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54850. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54851. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54852. }
  54853. else if (faceIndex == 1) {
  54854. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54855. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54856. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54857. }
  54858. else if (faceIndex == 2) {
  54859. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54860. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54861. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54862. }
  54863. else if (faceIndex == 3) {
  54864. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54865. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54866. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54867. }
  54868. else if (faceIndex == 4) {
  54869. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54870. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54871. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54872. }
  54873. else if (faceIndex == 5) {
  54874. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54875. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54876. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54877. }
  54878. 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]);
  54879. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54880. }
  54881. totalSolidAngle += deltaSolidAngle;
  54882. u += du;
  54883. }
  54884. v += dv;
  54885. }
  54886. }
  54887. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  54888. var correction = correctSolidAngle / totalSolidAngle;
  54889. sphericalHarmonics.scale(correction);
  54890. // Additionally scale by pi -- audit needed
  54891. sphericalHarmonics.scale(1.0 / Math.PI);
  54892. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  54893. };
  54894. return CubeMapToSphericalPolynomialTools;
  54895. }());
  54896. CubeMapToSphericalPolynomialTools.FileFaces = [
  54897. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  54898. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  54899. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  54900. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  54901. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  54902. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  54903. ];
  54904. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  54905. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54906. })(BABYLON || (BABYLON = {}));
  54907. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  54908. var BABYLON;
  54909. (function (BABYLON) {
  54910. var Internals;
  54911. (function (Internals) {
  54912. /**
  54913. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  54914. */
  54915. var PanoramaToCubeMapTools = (function () {
  54916. function PanoramaToCubeMapTools() {
  54917. }
  54918. /**
  54919. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  54920. *
  54921. * @param float32Array The source data.
  54922. * @param inputWidth The width of the input panorama.
  54923. * @param inputhHeight The height of the input panorama.
  54924. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  54925. * @return The cubemap data
  54926. */
  54927. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  54928. if (!float32Array) {
  54929. throw "ConvertPanoramaToCubemap: input cannot be null";
  54930. }
  54931. if (float32Array.length != inputWidth * inputHeight * 3) {
  54932. throw "ConvertPanoramaToCubemap: input size is wrong";
  54933. }
  54934. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  54935. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  54936. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  54937. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  54938. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  54939. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  54940. return {
  54941. front: textureFront,
  54942. back: textureBack,
  54943. left: textureLeft,
  54944. right: textureRight,
  54945. up: textureUp,
  54946. down: textureDown,
  54947. size: size
  54948. };
  54949. };
  54950. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  54951. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  54952. var textureArray = new Float32Array(buffer);
  54953. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  54954. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  54955. var dy = 1 / texSize;
  54956. var fy = 0;
  54957. for (var y = 0; y < texSize; y++) {
  54958. var xv1 = faceData[0];
  54959. var xv2 = faceData[2];
  54960. for (var x = 0; x < texSize; x++) {
  54961. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  54962. v.normalize();
  54963. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  54964. // 3 channels per pixels
  54965. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  54966. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  54967. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  54968. xv1 = xv1.add(rotDX1);
  54969. xv2 = xv2.add(rotDX2);
  54970. }
  54971. fy += dy;
  54972. }
  54973. return textureArray;
  54974. };
  54975. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  54976. var theta = Math.atan2(vDir.z, vDir.x);
  54977. var phi = Math.acos(vDir.y);
  54978. while (theta < -Math.PI)
  54979. theta += 2 * Math.PI;
  54980. while (theta > Math.PI)
  54981. theta -= 2 * Math.PI;
  54982. var dx = theta / Math.PI;
  54983. var dy = phi / Math.PI;
  54984. // recenter.
  54985. dx = dx * 0.5 + 0.5;
  54986. var px = Math.round(dx * inputWidth);
  54987. if (px < 0)
  54988. px = 0;
  54989. else if (px >= inputWidth)
  54990. px = inputWidth - 1;
  54991. var py = Math.round(dy * inputHeight);
  54992. if (py < 0)
  54993. py = 0;
  54994. else if (py >= inputHeight)
  54995. py = inputHeight - 1;
  54996. var inputY = (inputHeight - py - 1);
  54997. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  54998. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  54999. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  55000. return {
  55001. r: r,
  55002. g: g,
  55003. b: b
  55004. };
  55005. };
  55006. return PanoramaToCubeMapTools;
  55007. }());
  55008. PanoramaToCubeMapTools.FACE_FRONT = [
  55009. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55010. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55011. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55012. new BABYLON.Vector3(1.0, 1.0, -1.0)
  55013. ];
  55014. PanoramaToCubeMapTools.FACE_BACK = [
  55015. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55016. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55017. new BABYLON.Vector3(1.0, 1.0, 1.0),
  55018. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  55019. ];
  55020. PanoramaToCubeMapTools.FACE_RIGHT = [
  55021. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55022. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55023. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55024. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55025. ];
  55026. PanoramaToCubeMapTools.FACE_LEFT = [
  55027. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55028. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55029. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55030. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  55031. ];
  55032. PanoramaToCubeMapTools.FACE_DOWN = [
  55033. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55034. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55035. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55036. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55037. ];
  55038. PanoramaToCubeMapTools.FACE_UP = [
  55039. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55040. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55041. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55042. new BABYLON.Vector3(1.0, -1.0, -1.0)
  55043. ];
  55044. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  55045. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55046. })(BABYLON || (BABYLON = {}));
  55047. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  55048. var BABYLON;
  55049. (function (BABYLON) {
  55050. var Internals;
  55051. (function (Internals) {
  55052. ;
  55053. /**
  55054. * This groups tools to convert HDR texture to native colors array.
  55055. */
  55056. var HDRTools = (function () {
  55057. function HDRTools() {
  55058. }
  55059. HDRTools.Ldexp = function (mantissa, exponent) {
  55060. if (exponent > 1023) {
  55061. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  55062. }
  55063. if (exponent < -1074) {
  55064. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  55065. }
  55066. return mantissa * Math.pow(2, exponent);
  55067. };
  55068. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  55069. if (exponent > 0) {
  55070. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  55071. float32array[index + 0] = red * exponent;
  55072. float32array[index + 1] = green * exponent;
  55073. float32array[index + 2] = blue * exponent;
  55074. }
  55075. else {
  55076. float32array[index + 0] = 0;
  55077. float32array[index + 1] = 0;
  55078. float32array[index + 2] = 0;
  55079. }
  55080. };
  55081. HDRTools.readStringLine = function (uint8array, startIndex) {
  55082. var line = "";
  55083. var character = "";
  55084. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  55085. character = String.fromCharCode(uint8array[i]);
  55086. if (character == "\n") {
  55087. break;
  55088. }
  55089. line += character;
  55090. }
  55091. return line;
  55092. };
  55093. /**
  55094. * Reads header information from an RGBE texture stored in a native array.
  55095. * More information on this format are available here:
  55096. * https://en.wikipedia.org/wiki/RGBE_image_format
  55097. *
  55098. * @param uint8array The binary file stored in native array.
  55099. * @return The header information.
  55100. */
  55101. HDRTools.RGBE_ReadHeader = function (uint8array) {
  55102. var height = 0;
  55103. var width = 0;
  55104. var line = this.readStringLine(uint8array, 0);
  55105. if (line[0] != '#' || line[1] != '?') {
  55106. throw "Bad HDR Format.";
  55107. }
  55108. var endOfHeader = false;
  55109. var findFormat = false;
  55110. var lineIndex = 0;
  55111. do {
  55112. lineIndex += (line.length + 1);
  55113. line = this.readStringLine(uint8array, lineIndex);
  55114. if (line == "FORMAT=32-bit_rle_rgbe") {
  55115. findFormat = true;
  55116. }
  55117. else if (line.length == 0) {
  55118. endOfHeader = true;
  55119. }
  55120. } while (!endOfHeader);
  55121. if (!findFormat) {
  55122. throw "HDR Bad header format, unsupported FORMAT";
  55123. }
  55124. lineIndex += (line.length + 1);
  55125. line = this.readStringLine(uint8array, lineIndex);
  55126. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  55127. var match = sizeRegexp.exec(line);
  55128. // TODO. Support +Y and -X if needed.
  55129. if (match.length < 3) {
  55130. throw "HDR Bad header format, no size";
  55131. }
  55132. width = parseInt(match[2]);
  55133. height = parseInt(match[1]);
  55134. if (width < 8 || width > 0x7fff) {
  55135. throw "HDR Bad header format, unsupported size";
  55136. }
  55137. lineIndex += (line.length + 1);
  55138. return {
  55139. height: height,
  55140. width: width,
  55141. dataPosition: lineIndex
  55142. };
  55143. };
  55144. /**
  55145. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  55146. * This RGBE texture needs to store the information as a panorama.
  55147. *
  55148. * More information on this format are available here:
  55149. * https://en.wikipedia.org/wiki/RGBE_image_format
  55150. *
  55151. * @param buffer The binary file stored in an array buffer.
  55152. * @param size The expected size of the extracted cubemap.
  55153. * @return The Cube Map information.
  55154. */
  55155. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  55156. var uint8array = new Uint8Array(buffer);
  55157. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  55158. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55159. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  55160. return cubeMapData;
  55161. };
  55162. /**
  55163. * Returns the pixels data extracted from an RGBE texture.
  55164. * This pixels will be stored left to right up to down in the R G B order in one array.
  55165. *
  55166. * More information on this format are available here:
  55167. * https://en.wikipedia.org/wiki/RGBE_image_format
  55168. *
  55169. * @param uint8array The binary file stored in an array buffer.
  55170. * @param hdrInfo The header information of the file.
  55171. * @return The pixels data in RGB right to left up to down order.
  55172. */
  55173. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  55174. // Keep for multi format supports.
  55175. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55176. };
  55177. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  55178. var num_scanlines = hdrInfo.height;
  55179. var scanline_width = hdrInfo.width;
  55180. var a, b, c, d, count;
  55181. var dataIndex = hdrInfo.dataPosition;
  55182. var index = 0, endIndex = 0, i = 0;
  55183. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  55184. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  55185. // 3 channels of 4 bytes per pixel in float.
  55186. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  55187. var resultArray = new Float32Array(resultBuffer);
  55188. // read in each successive scanline
  55189. while (num_scanlines > 0) {
  55190. a = uint8array[dataIndex++];
  55191. b = uint8array[dataIndex++];
  55192. c = uint8array[dataIndex++];
  55193. d = uint8array[dataIndex++];
  55194. if (a != 2 || b != 2 || (c & 0x80)) {
  55195. // this file is not run length encoded
  55196. throw "HDR Bad header format, not RLE";
  55197. }
  55198. if (((c << 8) | d) != scanline_width) {
  55199. throw "HDR Bad header format, wrong scan line width";
  55200. }
  55201. index = 0;
  55202. // read each of the four channels for the scanline into the buffer
  55203. for (i = 0; i < 4; i++) {
  55204. endIndex = (i + 1) * scanline_width;
  55205. while (index < endIndex) {
  55206. a = uint8array[dataIndex++];
  55207. b = uint8array[dataIndex++];
  55208. if (a > 128) {
  55209. // a run of the same value
  55210. count = a - 128;
  55211. if ((count == 0) || (count > endIndex - index)) {
  55212. throw "HDR Bad Format, bad scanline data (run)";
  55213. }
  55214. while (count-- > 0) {
  55215. scanLineArray[index++] = b;
  55216. }
  55217. }
  55218. else {
  55219. // a non-run
  55220. count = a;
  55221. if ((count == 0) || (count > endIndex - index)) {
  55222. throw "HDR Bad Format, bad scanline data (non-run)";
  55223. }
  55224. scanLineArray[index++] = b;
  55225. if (--count > 0) {
  55226. for (var j = 0; j < count; j++) {
  55227. scanLineArray[index++] = uint8array[dataIndex++];
  55228. }
  55229. }
  55230. }
  55231. }
  55232. }
  55233. // now convert data from buffer into floats
  55234. for (i = 0; i < scanline_width; i++) {
  55235. a = scanLineArray[i];
  55236. b = scanLineArray[i + scanline_width];
  55237. c = scanLineArray[i + 2 * scanline_width];
  55238. d = scanLineArray[i + 3 * scanline_width];
  55239. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  55240. }
  55241. num_scanlines--;
  55242. }
  55243. return resultArray;
  55244. };
  55245. return HDRTools;
  55246. }());
  55247. Internals.HDRTools = HDRTools;
  55248. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55249. })(BABYLON || (BABYLON = {}));
  55250. //# sourceMappingURL=babylon.hdr.js.map
  55251. //_______________________________________________________________
  55252. // Extracted from CubeMapGen:
  55253. // https://code.google.com/archive/p/cubemapgen/
  55254. //
  55255. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55256. //_______________________________________________________________
  55257. var BABYLON;
  55258. (function (BABYLON) {
  55259. var Internals;
  55260. (function (Internals) {
  55261. /**
  55262. * The bounding box information used during the conversion process.
  55263. */
  55264. var CMGBoundinBox = (function () {
  55265. function CMGBoundinBox() {
  55266. this.min = new BABYLON.Vector3(0, 0, 0);
  55267. this.max = new BABYLON.Vector3(0, 0, 0);
  55268. this.clear();
  55269. }
  55270. CMGBoundinBox.prototype.clear = function () {
  55271. this.min.x = CMGBoundinBox.MAX;
  55272. this.min.y = CMGBoundinBox.MAX;
  55273. this.min.z = CMGBoundinBox.MAX;
  55274. this.max.x = CMGBoundinBox.MIN;
  55275. this.max.y = CMGBoundinBox.MIN;
  55276. this.max.z = CMGBoundinBox.MIN;
  55277. };
  55278. CMGBoundinBox.prototype.augment = function (x, y, z) {
  55279. this.min.x = Math.min(this.min.x, x);
  55280. this.min.y = Math.min(this.min.y, y);
  55281. this.min.z = Math.min(this.min.z, z);
  55282. this.max.x = Math.max(this.max.x, x);
  55283. this.max.y = Math.max(this.max.y, y);
  55284. this.max.z = Math.max(this.max.z, z);
  55285. };
  55286. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  55287. this.min.x = Math.max(this.min.x, x);
  55288. this.min.y = Math.max(this.min.y, y);
  55289. this.min.z = Math.max(this.min.z, z);
  55290. };
  55291. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  55292. this.max.x = Math.min(this.max.x, x);
  55293. this.max.y = Math.min(this.max.y, y);
  55294. this.max.z = Math.min(this.max.z, z);
  55295. };
  55296. CMGBoundinBox.prototype.empty = function () {
  55297. if ((this.min.x > this.max.y) ||
  55298. (this.min.y > this.max.y) ||
  55299. (this.min.z > this.max.y)) {
  55300. return true;
  55301. }
  55302. else {
  55303. return false;
  55304. }
  55305. };
  55306. return CMGBoundinBox;
  55307. }());
  55308. CMGBoundinBox.MAX = Number.MAX_VALUE;
  55309. CMGBoundinBox.MIN = Number.MIN_VALUE;
  55310. /**
  55311. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  55312. * required by the glossinees of a material.
  55313. *
  55314. * This only supports the cosine drop power as well as Warp fixup generation method.
  55315. *
  55316. * This is using the process from CubeMapGen described here:
  55317. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55318. */
  55319. var PMREMGenerator = (function () {
  55320. /**
  55321. * Constructor of the generator.
  55322. *
  55323. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  55324. * @param inputSize The size of the cubemap faces
  55325. * @param outputSize The size of the output cubemap faces
  55326. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  55327. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  55328. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  55329. * @param specularPower The max specular level of the desired cubemap
  55330. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  55331. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  55332. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  55333. */
  55334. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  55335. this.input = input;
  55336. this.inputSize = inputSize;
  55337. this.outputSize = outputSize;
  55338. this.maxNumMipLevels = maxNumMipLevels;
  55339. this.numChannels = numChannels;
  55340. this.isFloat = isFloat;
  55341. this.specularPower = specularPower;
  55342. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  55343. this.excludeBase = excludeBase;
  55344. this.fixup = fixup;
  55345. this._outputSurface = [];
  55346. this._numMipLevels = 0;
  55347. }
  55348. /**
  55349. * Launches the filter process and return the result.
  55350. *
  55351. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  55352. */
  55353. PMREMGenerator.prototype.filterCubeMap = function () {
  55354. // Init cubemap processor
  55355. this.init();
  55356. // Filters the cubemap
  55357. this.filterCubeMapMipChain();
  55358. // Returns the filtered mips.
  55359. return this._outputSurface;
  55360. };
  55361. PMREMGenerator.prototype.init = function () {
  55362. var i;
  55363. var j;
  55364. var mipLevelSize;
  55365. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  55366. if (this.maxNumMipLevels == 0) {
  55367. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  55368. }
  55369. //first miplevel size
  55370. mipLevelSize = this.outputSize;
  55371. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  55372. for (j = 0; j < this.maxNumMipLevels; j++) {
  55373. this._outputSurface.length++;
  55374. this._outputSurface[j] = [];
  55375. //Iterate over faces for output images
  55376. for (i = 0; i < 6; i++) {
  55377. this._outputSurface[j].length++;
  55378. // Initializes a new array for the output.
  55379. if (this.isFloat) {
  55380. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55381. }
  55382. else {
  55383. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55384. }
  55385. }
  55386. //next mip level is half size
  55387. mipLevelSize >>= 1;
  55388. this._numMipLevels++;
  55389. //terminate if mip chain becomes too small
  55390. if (mipLevelSize == 0) {
  55391. this.maxNumMipLevels = j;
  55392. return;
  55393. }
  55394. }
  55395. };
  55396. //--------------------------------------------------------------------------------------
  55397. //Cube map filtering and mip chain generation.
  55398. // the cube map filtereing is specified using a number of parameters:
  55399. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  55400. // indicates the region of the hemisphere to filter over for each tap.
  55401. //
  55402. // Note that the top mip level is also a filtered version of the original input images
  55403. // as well in order to create mip chains for diffuse environment illumination.
  55404. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  55405. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  55406. //
  55407. // Then the mip angle used to genreate the next level of the mip chain from the first level
  55408. // is a_InitialMipAngle
  55409. //
  55410. // The angle for the subsequent levels of the mip chain are specified by their parents
  55411. // filtering angle and a per-level scale and bias
  55412. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  55413. //
  55414. //--------------------------------------------------------------------------------------
  55415. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  55416. // First, take count of the lighting model to modify SpecularPower
  55417. // 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;
  55418. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  55419. //Cone angle start (for generating subsequent mip levels)
  55420. var currentSpecularPower = this.specularPower;
  55421. //Build filter lookup tables based on the source miplevel size
  55422. this.precomputeFilterLookupTables(this.inputSize);
  55423. // Note that we need to filter the first level before generating mipmap
  55424. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  55425. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  55426. // TODO : Write a function to copy and scale the base mipmap in output
  55427. // I am just lazy here and just put a high specular power value, and do some if.
  55428. if (this.excludeBase && (levelIndex == 0)) {
  55429. // 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).
  55430. currentSpecularPower = 100000.0;
  55431. }
  55432. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  55433. var srcCubeImage = this.input;
  55434. var dstCubeImage = this._outputSurface[levelIndex];
  55435. var dstSize = this.outputSize >> levelIndex;
  55436. // Compute required angle.
  55437. var angle = this.getBaseFilterAngle(currentSpecularPower);
  55438. // filter cube surfaces
  55439. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  55440. // fix seams
  55441. if (this.fixup) {
  55442. this.fixupCubeEdges(dstCubeImage, dstSize);
  55443. }
  55444. // Decrease the specular power to generate the mipmap chain
  55445. // TODO : Use another method for Exclude (see first comment at start of the function
  55446. if (this.excludeBase && (levelIndex == 0)) {
  55447. currentSpecularPower = this.specularPower;
  55448. }
  55449. currentSpecularPower *= this.cosinePowerDropPerMip;
  55450. }
  55451. };
  55452. //--------------------------------------------------------------------------------------
  55453. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  55454. // It allow to optimize the texel to access base on the specular power.
  55455. //--------------------------------------------------------------------------------------
  55456. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  55457. // We want to find the alpha such that:
  55458. // cos(alpha)^cosinePower = epsilon
  55459. // That's: acos(epsilon^(1/cosinePower))
  55460. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  55461. var angle = 180.0;
  55462. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  55463. angle *= 180.0 / Math.PI; // Convert to degree
  55464. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  55465. return angle;
  55466. };
  55467. //--------------------------------------------------------------------------------------
  55468. //Builds the following lookup tables prior to filtering:
  55469. // -normalizer cube map
  55470. // -tap weight lookup table
  55471. //
  55472. //--------------------------------------------------------------------------------------
  55473. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  55474. var srcTexelAngle;
  55475. var iCubeFace;
  55476. //clear pre-existing normalizer cube map
  55477. this._normCubeMap = [];
  55478. //Normalized vectors per cubeface and per-texel solid angle
  55479. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  55480. };
  55481. //--------------------------------------------------------------------------------------
  55482. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  55483. //
  55484. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  55485. //
  55486. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  55487. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  55488. // below
  55489. //--------------------------------------------------------------------------------------
  55490. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  55491. var iCubeFace;
  55492. var u;
  55493. var v;
  55494. //iterate over cube faces
  55495. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55496. //First three channels for norm cube, and last channel for solid angle
  55497. this._normCubeMap.push(new Float32Array(size * size * 4));
  55498. //fast texture walk, build normalizer cube map
  55499. var facesData = this.input[iCubeFace];
  55500. for (v = 0; v < size; v++) {
  55501. for (u = 0; u < size; u++) {
  55502. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  55503. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  55504. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  55505. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  55506. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  55507. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  55508. }
  55509. }
  55510. }
  55511. };
  55512. //--------------------------------------------------------------------------------------
  55513. // Convert cubemap face texel coordinates and face idx to 3D vector
  55514. // note the U and V coords are integer coords and range from 0 to size-1
  55515. // this routine can be used to generate a normalizer cube map
  55516. //--------------------------------------------------------------------------------------
  55517. // SL BEGIN
  55518. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  55519. var nvcU;
  55520. var nvcV;
  55521. var tempVec;
  55522. // Change from original AMD code
  55523. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55524. // + 0.5f is for texel center addressing
  55525. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  55526. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  55527. // warp fixup
  55528. if (fixup && size > 1) {
  55529. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  55530. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  55531. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  55532. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  55533. }
  55534. // Get current vector
  55535. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  55536. // U contribution
  55537. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55538. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  55539. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  55540. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  55541. // V contribution and Sum
  55542. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55543. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  55544. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  55545. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  55546. //add face axis
  55547. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  55548. PMREMGenerator._vectorTemp.x += faceAxis[0];
  55549. PMREMGenerator._vectorTemp.y += faceAxis[1];
  55550. PMREMGenerator._vectorTemp.z += faceAxis[2];
  55551. //normalize vector
  55552. PMREMGenerator._vectorTemp.normalize();
  55553. return PMREMGenerator._vectorTemp;
  55554. };
  55555. //--------------------------------------------------------------------------------------
  55556. // Convert 3D vector to cubemap face texel coordinates and face idx
  55557. // note the U and V coords are integer coords and range from 0 to size-1
  55558. // this routine can be used to generate a normalizer cube map
  55559. //
  55560. // returns face IDX and texel coords
  55561. //--------------------------------------------------------------------------------------
  55562. // SL BEGIN
  55563. /*
  55564. Mapping Texture Coordinates to Cube Map Faces
  55565. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  55566. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  55567. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  55568. map arrangement in Pixar's RenderMan package.
  55569. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  55570. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  55571. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  55572. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  55573. the major axis direction). The target column in the table below explains how the major axis direction
  55574. maps to the 2D image of a particular cube map target.
  55575. major axis
  55576. direction target sc tc ma
  55577. ---------- --------------------------------- --- --- ---
  55578. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  55579. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  55580. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  55581. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  55582. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  55583. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  55584. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  55585. an updated (s,t) is calculated as follows
  55586. s = ( sc/|ma| + 1 ) / 2
  55587. t = ( tc/|ma| + 1 ) / 2
  55588. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  55589. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  55590. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  55591. */
  55592. // Note this method return U and V in range from 0 to size-1
  55593. // SL END
  55594. // Store the information in vector3 for convenience (faceindex, u, v)
  55595. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  55596. var maxCoord;
  55597. var faceIdx;
  55598. //absolute value 3
  55599. var absX = Math.abs(x);
  55600. var absY = Math.abs(y);
  55601. var absZ = Math.abs(z);
  55602. if (absX >= absY && absX >= absZ) {
  55603. maxCoord = absX;
  55604. if (x >= 0) {
  55605. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  55606. }
  55607. else {
  55608. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55609. }
  55610. }
  55611. else if (absY >= absX && absY >= absZ) {
  55612. maxCoord = absY;
  55613. if (y >= 0) {
  55614. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55615. }
  55616. else {
  55617. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55618. }
  55619. }
  55620. else {
  55621. maxCoord = absZ;
  55622. if (z >= 0) {
  55623. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55624. }
  55625. else {
  55626. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55627. }
  55628. }
  55629. //divide through by max coord so face vector lies on cube face
  55630. var scale = 1 / maxCoord;
  55631. x *= scale;
  55632. y *= scale;
  55633. z *= scale;
  55634. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55635. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  55636. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55637. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  55638. // Modify original AMD code to return value from 0 to Size - 1
  55639. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  55640. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  55641. PMREMGenerator._vectorTemp.x = faceIdx;
  55642. PMREMGenerator._vectorTemp.y = u;
  55643. PMREMGenerator._vectorTemp.z = v;
  55644. return PMREMGenerator._vectorTemp;
  55645. };
  55646. //--------------------------------------------------------------------------------------
  55647. //Original code from Ignacio CastaÒo
  55648. // This formula is from Manne ÷hrstrˆm's thesis.
  55649. // Take two coordiantes in the range [-1, 1] that define a portion of a
  55650. // cube face and return the area of the projection of that portion on the
  55651. // surface of the sphere.
  55652. //--------------------------------------------------------------------------------------
  55653. PMREMGenerator.prototype.areaElement = function (x, y) {
  55654. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  55655. };
  55656. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  55657. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55658. // (+ 0.5f is for texel center addressing)
  55659. u = (2.0 * (u + 0.5) / size) - 1.0;
  55660. v = (2.0 * (v + 0.5) / size) - 1.0;
  55661. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  55662. var invResolution = 1.0 / size;
  55663. // U and V are the -1..1 texture coordinate on the current face.
  55664. // Get projected area for this texel
  55665. var x0 = u - invResolution;
  55666. var y0 = v - invResolution;
  55667. var x1 = u + invResolution;
  55668. var y1 = v + invResolution;
  55669. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  55670. return solidAngle;
  55671. };
  55672. //--------------------------------------------------------------------------------------
  55673. //The key to the speed of these filtering routines is to quickly define a per-face
  55674. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  55675. // Later these pixels are selectively processed based on their dot products to see if
  55676. // they reside within the filtering cone.
  55677. //
  55678. //This is done by computing the smallest per-texel angle to get a conservative estimate
  55679. // of the number of texels needed to be covered in width and height order to filter the
  55680. // region. the bounding box for the center taps face is defined first, and if the
  55681. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  55682. // defined next
  55683. //--------------------------------------------------------------------------------------
  55684. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  55685. // note that pixels within these regions may be rejected
  55686. // based on the anlge
  55687. var iCubeFace;
  55688. var u;
  55689. var v;
  55690. // bounding box per face to specify region to process
  55691. var filterExtents = [];
  55692. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55693. filterExtents.push(new CMGBoundinBox());
  55694. }
  55695. // min angle a src texel can cover (in degrees)
  55696. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55697. // angle about center tap to define filter cone
  55698. // filter angle is 1/2 the cone angle
  55699. var filterAngle = filterConeAngle / 2.0;
  55700. //ensure filter angle is larger than a texel
  55701. if (filterAngle < srcTexelAngle) {
  55702. filterAngle = srcTexelAngle;
  55703. }
  55704. //ensure filter cone is always smaller than the hemisphere
  55705. if (filterAngle > 90.0) {
  55706. filterAngle = 90.0;
  55707. }
  55708. // the maximum number of texels in 1D the filter cone angle will cover
  55709. // used to determine bounding box size for filter extents
  55710. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55711. // ensure conservative region always covers at least one texel
  55712. if (filterSize < 1) {
  55713. filterSize = 1;
  55714. }
  55715. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55716. // reside within the cone angle
  55717. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55718. // process required faces
  55719. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55720. //iterate over dst cube map face texel
  55721. for (v = 0; v < dstSize; v++) {
  55722. for (u = 0; u < dstSize; u++) {
  55723. //get center tap direction
  55724. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  55725. //clear old per-face filter extents
  55726. this.clearFilterExtents(filterExtents);
  55727. //define per-face filter extents
  55728. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  55729. //perform filtering of src faces using filter extents
  55730. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  55731. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  55732. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  55733. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  55734. }
  55735. }
  55736. }
  55737. };
  55738. //--------------------------------------------------------------------------------------
  55739. //Clear filter extents for the 6 cube map faces
  55740. //--------------------------------------------------------------------------------------
  55741. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  55742. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  55743. filterExtents[iCubeFaces].clear();
  55744. }
  55745. };
  55746. //--------------------------------------------------------------------------------------
  55747. //Define per-face bounding box filter extents
  55748. //
  55749. // These define conservative texel regions in each of the faces the filter can possibly
  55750. // process. When the pixels in the regions are actually processed, the dot product
  55751. // between the tap vector and the center tap vector is used to determine the weight of
  55752. // the tap and whether or not the tap is within the cone.
  55753. //
  55754. //--------------------------------------------------------------------------------------
  55755. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  55756. //neighboring face and bleed over amount, and width of BBOX for
  55757. // left, right, top, and bottom edges of this face
  55758. var bleedOverAmount = [0, 0, 0, 0];
  55759. var bleedOverBBoxMin = [0, 0, 0, 0];
  55760. var bleedOverBBoxMax = [0, 0, 0, 0];
  55761. var neighborFace;
  55762. var neighborEdge;
  55763. var oppositeFaceIdx;
  55764. //get face idx, and u, v info from center tap dir
  55765. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  55766. var faceIdx = result.x;
  55767. var u = result.y;
  55768. var v = result.z;
  55769. //define bbox size within face
  55770. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  55771. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  55772. filterExtents[faceIdx].clampMin(0, 0, 0);
  55773. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  55774. //u and v extent in face corresponding to center tap
  55775. var minU = filterExtents[faceIdx].min.x;
  55776. var minV = filterExtents[faceIdx].min.y;
  55777. var maxU = filterExtents[faceIdx].max.x;
  55778. var maxV = filterExtents[faceIdx].max.y;
  55779. //bleed over amounts for face across u=0 edge (left)
  55780. bleedOverAmount[0] = (bboxSize - u);
  55781. bleedOverBBoxMin[0] = minV;
  55782. bleedOverBBoxMax[0] = maxV;
  55783. //bleed over amounts for face across u=1 edge (right)
  55784. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  55785. bleedOverBBoxMin[1] = minV;
  55786. bleedOverBBoxMax[1] = maxV;
  55787. //bleed over to face across v=0 edge (up)
  55788. bleedOverAmount[2] = (bboxSize - v);
  55789. bleedOverBBoxMin[2] = minU;
  55790. bleedOverBBoxMax[2] = maxU;
  55791. //bleed over to face across v=1 edge (down)
  55792. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  55793. bleedOverBBoxMin[3] = minU;
  55794. bleedOverBBoxMax[3] = maxU;
  55795. //compute bleed over regions in neighboring faces
  55796. for (var i = 0; i < 4; i++) {
  55797. if (bleedOverAmount[i] > 0) {
  55798. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  55799. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  55800. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  55801. // be flipped: the cases are
  55802. // if a left edge mates with a left or bottom edge on the neighbor
  55803. // if a top edge mates with a top or right edge on the neighbor
  55804. // if a right edge mates with a right or top edge on the neighbor
  55805. // if a bottom edge mates with a bottom or left edge on the neighbor
  55806. //Seeing as the edges are enumerated as follows
  55807. // left =0
  55808. // right =1
  55809. // top =2
  55810. // bottom =3
  55811. //
  55812. // so if the edge enums are the same, or the sum of the enums == 3,
  55813. // the bbox needs to be flipped
  55814. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  55815. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  55816. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  55817. }
  55818. //The way the bounding box is extended onto the neighboring face
  55819. // depends on which edge of neighboring face abuts with this one
  55820. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  55821. case PMREMGenerator.CP_EDGE_LEFT:
  55822. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  55823. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55824. break;
  55825. case PMREMGenerator.CP_EDGE_RIGHT:
  55826. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  55827. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55828. break;
  55829. case PMREMGenerator.CP_EDGE_TOP:
  55830. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  55831. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  55832. break;
  55833. case PMREMGenerator.CP_EDGE_BOTTOM:
  55834. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  55835. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  55836. break;
  55837. }
  55838. //clamp filter extents in non-center tap faces to remain within surface
  55839. filterExtents[neighborFace].clampMin(0, 0, 0);
  55840. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  55841. }
  55842. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  55843. // from the center tap face, then process the opposite face entirely for now.
  55844. //Note that the cases in which this happens, what usually happens is that
  55845. // more than one edge bleeds onto the opposite face, and the bounding box
  55846. // encompasses the entire cube map face.
  55847. if (bleedOverAmount[i] > srcSize) {
  55848. //determine opposite face
  55849. switch (faceIdx) {
  55850. case PMREMGenerator.CP_FACE_X_POS:
  55851. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55852. break;
  55853. case PMREMGenerator.CP_FACE_X_NEG:
  55854. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  55855. break;
  55856. case PMREMGenerator.CP_FACE_Y_POS:
  55857. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55858. break;
  55859. case PMREMGenerator.CP_FACE_Y_NEG:
  55860. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55861. break;
  55862. case PMREMGenerator.CP_FACE_Z_POS:
  55863. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55864. break;
  55865. case PMREMGenerator.CP_FACE_Z_NEG:
  55866. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55867. break;
  55868. default:
  55869. break;
  55870. }
  55871. //just encompass entire face for now
  55872. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  55873. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  55874. }
  55875. }
  55876. };
  55877. //--------------------------------------------------------------------------------------
  55878. //ProcessFilterExtents
  55879. // Process bounding box in each cube face
  55880. //
  55881. //--------------------------------------------------------------------------------------
  55882. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  55883. //accumulators are 64-bit floats in order to have the precision needed
  55884. // over a summation of a large number of pixels
  55885. var dstAccum = [0, 0, 0, 0];
  55886. var weightAccum = 0;
  55887. var k = 0;
  55888. var nSrcChannels = this.numChannels;
  55889. // norm cube map and srcCubeMap have same face width
  55890. var faceWidth = srcSize;
  55891. //amount to add to pointer to move to next scanline in images
  55892. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  55893. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  55894. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  55895. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  55896. // iterate over cubefaces
  55897. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  55898. //if bbox is non empty
  55899. if (!filterExtents[iFaceIdx].empty()) {
  55900. var uStart = filterExtents[iFaceIdx].min.x;
  55901. var vStart = filterExtents[iFaceIdx].min.y;
  55902. var uEnd = filterExtents[iFaceIdx].max.x;
  55903. var vEnd = filterExtents[iFaceIdx].max.y;
  55904. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  55905. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  55906. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  55907. for (var v = vStart; v <= vEnd; v++) {
  55908. var normCubeRowWalk = 0;
  55909. var srcCubeRowWalk = 0;
  55910. for (var u = uStart; u <= uEnd; u++) {
  55911. //pointer to direction in cube map associated with texel
  55912. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  55913. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  55914. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  55915. //check dot product to see if texel is within cone
  55916. var tapDotProd = texelVectX * centerTapDir.x +
  55917. texelVectY * centerTapDir.y +
  55918. texelVectZ * centerTapDir.z;
  55919. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  55920. //solid angle stored in 4th channel of normalizer/solid angle cube map
  55921. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  55922. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  55923. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  55924. // so just adding one to specularpower do the trick.
  55925. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  55926. //iterate over channels
  55927. for (k = 0; k < nSrcChannels; k++) {
  55928. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  55929. srcCubeRowWalk++;
  55930. }
  55931. weightAccum += weight; //accumulate weight
  55932. }
  55933. else {
  55934. //step across source pixel
  55935. srcCubeRowWalk += nSrcChannels;
  55936. }
  55937. normCubeRowWalk += 4; // 4 channels per norm cube map.
  55938. }
  55939. startIndexNormCubeMap += normCubePitch;
  55940. startIndexSrcCubeMap += srcCubePitch;
  55941. }
  55942. }
  55943. }
  55944. //divide through by weights if weight is non zero
  55945. if (weightAccum != 0.0) {
  55946. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  55947. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  55948. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  55949. if (this.numChannels > 3) {
  55950. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  55951. }
  55952. }
  55953. else {
  55954. // otherwise sample nearest
  55955. // get face idx and u, v texel coordinate in face
  55956. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  55957. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  55958. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  55959. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  55960. if (this.numChannels > 3) {
  55961. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  55962. }
  55963. }
  55964. return PMREMGenerator._vectorTemp;
  55965. };
  55966. //--------------------------------------------------------------------------------------
  55967. // Fixup cube edges
  55968. //
  55969. // average texels on cube map faces across the edges
  55970. // WARP/BENT Method Only.
  55971. //--------------------------------------------------------------------------------------
  55972. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  55973. var k;
  55974. var j;
  55975. var i;
  55976. var iFace;
  55977. var iCorner = 0;
  55978. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  55979. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  55980. // note that if functionality to filter across the three texels for each corner, then
  55981. //indexed by corner and face idx. the array contains the face the start points belongs to.
  55982. var cornerPtr = [
  55983. [[], [], []],
  55984. [[], [], []],
  55985. [[], [], []],
  55986. [[], [], []],
  55987. [[], [], []],
  55988. [[], [], []],
  55989. [[], [], []],
  55990. [[], [], []]
  55991. ];
  55992. //if there is no fixup, or fixup width = 0, do nothing
  55993. if (cubeMapSize < 1) {
  55994. return;
  55995. }
  55996. //special case 1x1 cubemap, average face colors
  55997. if (cubeMapSize == 1) {
  55998. //iterate over channels
  55999. for (k = 0; k < this.numChannels; k++) {
  56000. var accum = 0.0;
  56001. //iterate over faces to accumulate face colors
  56002. for (iFace = 0; iFace < 6; iFace++) {
  56003. accum += cubeMap[iFace][k];
  56004. }
  56005. //compute average over 6 face colors
  56006. accum /= 6.0;
  56007. //iterate over faces to distribute face colors
  56008. for (iFace = 0; iFace < 6; iFace++) {
  56009. cubeMap[iFace][k] = accum;
  56010. }
  56011. }
  56012. return;
  56013. }
  56014. //iterate over faces to collect list of corner texel pointers
  56015. for (iFace = 0; iFace < 6; iFace++) {
  56016. //the 4 corner pointers for this face
  56017. faceCornerStartIndicies[0] = [iFace, 0];
  56018. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  56019. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  56020. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  56021. //iterate over face corners to collect cube corner pointers
  56022. for (iCorner = 0; iCorner < 4; iCorner++) {
  56023. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  56024. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  56025. cornerNumPtrs[corner]++;
  56026. }
  56027. }
  56028. //iterate over corners to average across corner tap values
  56029. for (iCorner = 0; iCorner < 8; iCorner++) {
  56030. for (k = 0; k < this.numChannels; k++) {
  56031. var cornerTapAccum = 0.0;
  56032. //iterate over corner texels and average results
  56033. for (i = 0; i < 3; i++) {
  56034. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  56035. }
  56036. //divide by 3 to compute average of corner tap values
  56037. cornerTapAccum *= (1.0 / 3.0);
  56038. //iterate over corner texels and average results
  56039. for (i = 0; i < 3; i++) {
  56040. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  56041. }
  56042. }
  56043. }
  56044. //iterate over the twelve edges of the cube to average across edges
  56045. for (i = 0; i < 12; i++) {
  56046. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  56047. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  56048. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  56049. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  56050. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  56051. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  56052. var edgeWalk = 0;
  56053. var neighborEdgeWalk = 0;
  56054. //Determine walking pointers based on edge type
  56055. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  56056. switch (edge) {
  56057. case PMREMGenerator.CP_EDGE_LEFT:
  56058. // no change to faceEdgeStartPtr
  56059. edgeWalk = this.numChannels * cubeMapSize;
  56060. break;
  56061. case PMREMGenerator.CP_EDGE_RIGHT:
  56062. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56063. edgeWalk = this.numChannels * cubeMapSize;
  56064. break;
  56065. case PMREMGenerator.CP_EDGE_TOP:
  56066. // no change to faceEdgeStartPtr
  56067. edgeWalk = this.numChannels;
  56068. break;
  56069. case PMREMGenerator.CP_EDGE_BOTTOM:
  56070. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56071. edgeWalk = this.numChannels;
  56072. break;
  56073. }
  56074. //For certain types of edge abutments, the neighbor edge walk needs to
  56075. // be flipped: the cases are
  56076. // if a left edge mates with a left or bottom edge on the neighbor
  56077. // if a top edge mates with a top or right edge on the neighbor
  56078. // if a right edge mates with a right or top edge on the neighbor
  56079. // if a bottom edge mates with a bottom or left edge on the neighbor
  56080. //Seeing as the edges are enumerated as follows
  56081. // left =0
  56082. // right =1
  56083. // top =2
  56084. // bottom =3
  56085. //
  56086. //If the edge enums are the same, or the sum of the enums == 3,
  56087. // the neighbor edge walk needs to be flipped
  56088. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  56089. switch (neighborEdge) {
  56090. case PMREMGenerator.CP_EDGE_LEFT:
  56091. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  56092. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56093. break;
  56094. case PMREMGenerator.CP_EDGE_RIGHT:
  56095. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56096. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56097. break;
  56098. case PMREMGenerator.CP_EDGE_TOP:
  56099. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56100. neighborEdgeWalk = -this.numChannels;
  56101. break;
  56102. case PMREMGenerator.CP_EDGE_BOTTOM:
  56103. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56104. neighborEdgeWalk = -this.numChannels;
  56105. break;
  56106. }
  56107. }
  56108. else {
  56109. //swapped direction neighbor edge walk
  56110. switch (neighborEdge) {
  56111. case PMREMGenerator.CP_EDGE_LEFT:
  56112. //no change to neighborEdgeStartPtr for this case since it points
  56113. // to the upper left corner already
  56114. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56115. break;
  56116. case PMREMGenerator.CP_EDGE_RIGHT:
  56117. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56118. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56119. break;
  56120. case PMREMGenerator.CP_EDGE_TOP:
  56121. //no change to neighborEdgeStartPtr for this case since it points
  56122. // to the upper left corner already
  56123. neighborEdgeWalk = this.numChannels;
  56124. break;
  56125. case PMREMGenerator.CP_EDGE_BOTTOM:
  56126. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56127. neighborEdgeWalk = this.numChannels;
  56128. break;
  56129. }
  56130. }
  56131. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  56132. //nearby neighborhood
  56133. //step ahead one texel on edge
  56134. edgeStartIndex += edgeWalk;
  56135. neighborEdgeStartIndex += neighborEdgeWalk;
  56136. // note that this loop does not process the corner texels, since they have already been
  56137. // averaged across faces across earlier
  56138. for (j = 1; j < (cubeMapSize - 1); j++) {
  56139. //for each set of taps along edge, average them
  56140. // and rewrite the results into the edges
  56141. for (k = 0; k < this.numChannels; k++) {
  56142. var edgeTap = cubeMap[face][edgeStartIndex + k];
  56143. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  56144. //compute average of tap intensity values
  56145. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  56146. //propagate average of taps to edge taps
  56147. cubeMap[face][edgeStartIndex + k] = avgTap;
  56148. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  56149. }
  56150. edgeStartIndex += edgeWalk;
  56151. neighborEdgeStartIndex += neighborEdgeWalk;
  56152. }
  56153. }
  56154. };
  56155. return PMREMGenerator;
  56156. }());
  56157. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  56158. PMREMGenerator.CP_UDIR = 0;
  56159. PMREMGenerator.CP_VDIR = 1;
  56160. PMREMGenerator.CP_FACEAXIS = 2;
  56161. //used to index cube faces
  56162. PMREMGenerator.CP_FACE_X_POS = 0;
  56163. PMREMGenerator.CP_FACE_X_NEG = 1;
  56164. PMREMGenerator.CP_FACE_Y_POS = 2;
  56165. PMREMGenerator.CP_FACE_Y_NEG = 3;
  56166. PMREMGenerator.CP_FACE_Z_POS = 4;
  56167. PMREMGenerator.CP_FACE_Z_NEG = 5;
  56168. //used to index image edges
  56169. // NOTE.. the actual number corresponding to the edge is important
  56170. // do not change these, or the code will break
  56171. //
  56172. // CP_EDGE_LEFT is u = 0
  56173. // CP_EDGE_RIGHT is u = width-1
  56174. // CP_EDGE_TOP is v = 0
  56175. // CP_EDGE_BOTTOM is v = height-1
  56176. PMREMGenerator.CP_EDGE_LEFT = 0;
  56177. PMREMGenerator.CP_EDGE_RIGHT = 1;
  56178. PMREMGenerator.CP_EDGE_TOP = 2;
  56179. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  56180. //corners of CUBE map (P or N specifys if it corresponds to the
  56181. // positive or negative direction each of X, Y, and Z
  56182. PMREMGenerator.CP_CORNER_NNN = 0;
  56183. PMREMGenerator.CP_CORNER_NNP = 1;
  56184. PMREMGenerator.CP_CORNER_NPN = 2;
  56185. PMREMGenerator.CP_CORNER_NPP = 3;
  56186. PMREMGenerator.CP_CORNER_PNN = 4;
  56187. PMREMGenerator.CP_CORNER_PNP = 5;
  56188. PMREMGenerator.CP_CORNER_PPN = 6;
  56189. PMREMGenerator.CP_CORNER_PPP = 7;
  56190. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  56191. //3x2 matrices that map cube map indexing vectors in 3d
  56192. // (after face selection and divide through by the
  56193. // _ABSOLUTE VALUE_ of the max coord)
  56194. // into NVC space
  56195. //Note this currently assumes the D3D cube face ordering and orientation
  56196. PMREMGenerator._sgFace2DMapping = [
  56197. //XPOS face
  56198. [[0, 0, -1],
  56199. [0, -1, 0],
  56200. [1, 0, 0]],
  56201. //XNEG face
  56202. [[0, 0, 1],
  56203. [0, -1, 0],
  56204. [-1, 0, 0]],
  56205. //YPOS face
  56206. [[1, 0, 0],
  56207. [0, 0, 1],
  56208. [0, 1, 0]],
  56209. //YNEG face
  56210. [[1, 0, 0],
  56211. [0, 0, -1],
  56212. [0, -1, 0]],
  56213. //ZPOS face
  56214. [[1, 0, 0],
  56215. [0, -1, 0],
  56216. [0, 0, 1]],
  56217. //ZNEG face
  56218. [[-1, 0, 0],
  56219. [0, -1, 0],
  56220. [0, 0, -1]],
  56221. ];
  56222. //------------------------------------------------------------------------------
  56223. // D3D cube map face specification
  56224. // mapping from 3D x,y,z cube map lookup coordinates
  56225. // to 2D within face u,v coordinates
  56226. //
  56227. // --------------------> U direction
  56228. // | (within-face texture space)
  56229. // | _____
  56230. // | | |
  56231. // | | +Y |
  56232. // | _____|_____|_____ _____
  56233. // | | | | | |
  56234. // | | -X | +Z | +X | -Z |
  56235. // | |_____|_____|_____|_____|
  56236. // | | |
  56237. // | | -Y |
  56238. // | |_____|
  56239. // |
  56240. // v V direction
  56241. // (within-face texture space)
  56242. //------------------------------------------------------------------------------
  56243. //Information about neighbors and how texture coorrdinates change across faces
  56244. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  56245. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  56246. //Note this currently assumes the D3D cube face ordering and orientation
  56247. PMREMGenerator._sgCubeNgh = [
  56248. //XPOS face
  56249. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56250. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56251. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56252. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  56253. //XNEG face
  56254. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56255. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  56256. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  56257. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  56258. //YPOS face
  56259. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56260. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56261. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56262. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  56263. //YNEG face
  56264. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56265. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56266. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56267. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  56268. //ZPOS face
  56269. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56270. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56271. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56272. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  56273. //ZNEG face
  56274. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56275. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56276. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  56277. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  56278. ];
  56279. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  56280. // this table is used to average over the edges.
  56281. PMREMGenerator._sgCubeEdgeList = [
  56282. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56283. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56284. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56285. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56286. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56287. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56288. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56289. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56290. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  56291. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56292. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56293. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  56294. ];
  56295. //Information about which of the 8 cube corners are correspond to the
  56296. // the 4 corners in each cube face
  56297. // the order is upper left, upper right, lower left, lower right
  56298. PMREMGenerator._sgCubeCornerList = [
  56299. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  56300. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  56301. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  56302. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  56303. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  56304. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  56305. ];
  56306. Internals.PMREMGenerator = PMREMGenerator;
  56307. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56308. })(BABYLON || (BABYLON = {}));
  56309. //# sourceMappingURL=babylon.pmremgenerator.js.map
  56310. var BABYLON;
  56311. (function (BABYLON) {
  56312. /**
  56313. * This represents a texture coming from an HDR input.
  56314. *
  56315. * The only supported format is currently panorama picture stored in RGBE format.
  56316. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56317. */
  56318. var HDRCubeTexture = (function (_super) {
  56319. __extends(HDRCubeTexture, _super);
  56320. /**
  56321. * Instantiates an HDRTexture from the following parameters.
  56322. *
  56323. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56324. * @param scene The scene the texture will be used in
  56325. * @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.
  56326. * @param noMipmap Forces to not generate the mipmap if true
  56327. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56328. * @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)
  56329. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56330. */
  56331. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  56332. if (noMipmap === void 0) { noMipmap = false; }
  56333. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56334. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56335. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56336. if (onLoad === void 0) { onLoad = null; }
  56337. if (onError === void 0) { onError = null; }
  56338. var _this = _super.call(this, scene) || this;
  56339. _this._useInGammaSpace = false;
  56340. _this._generateHarmonics = true;
  56341. _this._isBABYLONPreprocessed = false;
  56342. _this._onLoad = null;
  56343. _this._onError = null;
  56344. /**
  56345. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56346. */
  56347. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56348. /**
  56349. * The spherical polynomial data extracted from the texture.
  56350. */
  56351. _this.sphericalPolynomial = null;
  56352. /**
  56353. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56354. * This is usefull at run time to apply the good shader.
  56355. */
  56356. _this.isPMREM = false;
  56357. _this._isBlocking = true;
  56358. if (!url) {
  56359. return _this;
  56360. }
  56361. _this.name = url;
  56362. _this.url = url;
  56363. _this.hasAlpha = false;
  56364. _this.isCube = true;
  56365. _this._textureMatrix = BABYLON.Matrix.Identity();
  56366. _this._onLoad = onLoad;
  56367. _this._onError = onError;
  56368. if (size) {
  56369. _this._isBABYLONPreprocessed = false;
  56370. _this._noMipmap = noMipmap;
  56371. _this._size = size;
  56372. _this._useInGammaSpace = useInGammaSpace;
  56373. _this._usePMREMGenerator = usePMREMGenerator &&
  56374. scene.getEngine().getCaps().textureLOD &&
  56375. _this.getScene().getEngine().getCaps().textureFloat &&
  56376. !_this._useInGammaSpace;
  56377. }
  56378. else {
  56379. _this._isBABYLONPreprocessed = true;
  56380. _this._noMipmap = false;
  56381. _this._useInGammaSpace = false;
  56382. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56383. _this.getScene().getEngine().getCaps().textureFloat &&
  56384. !_this._useInGammaSpace;
  56385. }
  56386. _this.isPMREM = _this._usePMREMGenerator;
  56387. _this._texture = _this._getFromCache(url, _this._noMipmap);
  56388. if (!_this._texture) {
  56389. if (!scene.useDelayedTextureLoading) {
  56390. _this.loadTexture();
  56391. }
  56392. else {
  56393. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56394. }
  56395. }
  56396. return _this;
  56397. }
  56398. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  56399. /**
  56400. * Gets wether or not the texture is blocking during loading.
  56401. */
  56402. get: function () {
  56403. return this._isBlocking;
  56404. },
  56405. /**
  56406. * Sets wether or not the texture is blocking during loading.
  56407. */
  56408. set: function (value) {
  56409. this._isBlocking = value;
  56410. },
  56411. enumerable: true,
  56412. configurable: true
  56413. });
  56414. /**
  56415. * Occurs when the file is a preprocessed .babylon.hdr file.
  56416. */
  56417. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56418. var _this = this;
  56419. var mipLevels = 0;
  56420. var floatArrayView = null;
  56421. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56422. var mips = [];
  56423. var startIndex = 30;
  56424. for (var level = 0; level < mipLevels; level++) {
  56425. mips.push([]);
  56426. // Fill each pixel of the mip level.
  56427. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56428. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56429. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56430. mips[level].push(faceData);
  56431. startIndex += faceSize;
  56432. }
  56433. }
  56434. return mips;
  56435. } : null;
  56436. var callback = function (buffer) {
  56437. // Create Native Array Views
  56438. var intArrayView = new Int32Array(buffer);
  56439. floatArrayView = new Float32Array(buffer);
  56440. // Fill header.
  56441. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56442. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56443. // Update Texture Information.
  56444. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56445. // Fill polynomial information.
  56446. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56447. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56448. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56449. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56450. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56451. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56452. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56453. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56454. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56455. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56456. // Fill pixel data.
  56457. mipLevels = intArrayView[29]; // Number of mip levels.
  56458. var startIndex = 30;
  56459. var data = [];
  56460. var faceSize = Math.pow(_this._size, 2) * 3;
  56461. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56462. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56463. startIndex += faceSize;
  56464. }
  56465. var results = [];
  56466. var byteArray = null;
  56467. // Push each faces.
  56468. for (var k = 0; k < 6; k++) {
  56469. var dataFace = null;
  56470. // If special cases.
  56471. if (!mipmapGenerator) {
  56472. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  56473. dataFace = data[j];
  56474. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56475. // 3 channels of 1 bytes per pixel in bytes.
  56476. var byteBuffer = new ArrayBuffer(faceSize);
  56477. byteArray = new Uint8Array(byteBuffer);
  56478. }
  56479. for (var i = 0; i < _this._size * _this._size; i++) {
  56480. // Put in gamma space if requested.
  56481. if (_this._useInGammaSpace) {
  56482. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56483. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56484. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56485. }
  56486. // Convert to int texture for fallback.
  56487. if (byteArray) {
  56488. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56489. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56490. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56491. // May use luminance instead if the result is not accurate.
  56492. var max = Math.max(Math.max(r, g), b);
  56493. if (max > 255) {
  56494. var scale = 255 / max;
  56495. r *= scale;
  56496. g *= scale;
  56497. b *= scale;
  56498. }
  56499. byteArray[(i * 3) + 0] = r;
  56500. byteArray[(i * 3) + 1] = g;
  56501. byteArray[(i * 3) + 2] = b;
  56502. }
  56503. }
  56504. }
  56505. else {
  56506. dataFace = data[k];
  56507. }
  56508. // Fill the array accordingly.
  56509. if (byteArray) {
  56510. results.push(byteArray);
  56511. }
  56512. else {
  56513. results.push(dataFace);
  56514. }
  56515. }
  56516. return results;
  56517. };
  56518. 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);
  56519. };
  56520. /**
  56521. * Occurs when the file is raw .hdr file.
  56522. */
  56523. HDRCubeTexture.prototype.loadHDRTexture = function () {
  56524. var _this = this;
  56525. var callback = function (buffer) {
  56526. // Extract the raw linear data.
  56527. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  56528. // Generate harmonics if needed.
  56529. if (_this._generateHarmonics) {
  56530. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  56531. }
  56532. var results = [];
  56533. var byteArray = null;
  56534. // Push each faces.
  56535. for (var j = 0; j < 6; j++) {
  56536. // Create uintarray fallback.
  56537. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56538. // 3 channels of 1 bytes per pixel in bytes.
  56539. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  56540. byteArray = new Uint8Array(byteBuffer);
  56541. }
  56542. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  56543. // If special cases.
  56544. if (_this._useInGammaSpace || byteArray) {
  56545. for (var i = 0; i < _this._size * _this._size; i++) {
  56546. // Put in gamma space if requested.
  56547. if (_this._useInGammaSpace) {
  56548. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56549. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56550. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56551. }
  56552. // Convert to int texture for fallback.
  56553. if (byteArray) {
  56554. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56555. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56556. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56557. // May use luminance instead if the result is not accurate.
  56558. var max = Math.max(Math.max(r, g), b);
  56559. if (max > 255) {
  56560. var scale = 255 / max;
  56561. r *= scale;
  56562. g *= scale;
  56563. b *= scale;
  56564. }
  56565. byteArray[(i * 3) + 0] = r;
  56566. byteArray[(i * 3) + 1] = g;
  56567. byteArray[(i * 3) + 2] = b;
  56568. }
  56569. }
  56570. }
  56571. if (byteArray) {
  56572. results.push(byteArray);
  56573. }
  56574. else {
  56575. results.push(dataFace);
  56576. }
  56577. }
  56578. return results;
  56579. };
  56580. var mipmapGenerator = null;
  56581. if (!this._noMipmap &&
  56582. this._usePMREMGenerator) {
  56583. mipmapGenerator = function (data) {
  56584. // Custom setup of the generator matching with the PBR shader values.
  56585. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  56586. return generator.filterCubeMap();
  56587. };
  56588. }
  56589. 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);
  56590. };
  56591. /**
  56592. * Starts the loading process of the texture.
  56593. */
  56594. HDRCubeTexture.prototype.loadTexture = function () {
  56595. if (this._isBABYLONPreprocessed) {
  56596. this.loadBabylonTexture();
  56597. }
  56598. else {
  56599. this.loadHDRTexture();
  56600. }
  56601. };
  56602. HDRCubeTexture.prototype.clone = function () {
  56603. var size = this._isBABYLONPreprocessed ? null : this._size;
  56604. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56605. // Base texture
  56606. newTexture.level = this.level;
  56607. newTexture.wrapU = this.wrapU;
  56608. newTexture.wrapV = this.wrapV;
  56609. newTexture.coordinatesIndex = this.coordinatesIndex;
  56610. newTexture.coordinatesMode = this.coordinatesMode;
  56611. return newTexture;
  56612. };
  56613. // Methods
  56614. HDRCubeTexture.prototype.delayLoad = function () {
  56615. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56616. return;
  56617. }
  56618. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56619. this._texture = this._getFromCache(this.url, this._noMipmap);
  56620. if (!this._texture) {
  56621. this.loadTexture();
  56622. }
  56623. };
  56624. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56625. return this._textureMatrix;
  56626. };
  56627. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56628. var texture = null;
  56629. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56630. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56631. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  56632. texture.name = parsedTexture.name;
  56633. texture.hasAlpha = parsedTexture.hasAlpha;
  56634. texture.level = parsedTexture.level;
  56635. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56636. texture.isBlocking = parsedTexture.isBlocking;
  56637. }
  56638. return texture;
  56639. };
  56640. HDRCubeTexture.prototype.serialize = function () {
  56641. if (!this.name) {
  56642. return null;
  56643. }
  56644. var serializationObject = {};
  56645. serializationObject.name = this.name;
  56646. serializationObject.hasAlpha = this.hasAlpha;
  56647. serializationObject.isCube = true;
  56648. serializationObject.level = this.level;
  56649. serializationObject.size = this._size;
  56650. serializationObject.coordinatesMode = this.coordinatesMode;
  56651. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56652. serializationObject.generateHarmonics = this._generateHarmonics;
  56653. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56654. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56655. serializationObject.customType = "BABYLON.HDRCubeTexture";
  56656. serializationObject.noMipmap = this._noMipmap;
  56657. serializationObject.isBlocking = this._isBlocking;
  56658. return serializationObject;
  56659. };
  56660. /**
  56661. * Saves as a file the data contained in the texture in a binary format.
  56662. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56663. * as the spherical used in the lighting.
  56664. * @param url The HDR file url.
  56665. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56666. * @param onError Method called if any error happens during download.
  56667. * @return The packed binary data.
  56668. */
  56669. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56670. if (onError === void 0) { onError = null; }
  56671. var callback = function (buffer) {
  56672. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56673. // Returns a URL you can use as a href.
  56674. var objUrl = window.URL.createObjectURL(data);
  56675. // Simulates a link to it and click to dowload.
  56676. var a = document.createElement("a");
  56677. document.body.appendChild(a);
  56678. a.style.display = "none";
  56679. a.href = objUrl;
  56680. a.download = "envmap.babylon.hdr";
  56681. a.click();
  56682. };
  56683. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56684. };
  56685. /**
  56686. * Serializes the data contained in the texture in a binary format.
  56687. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56688. * as the spherical used in the lighting.
  56689. * @param url The HDR file url.
  56690. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56691. * @param onError Method called if any error happens during download.
  56692. * @return The packed binary data.
  56693. */
  56694. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56695. if (onError === void 0) { onError = null; }
  56696. // Needs the url tho create the texture.
  56697. if (!url) {
  56698. return null;
  56699. }
  56700. // Check Power of two size.
  56701. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56702. return null;
  56703. }
  56704. var getDataCallback = function (dataBuffer) {
  56705. // Extract the raw linear data.
  56706. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  56707. // Generate harmonics if needed.
  56708. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  56709. // Generate seamless faces
  56710. var mipGeneratorArray = [];
  56711. // Data are known to be in +X +Y +Z -X -Y -Z
  56712. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56713. mipGeneratorArray.push(cubeData.right); // +X
  56714. mipGeneratorArray.push(cubeData.left); // -X
  56715. mipGeneratorArray.push(cubeData.up); // +Y
  56716. mipGeneratorArray.push(cubeData.down); // -Y
  56717. mipGeneratorArray.push(cubeData.front); // +Z
  56718. mipGeneratorArray.push(cubeData.back); // -Z
  56719. // Custom setup of the generator matching with the PBR shader values.
  56720. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56721. var mippedData = generator.filterCubeMap();
  56722. // Compute required byte length.
  56723. var byteLength = 1 * 4; // Raw Data Version int32.
  56724. byteLength += 4; // CubeMap max mip face size int32.
  56725. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56726. // Add data size.
  56727. byteLength += 4; // Number of mip levels int32.
  56728. for (var level = 0; level < mippedData.length; level++) {
  56729. var mipSize = size >> level;
  56730. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56731. }
  56732. // Prepare binary structure.
  56733. var buffer = new ArrayBuffer(byteLength);
  56734. var intArrayView = new Int32Array(buffer);
  56735. var floatArrayView = new Float32Array(buffer);
  56736. // Fill header.
  56737. intArrayView[0] = 1; // Version 1.
  56738. intArrayView[1] = size; // CubeMap max mip face size.
  56739. // Fill polynomial information.
  56740. sphericalPolynomial.x.toArray(floatArrayView, 2);
  56741. sphericalPolynomial.y.toArray(floatArrayView, 5);
  56742. sphericalPolynomial.z.toArray(floatArrayView, 8);
  56743. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  56744. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  56745. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  56746. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  56747. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  56748. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  56749. // Fill pixel data.
  56750. intArrayView[29] = mippedData.length; // Number of mip levels.
  56751. var startIndex = 30;
  56752. for (var level = 0; level < mippedData.length; level++) {
  56753. // Fill each pixel of the mip level.
  56754. var faceSize = Math.pow(size >> level, 2) * 3;
  56755. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56756. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  56757. startIndex += faceSize;
  56758. }
  56759. }
  56760. // Callback.
  56761. callback(buffer);
  56762. };
  56763. // Download and process.
  56764. BABYLON.Tools.LoadFile(url, function (data) {
  56765. getDataCallback(data);
  56766. }, null, null, true, onError);
  56767. };
  56768. return HDRCubeTexture;
  56769. }(BABYLON.BaseTexture));
  56770. HDRCubeTexture._facesMapping = [
  56771. "right",
  56772. "up",
  56773. "front",
  56774. "left",
  56775. "down",
  56776. "back"
  56777. ];
  56778. BABYLON.HDRCubeTexture = HDRCubeTexture;
  56779. })(BABYLON || (BABYLON = {}));
  56780. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  56781. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  56782. // Huge respect for a such great lib.
  56783. // Earcut license:
  56784. // Copyright (c) 2016, Mapbox
  56785. //
  56786. // Permission to use, copy, modify, and/or distribute this software for any purpose
  56787. // with or without fee is hereby granted, provided that the above copyright notice
  56788. // and this permission notice appear in all copies.
  56789. //
  56790. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  56791. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  56792. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  56793. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  56794. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  56795. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  56796. // THIS SOFTWARE.
  56797. var Earcut;
  56798. (function (Earcut) {
  56799. /**
  56800. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  56801. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  56802. * @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).
  56803. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  56804. */
  56805. function earcut(data, holeIndices, dim) {
  56806. dim = dim || 2;
  56807. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  56808. if (!outerNode)
  56809. return triangles;
  56810. var minX, minY, maxX, maxY, x, y, size;
  56811. if (hasHoles)
  56812. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  56813. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  56814. if (data.length > 80 * dim) {
  56815. minX = maxX = data[0];
  56816. minY = maxY = data[1];
  56817. for (var i = dim; i < outerLen; i += dim) {
  56818. x = data[i];
  56819. y = data[i + 1];
  56820. if (x < minX)
  56821. minX = x;
  56822. if (y < minY)
  56823. minY = y;
  56824. if (x > maxX)
  56825. maxX = x;
  56826. if (y > maxY)
  56827. maxY = y;
  56828. }
  56829. // minX, minY and size are later used to transform coords into integers for z-order calculation
  56830. size = Math.max(maxX - minX, maxY - minY);
  56831. }
  56832. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  56833. return triangles;
  56834. }
  56835. Earcut.earcut = earcut;
  56836. // create a circular doubly linked list from polygon points in the specified winding order
  56837. function linkedList(data, start, end, dim, clockwise) {
  56838. var i, last;
  56839. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  56840. for (i = start; i < end; i += dim)
  56841. last = insertNode(i, data[i], data[i + 1], last);
  56842. }
  56843. else {
  56844. for (i = end - dim; i >= start; i -= dim)
  56845. last = insertNode(i, data[i], data[i + 1], last);
  56846. }
  56847. if (last && equals(last, last.next)) {
  56848. removeNode(last);
  56849. last = last.next;
  56850. }
  56851. return last;
  56852. }
  56853. // eliminate colinear or duplicate points
  56854. function filterPoints(start, end) {
  56855. if (!start)
  56856. return start;
  56857. if (!end)
  56858. end = start;
  56859. var p = start, again;
  56860. do {
  56861. again = false;
  56862. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  56863. removeNode(p);
  56864. p = end = p.prev;
  56865. if (p === p.next)
  56866. return null;
  56867. again = true;
  56868. }
  56869. else {
  56870. p = p.next;
  56871. }
  56872. } while (again || p !== end);
  56873. return end;
  56874. }
  56875. // main ear slicing loop which triangulates a polygon (given as a linked list)
  56876. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  56877. if (!ear)
  56878. return;
  56879. // interlink polygon nodes in z-order
  56880. if (!pass && size)
  56881. indexCurve(ear, minX, minY, size);
  56882. var stop = ear, prev, next;
  56883. // iterate through ears, slicing them one by one
  56884. while (ear.prev !== ear.next) {
  56885. prev = ear.prev;
  56886. next = ear.next;
  56887. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  56888. // cut off the triangle
  56889. triangles.push(prev.i / dim);
  56890. triangles.push(ear.i / dim);
  56891. triangles.push(next.i / dim);
  56892. removeNode(ear);
  56893. // skipping the next vertice leads to less sliver triangles
  56894. ear = next.next;
  56895. stop = next.next;
  56896. continue;
  56897. }
  56898. ear = next;
  56899. // if we looped through the whole remaining polygon and can't find any more ears
  56900. if (ear === stop) {
  56901. // try filtering points and slicing again
  56902. if (!pass) {
  56903. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  56904. // if this didn't work, try curing all small self-intersections locally
  56905. }
  56906. else if (pass === 1) {
  56907. ear = cureLocalIntersections(ear, triangles, dim);
  56908. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  56909. // as a last resort, try splitting the remaining polygon into two
  56910. }
  56911. else if (pass === 2) {
  56912. splitEarcut(ear, triangles, dim, minX, minY, size);
  56913. }
  56914. break;
  56915. }
  56916. }
  56917. }
  56918. // check whether a polygon node forms a valid ear with adjacent nodes
  56919. function isEar(ear) {
  56920. var a = ear.prev, b = ear, c = ear.next;
  56921. if (area(a, b, c) >= 0)
  56922. return false; // reflex, can't be an ear
  56923. // now make sure we don't have other points inside the potential ear
  56924. var p = ear.next.next;
  56925. while (p !== ear.prev) {
  56926. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56927. area(p.prev, p, p.next) >= 0)
  56928. return false;
  56929. p = p.next;
  56930. }
  56931. return true;
  56932. }
  56933. function isEarHashed(ear, minX, minY, size) {
  56934. var a = ear.prev, b = ear, c = ear.next;
  56935. if (area(a, b, c) >= 0)
  56936. return false; // reflex, can't be an ear
  56937. // triangle bbox; min & max are calculated like this for speed
  56938. 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);
  56939. // z-order range for the current triangle bbox;
  56940. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  56941. // first look for points inside the triangle in increasing z-order
  56942. var p = ear.nextZ;
  56943. while (p && p.z <= maxZ) {
  56944. if (p !== ear.prev &&
  56945. p !== ear.next &&
  56946. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56947. area(p.prev, p, p.next) >= 0)
  56948. return false;
  56949. p = p.nextZ;
  56950. }
  56951. // then look for points in decreasing z-order
  56952. p = ear.prevZ;
  56953. while (p && p.z >= minZ) {
  56954. if (p !== ear.prev &&
  56955. p !== ear.next &&
  56956. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56957. area(p.prev, p, p.next) >= 0)
  56958. return false;
  56959. p = p.prevZ;
  56960. }
  56961. return true;
  56962. }
  56963. // go through all polygon nodes and cure small local self-intersections
  56964. function cureLocalIntersections(start, triangles, dim) {
  56965. var p = start;
  56966. do {
  56967. var a = p.prev, b = p.next.next;
  56968. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  56969. triangles.push(a.i / dim);
  56970. triangles.push(p.i / dim);
  56971. triangles.push(b.i / dim);
  56972. // remove two nodes involved
  56973. removeNode(p);
  56974. removeNode(p.next);
  56975. p = start = b;
  56976. }
  56977. p = p.next;
  56978. } while (p !== start);
  56979. return p;
  56980. }
  56981. // try splitting polygon into two and triangulate them independently
  56982. function splitEarcut(start, triangles, dim, minX, minY, size) {
  56983. // look for a valid diagonal that divides the polygon into two
  56984. var a = start;
  56985. do {
  56986. var b = a.next.next;
  56987. while (b !== a.prev) {
  56988. if (a.i !== b.i && isValidDiagonal(a, b)) {
  56989. // split the polygon in two by the diagonal
  56990. var c = splitPolygon(a, b);
  56991. // filter colinear points around the cuts
  56992. a = filterPoints(a, a.next);
  56993. c = filterPoints(c, c.next);
  56994. // run earcut on each half
  56995. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  56996. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  56997. return;
  56998. }
  56999. b = b.next;
  57000. }
  57001. a = a.next;
  57002. } while (a !== start);
  57003. }
  57004. // link every hole into the outer loop, producing a single-ring polygon without holes
  57005. function eliminateHoles(data, holeIndices, outerNode, dim) {
  57006. var queue = [], i, len, start, end, list;
  57007. for (i = 0, len = holeIndices.length; i < len; i++) {
  57008. start = holeIndices[i] * dim;
  57009. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57010. list = linkedList(data, start, end, dim, false);
  57011. if (list === list.next)
  57012. list.steiner = true;
  57013. queue.push(getLeftmost(list));
  57014. }
  57015. queue.sort(compareX);
  57016. // process holes from left to right
  57017. for (i = 0; i < queue.length; i++) {
  57018. eliminateHole(queue[i], outerNode);
  57019. outerNode = filterPoints(outerNode, outerNode.next);
  57020. }
  57021. return outerNode;
  57022. }
  57023. function compareX(a, b) {
  57024. return a.x - b.x;
  57025. }
  57026. // find a bridge between vertices that connects hole with an outer ring and and link it
  57027. function eliminateHole(hole, outerNode) {
  57028. outerNode = findHoleBridge(hole, outerNode);
  57029. if (outerNode) {
  57030. var b = splitPolygon(outerNode, hole);
  57031. filterPoints(b, b.next);
  57032. }
  57033. }
  57034. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  57035. function findHoleBridge(hole, outerNode) {
  57036. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  57037. // find a segment intersected by a ray from the hole's leftmost point to the left;
  57038. // segment's endpoint with lesser x will be potential connection point
  57039. do {
  57040. if (hy <= p.y && hy >= p.next.y) {
  57041. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  57042. if (x <= hx && x > qx) {
  57043. qx = x;
  57044. if (x === hx) {
  57045. if (hy === p.y)
  57046. return p;
  57047. if (hy === p.next.y)
  57048. return p.next;
  57049. }
  57050. m = p.x < p.next.x ? p : p.next;
  57051. }
  57052. }
  57053. p = p.next;
  57054. } while (p !== outerNode);
  57055. if (!m)
  57056. return null;
  57057. if (hx === qx)
  57058. return m.prev; // hole touches outer segment; pick lower endpoint
  57059. // look for points inside the triangle of hole point, segment intersection and endpoint;
  57060. // if there are no points found, we have a valid connection;
  57061. // otherwise choose the point of the minimum angle with the ray as connection point
  57062. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  57063. p = m.next;
  57064. while (p !== stop) {
  57065. if (hx >= p.x &&
  57066. p.x >= mx &&
  57067. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  57068. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  57069. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  57070. m = p;
  57071. tanMin = tan;
  57072. }
  57073. }
  57074. p = p.next;
  57075. }
  57076. return m;
  57077. }
  57078. // interlink polygon nodes in z-order
  57079. function indexCurve(start, minX, minY, size) {
  57080. var p = start;
  57081. do {
  57082. if (p.z === null)
  57083. p.z = zOrder(p.x, p.y, minX, minY, size);
  57084. p.prevZ = p.prev;
  57085. p.nextZ = p.next;
  57086. p = p.next;
  57087. } while (p !== start);
  57088. p.prevZ.nextZ = null;
  57089. p.prevZ = null;
  57090. sortLinked(p);
  57091. }
  57092. // Simon Tatham's linked list merge sort algorithm
  57093. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  57094. function sortLinked(list) {
  57095. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  57096. do {
  57097. p = list;
  57098. list = null;
  57099. tail = null;
  57100. numMerges = 0;
  57101. while (p) {
  57102. numMerges++;
  57103. q = p;
  57104. pSize = 0;
  57105. for (i = 0; i < inSize; i++) {
  57106. pSize++;
  57107. q = q.nextZ;
  57108. if (!q)
  57109. break;
  57110. }
  57111. qSize = inSize;
  57112. while (pSize > 0 || (qSize > 0 && q)) {
  57113. if (pSize === 0) {
  57114. e = q;
  57115. q = q.nextZ;
  57116. qSize--;
  57117. }
  57118. else if (qSize === 0 || !q) {
  57119. e = p;
  57120. p = p.nextZ;
  57121. pSize--;
  57122. }
  57123. else if (p.z <= q.z) {
  57124. e = p;
  57125. p = p.nextZ;
  57126. pSize--;
  57127. }
  57128. else {
  57129. e = q;
  57130. q = q.nextZ;
  57131. qSize--;
  57132. }
  57133. if (tail)
  57134. tail.nextZ = e;
  57135. else
  57136. list = e;
  57137. e.prevZ = tail;
  57138. tail = e;
  57139. }
  57140. p = q;
  57141. }
  57142. tail.nextZ = null;
  57143. inSize *= 2;
  57144. } while (numMerges > 1);
  57145. return list;
  57146. }
  57147. // z-order of a point given coords and size of the data bounding box
  57148. function zOrder(x, y, minX, minY, size) {
  57149. // coords are transformed into non-negative 15-bit integer range
  57150. x = 32767 * (x - minX) / size;
  57151. y = 32767 * (y - minY) / size;
  57152. x = (x | (x << 8)) & 0x00FF00FF;
  57153. x = (x | (x << 4)) & 0x0F0F0F0F;
  57154. x = (x | (x << 2)) & 0x33333333;
  57155. x = (x | (x << 1)) & 0x55555555;
  57156. y = (y | (y << 8)) & 0x00FF00FF;
  57157. y = (y | (y << 4)) & 0x0F0F0F0F;
  57158. y = (y | (y << 2)) & 0x33333333;
  57159. y = (y | (y << 1)) & 0x55555555;
  57160. return x | (y << 1);
  57161. }
  57162. // find the leftmost node of a polygon ring
  57163. function getLeftmost(start) {
  57164. var p = start, leftmost = start;
  57165. do {
  57166. if (p.x < leftmost.x)
  57167. leftmost = p;
  57168. p = p.next;
  57169. } while (p !== start);
  57170. return leftmost;
  57171. }
  57172. // check if a point lies within a convex triangle
  57173. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  57174. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  57175. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  57176. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  57177. }
  57178. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  57179. function isValidDiagonal(a, b) {
  57180. return a.next.i !== b.i &&
  57181. a.prev.i !== b.i &&
  57182. !intersectsPolygon(a, b) &&
  57183. locallyInside(a, b) &&
  57184. locallyInside(b, a) &&
  57185. middleInside(a, b);
  57186. }
  57187. // signed area of a triangle
  57188. function area(p, q, r) {
  57189. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  57190. }
  57191. // check if two points are equal
  57192. function equals(p1, p2) {
  57193. return p1.x === p2.x && p1.y === p2.y;
  57194. }
  57195. // check if two segments intersect
  57196. function intersects(p1, q1, p2, q2) {
  57197. if ((equals(p1, q1) && equals(p2, q2)) ||
  57198. (equals(p1, q2) && equals(p2, q1)))
  57199. return true;
  57200. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  57201. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  57202. }
  57203. // check if a polygon diagonal intersects any polygon segments
  57204. function intersectsPolygon(a, b) {
  57205. var p = a;
  57206. do {
  57207. if (p.i !== a.i &&
  57208. p.next.i !== a.i &&
  57209. p.i !== b.i &&
  57210. p.next.i !== b.i &&
  57211. intersects(p, p.next, a, b))
  57212. return true;
  57213. p = p.next;
  57214. } while (p !== a);
  57215. return false;
  57216. }
  57217. // check if a polygon diagonal is locally inside the polygon
  57218. function locallyInside(a, b) {
  57219. return area(a.prev, a, a.next) < 0
  57220. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  57221. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  57222. }
  57223. // check if the middle point of a polygon diagonal is inside the polygon
  57224. function middleInside(a, b) {
  57225. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  57226. do {
  57227. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  57228. inside = !inside;
  57229. p = p.next;
  57230. } while (p !== a);
  57231. return inside;
  57232. }
  57233. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  57234. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  57235. function splitPolygon(a, b) {
  57236. 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;
  57237. a.next = b;
  57238. b.prev = a;
  57239. a2.next = an;
  57240. an.prev = a2;
  57241. b2.next = a2;
  57242. a2.prev = b2;
  57243. bp.next = b2;
  57244. b2.prev = bp;
  57245. return b2;
  57246. }
  57247. // create a node and optionally link it with previous one (in a circular doubly linked list)
  57248. function insertNode(i, x, y, last) {
  57249. var p = new Node(i, x, y);
  57250. if (!last) {
  57251. p.prev = p;
  57252. p.next = p;
  57253. }
  57254. else {
  57255. p.next = last.next;
  57256. p.prev = last;
  57257. last.next.prev = p;
  57258. last.next = p;
  57259. }
  57260. return p;
  57261. }
  57262. function removeNode(p) {
  57263. p.next.prev = p.prev;
  57264. p.prev.next = p.next;
  57265. if (p.prevZ)
  57266. p.prevZ.nextZ = p.nextZ;
  57267. if (p.nextZ)
  57268. p.nextZ.prevZ = p.prevZ;
  57269. }
  57270. function Node(i, x, y) {
  57271. // vertice index in coordinates array
  57272. this.i = i;
  57273. // vertex coordinates
  57274. this.x = x;
  57275. this.y = y;
  57276. // previous and next vertice nodes in a polygon ring
  57277. this.prev = null;
  57278. this.next = null;
  57279. // z-order curve value
  57280. this.z = null;
  57281. // previous and next nodes in z-order
  57282. this.prevZ = null;
  57283. this.nextZ = null;
  57284. // indicates whether this is a steiner point
  57285. this.steiner = false;
  57286. }
  57287. /**
  57288. * return a percentage difference between the polygon area and its triangulation area;
  57289. * used to verify correctness of triangulation
  57290. */
  57291. function deviation(data, holeIndices, dim, triangles) {
  57292. var hasHoles = holeIndices && holeIndices.length;
  57293. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  57294. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  57295. if (hasHoles) {
  57296. for (var i = 0, len = holeIndices.length; i < len; i++) {
  57297. var start = holeIndices[i] * dim;
  57298. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57299. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  57300. }
  57301. }
  57302. var trianglesArea = 0;
  57303. for (i = 0; i < triangles.length; i += 3) {
  57304. var a = triangles[i] * dim;
  57305. var b = triangles[i + 1] * dim;
  57306. var c = triangles[i + 2] * dim;
  57307. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  57308. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  57309. }
  57310. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  57311. }
  57312. Earcut.deviation = deviation;
  57313. ;
  57314. function signedArea(data, start, end, dim) {
  57315. var sum = 0;
  57316. for (var i = start, j = end - dim; i < end; i += dim) {
  57317. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  57318. j = i;
  57319. }
  57320. return sum;
  57321. }
  57322. /**
  57323. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  57324. */
  57325. function flatten(data) {
  57326. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  57327. for (var i = 0; i < data.length; i++) {
  57328. for (var j = 0; j < data[i].length; j++) {
  57329. for (var d = 0; d < dim; d++)
  57330. result.vertices.push(data[i][j][d]);
  57331. }
  57332. if (i > 0) {
  57333. holeIndex += data[i - 1].length;
  57334. result.holes.push(holeIndex);
  57335. }
  57336. }
  57337. return result;
  57338. }
  57339. Earcut.flatten = flatten;
  57340. ;
  57341. })(Earcut || (Earcut = {}));
  57342. //# sourceMappingURL=babylon.earcut.js.map
  57343. /// <reference path="..\Math\babylon.math.ts" />
  57344. var BABYLON;
  57345. (function (BABYLON) {
  57346. var IndexedVector2 = (function (_super) {
  57347. __extends(IndexedVector2, _super);
  57348. function IndexedVector2(original, index) {
  57349. var _this = _super.call(this, original.x, original.y) || this;
  57350. _this.index = index;
  57351. return _this;
  57352. }
  57353. return IndexedVector2;
  57354. }(BABYLON.Vector2));
  57355. var PolygonPoints = (function () {
  57356. function PolygonPoints() {
  57357. this.elements = new Array();
  57358. }
  57359. PolygonPoints.prototype.add = function (originalPoints) {
  57360. var _this = this;
  57361. var result = new Array();
  57362. originalPoints.forEach(function (point) {
  57363. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  57364. var newPoint = new IndexedVector2(point, _this.elements.length);
  57365. result.push(newPoint);
  57366. _this.elements.push(newPoint);
  57367. }
  57368. });
  57369. return result;
  57370. };
  57371. PolygonPoints.prototype.computeBounds = function () {
  57372. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  57373. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  57374. this.elements.forEach(function (point) {
  57375. // x
  57376. if (point.x < lmin.x) {
  57377. lmin.x = point.x;
  57378. }
  57379. else if (point.x > lmax.x) {
  57380. lmax.x = point.x;
  57381. }
  57382. // y
  57383. if (point.y < lmin.y) {
  57384. lmin.y = point.y;
  57385. }
  57386. else if (point.y > lmax.y) {
  57387. lmax.y = point.y;
  57388. }
  57389. });
  57390. return {
  57391. min: lmin,
  57392. max: lmax,
  57393. width: lmax.x - lmin.x,
  57394. height: lmax.y - lmin.y
  57395. };
  57396. };
  57397. return PolygonPoints;
  57398. }());
  57399. var Polygon = (function () {
  57400. function Polygon() {
  57401. }
  57402. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  57403. return [
  57404. new BABYLON.Vector2(xmin, ymin),
  57405. new BABYLON.Vector2(xmax, ymin),
  57406. new BABYLON.Vector2(xmax, ymax),
  57407. new BABYLON.Vector2(xmin, ymax)
  57408. ];
  57409. };
  57410. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  57411. if (cx === void 0) { cx = 0; }
  57412. if (cy === void 0) { cy = 0; }
  57413. if (numberOfSides === void 0) { numberOfSides = 32; }
  57414. var result = new Array();
  57415. var angle = 0;
  57416. var increment = (Math.PI * 2) / numberOfSides;
  57417. for (var i = 0; i < numberOfSides; i++) {
  57418. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  57419. angle -= increment;
  57420. }
  57421. return result;
  57422. };
  57423. Polygon.Parse = function (input) {
  57424. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  57425. var i, result = [];
  57426. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  57427. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  57428. }
  57429. return result;
  57430. };
  57431. Polygon.StartingAt = function (x, y) {
  57432. return BABYLON.Path2.StartingAt(x, y);
  57433. };
  57434. return Polygon;
  57435. }());
  57436. BABYLON.Polygon = Polygon;
  57437. var PolygonMeshBuilder = (function () {
  57438. function PolygonMeshBuilder(name, contours, scene) {
  57439. this._points = new PolygonPoints();
  57440. this._outlinepoints = new PolygonPoints();
  57441. this._holes = [];
  57442. this._epoints = new Array();
  57443. this._eholes = new Array();
  57444. this._name = name;
  57445. this._scene = scene;
  57446. var points;
  57447. if (contours instanceof BABYLON.Path2) {
  57448. points = contours.getPoints();
  57449. }
  57450. else {
  57451. points = contours;
  57452. }
  57453. this._addToepoint(points);
  57454. this._points.add(points);
  57455. this._outlinepoints.add(points);
  57456. }
  57457. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  57458. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  57459. var p = points_1[_i];
  57460. this._epoints.push(p.x, p.y);
  57461. }
  57462. };
  57463. PolygonMeshBuilder.prototype.addHole = function (hole) {
  57464. this._points.add(hole);
  57465. var holepoints = new PolygonPoints();
  57466. holepoints.add(hole);
  57467. this._holes.push(holepoints);
  57468. this._eholes.push(this._epoints.length / 2);
  57469. this._addToepoint(hole);
  57470. return this;
  57471. };
  57472. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  57473. var _this = this;
  57474. if (updatable === void 0) { updatable = false; }
  57475. var result = new BABYLON.Mesh(this._name, this._scene);
  57476. var normals = [];
  57477. var positions = [];
  57478. var uvs = [];
  57479. var bounds = this._points.computeBounds();
  57480. this._points.elements.forEach(function (p) {
  57481. normals.push(0, 1.0, 0);
  57482. positions.push(p.x, 0, p.y);
  57483. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  57484. });
  57485. var indices = [];
  57486. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  57487. for (var i = 0; i < res.length; i++) {
  57488. indices.push(res[i]);
  57489. }
  57490. if (depth > 0) {
  57491. var positionscount = (positions.length / 3); //get the current pointcount
  57492. this._points.elements.forEach(function (p) {
  57493. normals.push(0, -1.0, 0);
  57494. positions.push(p.x, -depth, p.y);
  57495. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  57496. });
  57497. var totalCount = indices.length;
  57498. for (var i = 0; i < totalCount; i += 3) {
  57499. var i0 = indices[i + 0];
  57500. var i1 = indices[i + 1];
  57501. var i2 = indices[i + 2];
  57502. indices.push(i2 + positionscount);
  57503. indices.push(i1 + positionscount);
  57504. indices.push(i0 + positionscount);
  57505. }
  57506. //Add the sides
  57507. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  57508. this._holes.forEach(function (hole) {
  57509. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  57510. });
  57511. }
  57512. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  57513. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  57514. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  57515. result.setIndices(indices);
  57516. return result;
  57517. };
  57518. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  57519. var StartIndex = positions.length / 3;
  57520. var ulength = 0;
  57521. for (var i = 0; i < points.elements.length; i++) {
  57522. var p = points.elements[i];
  57523. var p1;
  57524. if ((i + 1) > points.elements.length - 1) {
  57525. p1 = points.elements[0];
  57526. }
  57527. else {
  57528. p1 = points.elements[i + 1];
  57529. }
  57530. positions.push(p.x, 0, p.y);
  57531. positions.push(p.x, -depth, p.y);
  57532. positions.push(p1.x, 0, p1.y);
  57533. positions.push(p1.x, -depth, p1.y);
  57534. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  57535. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  57536. var v3 = v2.subtract(v1);
  57537. var v4 = new BABYLON.Vector3(0, 1, 0);
  57538. var vn = BABYLON.Vector3.Cross(v3, v4);
  57539. vn = vn.normalize();
  57540. uvs.push(ulength / bounds.width, 0);
  57541. uvs.push(ulength / bounds.width, 1);
  57542. ulength += v3.length();
  57543. uvs.push((ulength / bounds.width), 0);
  57544. uvs.push((ulength / bounds.width), 1);
  57545. if (!flip) {
  57546. normals.push(-vn.x, -vn.y, -vn.z);
  57547. normals.push(-vn.x, -vn.y, -vn.z);
  57548. normals.push(-vn.x, -vn.y, -vn.z);
  57549. normals.push(-vn.x, -vn.y, -vn.z);
  57550. indices.push(StartIndex);
  57551. indices.push(StartIndex + 1);
  57552. indices.push(StartIndex + 2);
  57553. indices.push(StartIndex + 1);
  57554. indices.push(StartIndex + 3);
  57555. indices.push(StartIndex + 2);
  57556. }
  57557. else {
  57558. normals.push(vn.x, vn.y, vn.z);
  57559. normals.push(vn.x, vn.y, vn.z);
  57560. normals.push(vn.x, vn.y, vn.z);
  57561. normals.push(vn.x, vn.y, vn.z);
  57562. indices.push(StartIndex);
  57563. indices.push(StartIndex + 2);
  57564. indices.push(StartIndex + 1);
  57565. indices.push(StartIndex + 1);
  57566. indices.push(StartIndex + 2);
  57567. indices.push(StartIndex + 3);
  57568. }
  57569. StartIndex += 4;
  57570. }
  57571. ;
  57572. };
  57573. return PolygonMeshBuilder;
  57574. }());
  57575. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  57576. })(BABYLON || (BABYLON = {}));
  57577. //# sourceMappingURL=babylon.polygonMesh.js.map
  57578. var BABYLON;
  57579. (function (BABYLON) {
  57580. // Unique ID when we import meshes from Babylon to CSG
  57581. var currentCSGMeshId = 0;
  57582. // # class Vertex
  57583. // Represents a vertex of a polygon. Use your own vertex class instead of this
  57584. // one to provide additional features like texture coordinates and vertex
  57585. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  57586. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  57587. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  57588. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  57589. // is not used anywhere else.
  57590. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  57591. var Vertex = (function () {
  57592. function Vertex(pos, normal, uv) {
  57593. this.pos = pos;
  57594. this.normal = normal;
  57595. this.uv = uv;
  57596. }
  57597. Vertex.prototype.clone = function () {
  57598. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  57599. };
  57600. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  57601. // orientation of a polygon is flipped.
  57602. Vertex.prototype.flip = function () {
  57603. this.normal = this.normal.scale(-1);
  57604. };
  57605. // Create a new vertex between this vertex and `other` by linearly
  57606. // interpolating all properties using a parameter of `t`. Subclasses should
  57607. // override this to interpolate additional properties.
  57608. Vertex.prototype.interpolate = function (other, t) {
  57609. 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));
  57610. };
  57611. return Vertex;
  57612. }());
  57613. // # class Plane
  57614. // Represents a plane in 3D space.
  57615. var Plane = (function () {
  57616. function Plane(normal, w) {
  57617. this.normal = normal;
  57618. this.w = w;
  57619. }
  57620. Plane.FromPoints = function (a, b, c) {
  57621. var v0 = c.subtract(a);
  57622. var v1 = b.subtract(a);
  57623. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  57624. return null;
  57625. }
  57626. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  57627. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  57628. };
  57629. Plane.prototype.clone = function () {
  57630. return new Plane(this.normal.clone(), this.w);
  57631. };
  57632. Plane.prototype.flip = function () {
  57633. this.normal.scaleInPlace(-1);
  57634. this.w = -this.w;
  57635. };
  57636. // Split `polygon` by this plane if needed, then put the polygon or polygon
  57637. // fragments in the appropriate lists. Coplanar polygons go into either
  57638. // `coplanarFront` or `coplanarBack` depending on their orientation with
  57639. // respect to this plane. Polygons in front or in back of this plane go into
  57640. // either `front` or `back`.
  57641. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  57642. var COPLANAR = 0;
  57643. var FRONT = 1;
  57644. var BACK = 2;
  57645. var SPANNING = 3;
  57646. // Classify each point as well as the entire polygon into one of the above
  57647. // four classes.
  57648. var polygonType = 0;
  57649. var types = [];
  57650. var i;
  57651. var t;
  57652. for (i = 0; i < polygon.vertices.length; i++) {
  57653. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  57654. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  57655. polygonType |= type;
  57656. types.push(type);
  57657. }
  57658. // Put the polygon in the correct list, splitting it when necessary.
  57659. switch (polygonType) {
  57660. case COPLANAR:
  57661. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  57662. break;
  57663. case FRONT:
  57664. front.push(polygon);
  57665. break;
  57666. case BACK:
  57667. back.push(polygon);
  57668. break;
  57669. case SPANNING:
  57670. var f = [], b = [];
  57671. for (i = 0; i < polygon.vertices.length; i++) {
  57672. var j = (i + 1) % polygon.vertices.length;
  57673. var ti = types[i], tj = types[j];
  57674. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  57675. if (ti !== BACK)
  57676. f.push(vi);
  57677. if (ti !== FRONT)
  57678. b.push(ti !== BACK ? vi.clone() : vi);
  57679. if ((ti | tj) === SPANNING) {
  57680. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  57681. var v = vi.interpolate(vj, t);
  57682. f.push(v);
  57683. b.push(v.clone());
  57684. }
  57685. }
  57686. var poly;
  57687. if (f.length >= 3) {
  57688. poly = new Polygon(f, polygon.shared);
  57689. if (poly.plane)
  57690. front.push(poly);
  57691. }
  57692. if (b.length >= 3) {
  57693. poly = new Polygon(b, polygon.shared);
  57694. if (poly.plane)
  57695. back.push(poly);
  57696. }
  57697. break;
  57698. }
  57699. };
  57700. return Plane;
  57701. }());
  57702. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  57703. // point is on the plane.
  57704. Plane.EPSILON = 1e-5;
  57705. // # class Polygon
  57706. // Represents a convex polygon. The vertices used to initialize a polygon must
  57707. // be coplanar and form a convex loop.
  57708. //
  57709. // Each convex polygon has a `shared` property, which is shared between all
  57710. // polygons that are clones of each other or were split from the same polygon.
  57711. // This can be used to define per-polygon properties (such as surface color).
  57712. var Polygon = (function () {
  57713. function Polygon(vertices, shared) {
  57714. this.vertices = vertices;
  57715. this.shared = shared;
  57716. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  57717. }
  57718. Polygon.prototype.clone = function () {
  57719. var vertices = this.vertices.map(function (v) { return v.clone(); });
  57720. return new Polygon(vertices, this.shared);
  57721. };
  57722. Polygon.prototype.flip = function () {
  57723. this.vertices.reverse().map(function (v) { v.flip(); });
  57724. this.plane.flip();
  57725. };
  57726. return Polygon;
  57727. }());
  57728. // # class Node
  57729. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  57730. // by picking a polygon to split along. That polygon (and all other coplanar
  57731. // polygons) are added directly to that node and the other polygons are added to
  57732. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  57733. // no distinction between internal and leaf nodes.
  57734. var Node = (function () {
  57735. function Node(polygons) {
  57736. this.plane = null;
  57737. this.front = null;
  57738. this.back = null;
  57739. this.polygons = [];
  57740. if (polygons) {
  57741. this.build(polygons);
  57742. }
  57743. }
  57744. Node.prototype.clone = function () {
  57745. var node = new Node();
  57746. node.plane = this.plane && this.plane.clone();
  57747. node.front = this.front && this.front.clone();
  57748. node.back = this.back && this.back.clone();
  57749. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  57750. return node;
  57751. };
  57752. // Convert solid space to empty space and empty space to solid space.
  57753. Node.prototype.invert = function () {
  57754. for (var i = 0; i < this.polygons.length; i++) {
  57755. this.polygons[i].flip();
  57756. }
  57757. if (this.plane) {
  57758. this.plane.flip();
  57759. }
  57760. if (this.front) {
  57761. this.front.invert();
  57762. }
  57763. if (this.back) {
  57764. this.back.invert();
  57765. }
  57766. var temp = this.front;
  57767. this.front = this.back;
  57768. this.back = temp;
  57769. };
  57770. // Recursively remove all polygons in `polygons` that are inside this BSP
  57771. // tree.
  57772. Node.prototype.clipPolygons = function (polygons) {
  57773. if (!this.plane)
  57774. return polygons.slice();
  57775. var front = [], back = [];
  57776. for (var i = 0; i < polygons.length; i++) {
  57777. this.plane.splitPolygon(polygons[i], front, back, front, back);
  57778. }
  57779. if (this.front) {
  57780. front = this.front.clipPolygons(front);
  57781. }
  57782. if (this.back) {
  57783. back = this.back.clipPolygons(back);
  57784. }
  57785. else {
  57786. back = [];
  57787. }
  57788. return front.concat(back);
  57789. };
  57790. // Remove all polygons in this BSP tree that are inside the other BSP tree
  57791. // `bsp`.
  57792. Node.prototype.clipTo = function (bsp) {
  57793. this.polygons = bsp.clipPolygons(this.polygons);
  57794. if (this.front)
  57795. this.front.clipTo(bsp);
  57796. if (this.back)
  57797. this.back.clipTo(bsp);
  57798. };
  57799. // Return a list of all polygons in this BSP tree.
  57800. Node.prototype.allPolygons = function () {
  57801. var polygons = this.polygons.slice();
  57802. if (this.front)
  57803. polygons = polygons.concat(this.front.allPolygons());
  57804. if (this.back)
  57805. polygons = polygons.concat(this.back.allPolygons());
  57806. return polygons;
  57807. };
  57808. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  57809. // new polygons are filtered down to the bottom of the tree and become new
  57810. // nodes there. Each set of polygons is partitioned using the first polygon
  57811. // (no heuristic is used to pick a good split).
  57812. Node.prototype.build = function (polygons) {
  57813. if (!polygons.length)
  57814. return;
  57815. if (!this.plane)
  57816. this.plane = polygons[0].plane.clone();
  57817. var front = [], back = [];
  57818. for (var i = 0; i < polygons.length; i++) {
  57819. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  57820. }
  57821. if (front.length) {
  57822. if (!this.front)
  57823. this.front = new Node();
  57824. this.front.build(front);
  57825. }
  57826. if (back.length) {
  57827. if (!this.back)
  57828. this.back = new Node();
  57829. this.back.build(back);
  57830. }
  57831. };
  57832. return Node;
  57833. }());
  57834. var CSG = (function () {
  57835. function CSG() {
  57836. this.polygons = new Array();
  57837. }
  57838. // Convert BABYLON.Mesh to BABYLON.CSG
  57839. CSG.FromMesh = function (mesh) {
  57840. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  57841. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  57842. if (mesh instanceof BABYLON.Mesh) {
  57843. mesh.computeWorldMatrix(true);
  57844. matrix = mesh.getWorldMatrix();
  57845. meshPosition = mesh.position.clone();
  57846. meshRotation = mesh.rotation.clone();
  57847. if (mesh.rotationQuaternion) {
  57848. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  57849. }
  57850. meshScaling = mesh.scaling.clone();
  57851. }
  57852. else {
  57853. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  57854. }
  57855. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57856. var subMeshes = mesh.subMeshes;
  57857. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  57858. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  57859. vertices = [];
  57860. for (var j = 0; j < 3; j++) {
  57861. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  57862. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  57863. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  57864. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  57865. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  57866. vertex = new Vertex(position, normal, uv);
  57867. vertices.push(vertex);
  57868. }
  57869. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  57870. // To handle the case of degenerated triangle
  57871. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  57872. if (polygon.plane)
  57873. polygons.push(polygon);
  57874. }
  57875. }
  57876. var csg = CSG.FromPolygons(polygons);
  57877. csg.matrix = matrix;
  57878. csg.position = meshPosition;
  57879. csg.rotation = meshRotation;
  57880. csg.scaling = meshScaling;
  57881. csg.rotationQuaternion = meshRotationQuaternion;
  57882. currentCSGMeshId++;
  57883. return csg;
  57884. };
  57885. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  57886. CSG.FromPolygons = function (polygons) {
  57887. var csg = new CSG();
  57888. csg.polygons = polygons;
  57889. return csg;
  57890. };
  57891. CSG.prototype.clone = function () {
  57892. var csg = new CSG();
  57893. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  57894. csg.copyTransformAttributes(this);
  57895. return csg;
  57896. };
  57897. CSG.prototype.toPolygons = function () {
  57898. return this.polygons;
  57899. };
  57900. CSG.prototype.union = function (csg) {
  57901. var a = new Node(this.clone().polygons);
  57902. var b = new Node(csg.clone().polygons);
  57903. a.clipTo(b);
  57904. b.clipTo(a);
  57905. b.invert();
  57906. b.clipTo(a);
  57907. b.invert();
  57908. a.build(b.allPolygons());
  57909. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57910. };
  57911. CSG.prototype.unionInPlace = function (csg) {
  57912. var a = new Node(this.polygons);
  57913. var b = new Node(csg.polygons);
  57914. a.clipTo(b);
  57915. b.clipTo(a);
  57916. b.invert();
  57917. b.clipTo(a);
  57918. b.invert();
  57919. a.build(b.allPolygons());
  57920. this.polygons = a.allPolygons();
  57921. };
  57922. CSG.prototype.subtract = function (csg) {
  57923. var a = new Node(this.clone().polygons);
  57924. var b = new Node(csg.clone().polygons);
  57925. a.invert();
  57926. a.clipTo(b);
  57927. b.clipTo(a);
  57928. b.invert();
  57929. b.clipTo(a);
  57930. b.invert();
  57931. a.build(b.allPolygons());
  57932. a.invert();
  57933. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57934. };
  57935. CSG.prototype.subtractInPlace = function (csg) {
  57936. var a = new Node(this.polygons);
  57937. var b = new Node(csg.polygons);
  57938. a.invert();
  57939. a.clipTo(b);
  57940. b.clipTo(a);
  57941. b.invert();
  57942. b.clipTo(a);
  57943. b.invert();
  57944. a.build(b.allPolygons());
  57945. a.invert();
  57946. this.polygons = a.allPolygons();
  57947. };
  57948. CSG.prototype.intersect = function (csg) {
  57949. var a = new Node(this.clone().polygons);
  57950. var b = new Node(csg.clone().polygons);
  57951. a.invert();
  57952. b.clipTo(a);
  57953. b.invert();
  57954. a.clipTo(b);
  57955. b.clipTo(a);
  57956. a.build(b.allPolygons());
  57957. a.invert();
  57958. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57959. };
  57960. CSG.prototype.intersectInPlace = function (csg) {
  57961. var a = new Node(this.polygons);
  57962. var b = new Node(csg.polygons);
  57963. a.invert();
  57964. b.clipTo(a);
  57965. b.invert();
  57966. a.clipTo(b);
  57967. b.clipTo(a);
  57968. a.build(b.allPolygons());
  57969. a.invert();
  57970. this.polygons = a.allPolygons();
  57971. };
  57972. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  57973. // not modified.
  57974. CSG.prototype.inverse = function () {
  57975. var csg = this.clone();
  57976. csg.inverseInPlace();
  57977. return csg;
  57978. };
  57979. CSG.prototype.inverseInPlace = function () {
  57980. this.polygons.map(function (p) { p.flip(); });
  57981. };
  57982. // This is used to keep meshes transformations so they can be restored
  57983. // when we build back a Babylon Mesh
  57984. // NB : All CSG operations are performed in world coordinates
  57985. CSG.prototype.copyTransformAttributes = function (csg) {
  57986. this.matrix = csg.matrix;
  57987. this.position = csg.position;
  57988. this.rotation = csg.rotation;
  57989. this.scaling = csg.scaling;
  57990. this.rotationQuaternion = csg.rotationQuaternion;
  57991. return this;
  57992. };
  57993. // Build Raw mesh from CSG
  57994. // Coordinates here are in world space
  57995. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  57996. var matrix = this.matrix.clone();
  57997. matrix.invert();
  57998. 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;
  57999. if (keepSubMeshes) {
  58000. // Sort Polygons, since subMeshes are indices range
  58001. polygons.sort(function (a, b) {
  58002. if (a.shared.meshId === b.shared.meshId) {
  58003. return a.shared.subMeshId - b.shared.subMeshId;
  58004. }
  58005. else {
  58006. return a.shared.meshId - b.shared.meshId;
  58007. }
  58008. });
  58009. }
  58010. for (var i = 0, il = polygons.length; i < il; i++) {
  58011. polygon = polygons[i];
  58012. // Building SubMeshes
  58013. if (!subMesh_dict[polygon.shared.meshId]) {
  58014. subMesh_dict[polygon.shared.meshId] = {};
  58015. }
  58016. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  58017. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  58018. indexStart: +Infinity,
  58019. indexEnd: -Infinity,
  58020. materialIndex: polygon.shared.materialIndex
  58021. };
  58022. }
  58023. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  58024. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  58025. polygonIndices[0] = 0;
  58026. polygonIndices[1] = j - 1;
  58027. polygonIndices[2] = j;
  58028. for (var k = 0; k < 3; k++) {
  58029. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  58030. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  58031. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  58032. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  58033. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  58034. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  58035. // Check if 2 points can be merged
  58036. if (!(typeof vertex_idx !== 'undefined' &&
  58037. normals[vertex_idx * 3] === localNormal.x &&
  58038. normals[vertex_idx * 3 + 1] === localNormal.y &&
  58039. normals[vertex_idx * 3 + 2] === localNormal.z &&
  58040. uvs[vertex_idx * 2] === uv.x &&
  58041. uvs[vertex_idx * 2 + 1] === uv.y)) {
  58042. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  58043. uvs.push(uv.x, uv.y);
  58044. normals.push(normal.x, normal.y, normal.z);
  58045. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  58046. }
  58047. indices.push(vertex_idx);
  58048. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  58049. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  58050. currentIndex++;
  58051. }
  58052. }
  58053. }
  58054. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  58055. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  58056. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  58057. mesh.setIndices(indices);
  58058. if (keepSubMeshes) {
  58059. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  58060. var materialIndexOffset = 0, materialMaxIndex;
  58061. mesh.subMeshes = new Array();
  58062. for (var m in subMesh_dict) {
  58063. materialMaxIndex = -1;
  58064. for (var sm in subMesh_dict[m]) {
  58065. subMesh_obj = subMesh_dict[m][sm];
  58066. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  58067. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  58068. }
  58069. materialIndexOffset += ++materialMaxIndex;
  58070. }
  58071. }
  58072. return mesh;
  58073. };
  58074. // Build Mesh from CSG taking material and transforms into account
  58075. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  58076. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  58077. mesh.material = material;
  58078. mesh.position.copyFrom(this.position);
  58079. mesh.rotation.copyFrom(this.rotation);
  58080. if (this.rotationQuaternion) {
  58081. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  58082. }
  58083. mesh.scaling.copyFrom(this.scaling);
  58084. mesh.computeWorldMatrix(true);
  58085. return mesh;
  58086. };
  58087. return CSG;
  58088. }());
  58089. BABYLON.CSG = CSG;
  58090. })(BABYLON || (BABYLON = {}));
  58091. //# sourceMappingURL=babylon.csg.js.map
  58092. var BABYLON;
  58093. (function (BABYLON) {
  58094. var LensFlare = (function () {
  58095. function LensFlare(size, position, color, imgUrl, system) {
  58096. this.size = size;
  58097. this.position = position;
  58098. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  58099. this.dispose = function () {
  58100. if (this.texture) {
  58101. this.texture.dispose();
  58102. }
  58103. // Remove from scene
  58104. var index = this._system.lensFlares.indexOf(this);
  58105. this._system.lensFlares.splice(index, 1);
  58106. };
  58107. this.color = color || new BABYLON.Color3(1, 1, 1);
  58108. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  58109. this._system = system;
  58110. system.lensFlares.push(this);
  58111. }
  58112. return LensFlare;
  58113. }());
  58114. BABYLON.LensFlare = LensFlare;
  58115. })(BABYLON || (BABYLON = {}));
  58116. //# sourceMappingURL=babylon.lensFlare.js.map
  58117. var BABYLON;
  58118. (function (BABYLON) {
  58119. var LensFlareSystem = (function () {
  58120. function LensFlareSystem(name, emitter, scene) {
  58121. this.name = name;
  58122. this.lensFlares = new Array();
  58123. this.borderLimit = 300;
  58124. this.viewportBorder = 0;
  58125. this.layerMask = 0x0FFFFFFF;
  58126. this._vertexBuffers = {};
  58127. this._isEnabled = true;
  58128. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58129. this._emitter = emitter;
  58130. this.id = name;
  58131. scene.lensFlareSystems.push(this);
  58132. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  58133. var engine = scene.getEngine();
  58134. // VBO
  58135. var vertices = [];
  58136. vertices.push(1, 1);
  58137. vertices.push(-1, 1);
  58138. vertices.push(-1, -1);
  58139. vertices.push(1, -1);
  58140. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  58141. // Indices
  58142. var indices = [];
  58143. indices.push(0);
  58144. indices.push(1);
  58145. indices.push(2);
  58146. indices.push(0);
  58147. indices.push(2);
  58148. indices.push(3);
  58149. this._indexBuffer = engine.createIndexBuffer(indices);
  58150. // Effects
  58151. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  58152. }
  58153. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  58154. get: function () {
  58155. return this._isEnabled;
  58156. },
  58157. set: function (value) {
  58158. this._isEnabled = value;
  58159. },
  58160. enumerable: true,
  58161. configurable: true
  58162. });
  58163. LensFlareSystem.prototype.getScene = function () {
  58164. return this._scene;
  58165. };
  58166. LensFlareSystem.prototype.getEmitter = function () {
  58167. return this._emitter;
  58168. };
  58169. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  58170. this._emitter = newEmitter;
  58171. };
  58172. LensFlareSystem.prototype.getEmitterPosition = function () {
  58173. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  58174. };
  58175. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  58176. var position = this.getEmitterPosition();
  58177. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  58178. this._positionX = position.x;
  58179. this._positionY = position.y;
  58180. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  58181. if (this.viewportBorder > 0) {
  58182. globalViewport.x -= this.viewportBorder;
  58183. globalViewport.y -= this.viewportBorder;
  58184. globalViewport.width += this.viewportBorder * 2;
  58185. globalViewport.height += this.viewportBorder * 2;
  58186. position.x += this.viewportBorder;
  58187. position.y += this.viewportBorder;
  58188. this._positionX += this.viewportBorder;
  58189. this._positionY += this.viewportBorder;
  58190. }
  58191. if (position.z > 0) {
  58192. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  58193. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  58194. return true;
  58195. }
  58196. return true;
  58197. }
  58198. return false;
  58199. };
  58200. LensFlareSystem.prototype._isVisible = function () {
  58201. if (!this._isEnabled) {
  58202. return false;
  58203. }
  58204. var emitterPosition = this.getEmitterPosition();
  58205. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  58206. var distance = direction.length();
  58207. direction.normalize();
  58208. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  58209. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  58210. return !pickInfo.hit || pickInfo.distance > distance;
  58211. };
  58212. LensFlareSystem.prototype.render = function () {
  58213. if (!this._effect.isReady())
  58214. return false;
  58215. var engine = this._scene.getEngine();
  58216. var viewport = this._scene.activeCamera.viewport;
  58217. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  58218. // Position
  58219. if (!this.computeEffectivePosition(globalViewport)) {
  58220. return false;
  58221. }
  58222. // Visibility
  58223. if (!this._isVisible()) {
  58224. return false;
  58225. }
  58226. // Intensity
  58227. var awayX;
  58228. var awayY;
  58229. if (this._positionX < this.borderLimit + globalViewport.x) {
  58230. awayX = this.borderLimit + globalViewport.x - this._positionX;
  58231. }
  58232. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  58233. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  58234. }
  58235. else {
  58236. awayX = 0;
  58237. }
  58238. if (this._positionY < this.borderLimit + globalViewport.y) {
  58239. awayY = this.borderLimit + globalViewport.y - this._positionY;
  58240. }
  58241. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  58242. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  58243. }
  58244. else {
  58245. awayY = 0;
  58246. }
  58247. var away = (awayX > awayY) ? awayX : awayY;
  58248. away -= this.viewportBorder;
  58249. if (away > this.borderLimit) {
  58250. away = this.borderLimit;
  58251. }
  58252. var intensity = 1.0 - (away / this.borderLimit);
  58253. if (intensity < 0) {
  58254. return false;
  58255. }
  58256. if (intensity > 1.0) {
  58257. intensity = 1.0;
  58258. }
  58259. if (this.viewportBorder > 0) {
  58260. globalViewport.x += this.viewportBorder;
  58261. globalViewport.y += this.viewportBorder;
  58262. globalViewport.width -= this.viewportBorder * 2;
  58263. globalViewport.height -= this.viewportBorder * 2;
  58264. this._positionX -= this.viewportBorder;
  58265. this._positionY -= this.viewportBorder;
  58266. }
  58267. // Position
  58268. var centerX = globalViewport.x + globalViewport.width / 2;
  58269. var centerY = globalViewport.y + globalViewport.height / 2;
  58270. var distX = centerX - this._positionX;
  58271. var distY = centerY - this._positionY;
  58272. // Effects
  58273. engine.enableEffect(this._effect);
  58274. engine.setState(false);
  58275. engine.setDepthBuffer(false);
  58276. // VBOs
  58277. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58278. // Flares
  58279. for (var index = 0; index < this.lensFlares.length; index++) {
  58280. var flare = this.lensFlares[index];
  58281. engine.setAlphaMode(flare.alphaMode);
  58282. var x = centerX - (distX * flare.position);
  58283. var y = centerY - (distY * flare.position);
  58284. var cw = flare.size;
  58285. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  58286. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  58287. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  58288. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  58289. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  58290. // Texture
  58291. this._effect.setTexture("textureSampler", flare.texture);
  58292. // Color
  58293. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  58294. // Draw order
  58295. engine.draw(true, 0, 6);
  58296. }
  58297. engine.setDepthBuffer(true);
  58298. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58299. return true;
  58300. };
  58301. LensFlareSystem.prototype.dispose = function () {
  58302. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58303. if (vertexBuffer) {
  58304. vertexBuffer.dispose();
  58305. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  58306. }
  58307. if (this._indexBuffer) {
  58308. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58309. this._indexBuffer = null;
  58310. }
  58311. while (this.lensFlares.length) {
  58312. this.lensFlares[0].dispose();
  58313. }
  58314. // Remove from scene
  58315. var index = this._scene.lensFlareSystems.indexOf(this);
  58316. this._scene.lensFlareSystems.splice(index, 1);
  58317. };
  58318. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  58319. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  58320. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  58321. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  58322. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  58323. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  58324. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  58325. var parsedFlare = parsedLensFlareSystem.flares[index];
  58326. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  58327. }
  58328. return lensFlareSystem;
  58329. };
  58330. LensFlareSystem.prototype.serialize = function () {
  58331. var serializationObject = {};
  58332. serializationObject.id = this.id;
  58333. serializationObject.name = this.name;
  58334. serializationObject.emitterId = this.getEmitter().id;
  58335. serializationObject.borderLimit = this.borderLimit;
  58336. serializationObject.flares = [];
  58337. for (var index = 0; index < this.lensFlares.length; index++) {
  58338. var flare = this.lensFlares[index];
  58339. serializationObject.flares.push({
  58340. size: flare.size,
  58341. position: flare.position,
  58342. color: flare.color.asArray(),
  58343. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  58344. });
  58345. }
  58346. return serializationObject;
  58347. };
  58348. return LensFlareSystem;
  58349. }());
  58350. BABYLON.LensFlareSystem = LensFlareSystem;
  58351. })(BABYLON || (BABYLON = {}));
  58352. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  58353. var BABYLON;
  58354. (function (BABYLON) {
  58355. /**
  58356. * This is a holder class for the physics joint created by the physics plugin.
  58357. * It holds a set of functions to control the underlying joint.
  58358. */
  58359. var PhysicsJoint = (function () {
  58360. function PhysicsJoint(type, jointData) {
  58361. this.type = type;
  58362. this.jointData = jointData;
  58363. jointData.nativeParams = jointData.nativeParams || {};
  58364. }
  58365. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  58366. get: function () {
  58367. return this._physicsJoint;
  58368. },
  58369. set: function (newJoint) {
  58370. if (this._physicsJoint) {
  58371. //remove from the wolrd
  58372. }
  58373. this._physicsJoint = newJoint;
  58374. },
  58375. enumerable: true,
  58376. configurable: true
  58377. });
  58378. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  58379. set: function (physicsPlugin) {
  58380. this._physicsPlugin = physicsPlugin;
  58381. },
  58382. enumerable: true,
  58383. configurable: true
  58384. });
  58385. /**
  58386. * Execute a function that is physics-plugin specific.
  58387. * @param {Function} func the function that will be executed.
  58388. * It accepts two parameters: the physics world and the physics joint.
  58389. */
  58390. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  58391. func(this._physicsPlugin.world, this._physicsJoint);
  58392. };
  58393. return PhysicsJoint;
  58394. }());
  58395. //TODO check if the native joints are the same
  58396. //Joint Types
  58397. PhysicsJoint.DistanceJoint = 0;
  58398. PhysicsJoint.HingeJoint = 1;
  58399. PhysicsJoint.BallAndSocketJoint = 2;
  58400. PhysicsJoint.WheelJoint = 3;
  58401. PhysicsJoint.SliderJoint = 4;
  58402. //OIMO
  58403. PhysicsJoint.PrismaticJoint = 5;
  58404. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  58405. PhysicsJoint.UniversalJoint = 6;
  58406. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  58407. //Cannon
  58408. //Similar to a Ball-Joint. Different in params
  58409. PhysicsJoint.PointToPointJoint = 8;
  58410. //Cannon only at the moment
  58411. PhysicsJoint.SpringJoint = 9;
  58412. PhysicsJoint.LockJoint = 10;
  58413. BABYLON.PhysicsJoint = PhysicsJoint;
  58414. /**
  58415. * A class representing a physics distance joint.
  58416. */
  58417. var DistanceJoint = (function (_super) {
  58418. __extends(DistanceJoint, _super);
  58419. function DistanceJoint(jointData) {
  58420. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  58421. }
  58422. /**
  58423. * Update the predefined distance.
  58424. */
  58425. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  58426. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  58427. };
  58428. return DistanceJoint;
  58429. }(PhysicsJoint));
  58430. BABYLON.DistanceJoint = DistanceJoint;
  58431. var MotorEnabledJoint = (function (_super) {
  58432. __extends(MotorEnabledJoint, _super);
  58433. function MotorEnabledJoint(type, jointData) {
  58434. return _super.call(this, type, jointData) || this;
  58435. }
  58436. /**
  58437. * Set the motor values.
  58438. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58439. * @param {number} force the force to apply
  58440. * @param {number} maxForce max force for this motor.
  58441. */
  58442. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  58443. this._physicsPlugin.setMotor(this, force, maxForce);
  58444. };
  58445. /**
  58446. * Set the motor's limits.
  58447. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58448. */
  58449. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  58450. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  58451. };
  58452. return MotorEnabledJoint;
  58453. }(PhysicsJoint));
  58454. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  58455. /**
  58456. * This class represents a single hinge physics joint
  58457. */
  58458. var HingeJoint = (function (_super) {
  58459. __extends(HingeJoint, _super);
  58460. function HingeJoint(jointData) {
  58461. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  58462. }
  58463. /**
  58464. * Set the motor values.
  58465. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58466. * @param {number} force the force to apply
  58467. * @param {number} maxForce max force for this motor.
  58468. */
  58469. HingeJoint.prototype.setMotor = function (force, maxForce) {
  58470. this._physicsPlugin.setMotor(this, force, maxForce);
  58471. };
  58472. /**
  58473. * Set the motor's limits.
  58474. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58475. */
  58476. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  58477. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  58478. };
  58479. return HingeJoint;
  58480. }(MotorEnabledJoint));
  58481. BABYLON.HingeJoint = HingeJoint;
  58482. /**
  58483. * This class represents a dual hinge physics joint (same as wheel joint)
  58484. */
  58485. var Hinge2Joint = (function (_super) {
  58486. __extends(Hinge2Joint, _super);
  58487. function Hinge2Joint(jointData) {
  58488. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  58489. }
  58490. /**
  58491. * Set the motor values.
  58492. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58493. * @param {number} force the force to apply
  58494. * @param {number} maxForce max force for this motor.
  58495. * @param {motorIndex} the motor's index, 0 or 1.
  58496. */
  58497. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  58498. if (motorIndex === void 0) { motorIndex = 0; }
  58499. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  58500. };
  58501. /**
  58502. * Set the motor limits.
  58503. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58504. * @param {number} upperLimit the upper limit
  58505. * @param {number} lowerLimit lower limit
  58506. * @param {motorIndex} the motor's index, 0 or 1.
  58507. */
  58508. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  58509. if (motorIndex === void 0) { motorIndex = 0; }
  58510. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  58511. };
  58512. return Hinge2Joint;
  58513. }(MotorEnabledJoint));
  58514. BABYLON.Hinge2Joint = Hinge2Joint;
  58515. })(BABYLON || (BABYLON = {}));
  58516. //# sourceMappingURL=babylon.physicsJoint.js.map
  58517. var BABYLON;
  58518. (function (BABYLON) {
  58519. var PhysicsImpostor = (function () {
  58520. function PhysicsImpostor(object, type, _options, _scene) {
  58521. if (_options === void 0) { _options = { mass: 0 }; }
  58522. var _this = this;
  58523. this.object = object;
  58524. this.type = type;
  58525. this._options = _options;
  58526. this._scene = _scene;
  58527. this._bodyUpdateRequired = false;
  58528. this._onBeforePhysicsStepCallbacks = new Array();
  58529. this._onAfterPhysicsStepCallbacks = new Array();
  58530. this._onPhysicsCollideCallbacks = [];
  58531. this._deltaPosition = BABYLON.Vector3.Zero();
  58532. this._isDisposed = false;
  58533. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  58534. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  58535. /**
  58536. * this function is executed by the physics engine.
  58537. */
  58538. this.beforeStep = function () {
  58539. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  58540. //conjugate deltaRotation
  58541. if (_this._deltaRotationConjugated) {
  58542. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  58543. }
  58544. else {
  58545. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  58546. }
  58547. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  58548. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  58549. func(_this);
  58550. });
  58551. };
  58552. /**
  58553. * this function is executed by the physics engine.
  58554. */
  58555. this.afterStep = function () {
  58556. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  58557. func(_this);
  58558. });
  58559. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  58560. _this.object.position.addInPlace(_this._deltaPosition);
  58561. if (_this._deltaRotation) {
  58562. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  58563. }
  58564. };
  58565. /**
  58566. * Legacy collision detection event support
  58567. */
  58568. this.onCollideEvent = null;
  58569. //event and body object due to cannon's event-based architecture.
  58570. this.onCollide = function (e) {
  58571. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  58572. return;
  58573. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  58574. if (otherImpostor) {
  58575. // Legacy collision detection event support
  58576. if (_this.onCollideEvent) {
  58577. _this.onCollideEvent(_this, otherImpostor);
  58578. }
  58579. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  58580. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  58581. }).forEach(function (obj) {
  58582. obj.callback(_this, otherImpostor);
  58583. });
  58584. }
  58585. };
  58586. //sanity check!
  58587. if (!this.object) {
  58588. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  58589. return;
  58590. }
  58591. //legacy support for old syntax.
  58592. if (!this._scene && object.getScene) {
  58593. this._scene = object.getScene();
  58594. }
  58595. this._physicsEngine = this._scene.getPhysicsEngine();
  58596. if (!this._physicsEngine) {
  58597. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  58598. }
  58599. else {
  58600. //set the object's quaternion, if not set
  58601. if (!this.object.rotationQuaternion) {
  58602. if (this.object.rotation) {
  58603. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  58604. }
  58605. else {
  58606. this.object.rotationQuaternion = new BABYLON.Quaternion();
  58607. }
  58608. }
  58609. //default options params
  58610. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  58611. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  58612. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  58613. this._joints = [];
  58614. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  58615. if (!this.object.parent) {
  58616. this._init();
  58617. }
  58618. else if (this.object.parent.physicsImpostor) {
  58619. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  58620. }
  58621. }
  58622. }
  58623. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  58624. get: function () {
  58625. return this._isDisposed;
  58626. },
  58627. enumerable: true,
  58628. configurable: true
  58629. });
  58630. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  58631. get: function () {
  58632. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  58633. },
  58634. set: function (value) {
  58635. this.setMass(value);
  58636. },
  58637. enumerable: true,
  58638. configurable: true
  58639. });
  58640. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  58641. get: function () {
  58642. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  58643. },
  58644. set: function (value) {
  58645. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  58646. },
  58647. enumerable: true,
  58648. configurable: true
  58649. });
  58650. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  58651. get: function () {
  58652. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  58653. },
  58654. set: function (value) {
  58655. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  58656. },
  58657. enumerable: true,
  58658. configurable: true
  58659. });
  58660. /**
  58661. * This function will completly initialize this impostor.
  58662. * It will create a new body - but only if this mesh has no parent.
  58663. * If it has, this impostor will not be used other than to define the impostor
  58664. * of the child mesh.
  58665. */
  58666. PhysicsImpostor.prototype._init = function () {
  58667. this._physicsEngine.removeImpostor(this);
  58668. this.physicsBody = null;
  58669. this._parent = this._parent || this._getPhysicsParent();
  58670. if (!this.parent) {
  58671. this._physicsEngine.addImpostor(this);
  58672. }
  58673. };
  58674. PhysicsImpostor.prototype._getPhysicsParent = function () {
  58675. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  58676. var parentMesh = this.object.parent;
  58677. return parentMesh.physicsImpostor;
  58678. }
  58679. return;
  58680. };
  58681. /**
  58682. * Should a new body be generated.
  58683. */
  58684. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  58685. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  58686. };
  58687. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  58688. this.forceUpdate();
  58689. };
  58690. /**
  58691. * Force a regeneration of this or the parent's impostor's body.
  58692. * Use under cautious - This will remove all joints already implemented.
  58693. */
  58694. PhysicsImpostor.prototype.forceUpdate = function () {
  58695. this._init();
  58696. if (this.parent) {
  58697. this.parent.forceUpdate();
  58698. }
  58699. };
  58700. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  58701. /*public get mesh(): AbstractMesh {
  58702. return this._mesh;
  58703. }*/
  58704. /**
  58705. * Gets the body that holds this impostor. Either its own, or its parent.
  58706. */
  58707. get: function () {
  58708. return this._parent ? this._parent.physicsBody : this._physicsBody;
  58709. },
  58710. /**
  58711. * Set the physics body. Used mainly by the physics engine/plugin
  58712. */
  58713. set: function (physicsBody) {
  58714. if (this._physicsBody) {
  58715. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  58716. }
  58717. this._physicsBody = physicsBody;
  58718. this.resetUpdateFlags();
  58719. },
  58720. enumerable: true,
  58721. configurable: true
  58722. });
  58723. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  58724. get: function () {
  58725. return this._parent;
  58726. },
  58727. set: function (value) {
  58728. this._parent = value;
  58729. },
  58730. enumerable: true,
  58731. configurable: true
  58732. });
  58733. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  58734. this._bodyUpdateRequired = false;
  58735. };
  58736. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  58737. if (this.object.getBoundingInfo) {
  58738. var q = this.object.rotationQuaternion;
  58739. //reset rotation
  58740. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  58741. //calculate the world matrix with no rotation
  58742. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  58743. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  58744. //bring back the rotation
  58745. this.object.rotationQuaternion = q;
  58746. //calculate the world matrix with the new rotation
  58747. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  58748. return size;
  58749. }
  58750. else {
  58751. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  58752. }
  58753. };
  58754. PhysicsImpostor.prototype.getObjectCenter = function () {
  58755. if (this.object.getBoundingInfo) {
  58756. return this.object.getBoundingInfo().boundingBox.centerWorld;
  58757. }
  58758. else {
  58759. return this.object.position;
  58760. }
  58761. };
  58762. /**
  58763. * Get a specific parametes from the options parameter.
  58764. */
  58765. PhysicsImpostor.prototype.getParam = function (paramName) {
  58766. return this._options[paramName];
  58767. };
  58768. /**
  58769. * Sets a specific parameter in the options given to the physics plugin
  58770. */
  58771. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  58772. this._options[paramName] = value;
  58773. this._bodyUpdateRequired = true;
  58774. };
  58775. /**
  58776. * Specifically change the body's mass option. Won't recreate the physics body object
  58777. */
  58778. PhysicsImpostor.prototype.setMass = function (mass) {
  58779. if (this.getParam("mass") !== mass) {
  58780. this.setParam("mass", mass);
  58781. }
  58782. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  58783. };
  58784. PhysicsImpostor.prototype.getLinearVelocity = function () {
  58785. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  58786. };
  58787. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  58788. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  58789. };
  58790. PhysicsImpostor.prototype.getAngularVelocity = function () {
  58791. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  58792. };
  58793. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  58794. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  58795. };
  58796. /**
  58797. * Execute a function with the physics plugin native code.
  58798. * Provide a function the will have two variables - the world object and the physics body object.
  58799. */
  58800. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  58801. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  58802. };
  58803. /**
  58804. * Register a function that will be executed before the physics world is stepping forward.
  58805. */
  58806. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  58807. this._onBeforePhysicsStepCallbacks.push(func);
  58808. };
  58809. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  58810. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  58811. if (index > -1) {
  58812. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  58813. }
  58814. else {
  58815. BABYLON.Tools.Warn("Function to remove was not found");
  58816. }
  58817. };
  58818. /**
  58819. * Register a function that will be executed after the physics step
  58820. */
  58821. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  58822. this._onAfterPhysicsStepCallbacks.push(func);
  58823. };
  58824. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  58825. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  58826. if (index > -1) {
  58827. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  58828. }
  58829. else {
  58830. BABYLON.Tools.Warn("Function to remove was not found");
  58831. }
  58832. };
  58833. /**
  58834. * register a function that will be executed when this impostor collides against a different body.
  58835. */
  58836. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  58837. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  58838. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  58839. };
  58840. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  58841. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  58842. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  58843. if (index > -1) {
  58844. this._onPhysicsCollideCallbacks.splice(index, 1);
  58845. }
  58846. else {
  58847. BABYLON.Tools.Warn("Function to remove was not found");
  58848. }
  58849. };
  58850. /**
  58851. * Apply a force
  58852. */
  58853. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  58854. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  58855. };
  58856. /**
  58857. * Apply an impulse
  58858. */
  58859. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  58860. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  58861. };
  58862. /**
  58863. * A help function to create a joint.
  58864. */
  58865. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  58866. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  58867. this.addJoint(otherImpostor, joint);
  58868. };
  58869. /**
  58870. * Add a joint to this impostor with a different impostor.
  58871. */
  58872. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  58873. this._joints.push({
  58874. otherImpostor: otherImpostor,
  58875. joint: joint
  58876. });
  58877. this._physicsEngine.addJoint(this, otherImpostor, joint);
  58878. };
  58879. /**
  58880. * Will keep this body still, in a sleep mode.
  58881. */
  58882. PhysicsImpostor.prototype.sleep = function () {
  58883. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  58884. };
  58885. /**
  58886. * Wake the body up.
  58887. */
  58888. PhysicsImpostor.prototype.wakeUp = function () {
  58889. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  58890. };
  58891. PhysicsImpostor.prototype.clone = function (newObject) {
  58892. if (!newObject)
  58893. return null;
  58894. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  58895. };
  58896. PhysicsImpostor.prototype.dispose = function () {
  58897. var _this = this;
  58898. //no dispose if no physics engine is available.
  58899. if (!this._physicsEngine) {
  58900. return;
  58901. }
  58902. this._joints.forEach(function (j) {
  58903. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  58904. });
  58905. //dispose the physics body
  58906. this._physicsEngine.removeImpostor(this);
  58907. if (this.parent) {
  58908. this.parent.forceUpdate();
  58909. }
  58910. else {
  58911. /*this._object.getChildMeshes().forEach(function(mesh) {
  58912. if (mesh.physicsImpostor) {
  58913. if (disposeChildren) {
  58914. mesh.physicsImpostor.dispose();
  58915. mesh.physicsImpostor = null;
  58916. }
  58917. }
  58918. })*/
  58919. }
  58920. this._isDisposed = true;
  58921. };
  58922. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  58923. this._deltaPosition.copyFrom(position);
  58924. };
  58925. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  58926. if (!this._deltaRotation) {
  58927. this._deltaRotation = new BABYLON.Quaternion();
  58928. }
  58929. this._deltaRotation.copyFrom(rotation);
  58930. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  58931. };
  58932. return PhysicsImpostor;
  58933. }());
  58934. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  58935. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  58936. //Impostor types
  58937. PhysicsImpostor.NoImpostor = 0;
  58938. PhysicsImpostor.SphereImpostor = 1;
  58939. PhysicsImpostor.BoxImpostor = 2;
  58940. PhysicsImpostor.PlaneImpostor = 3;
  58941. PhysicsImpostor.MeshImpostor = 4;
  58942. PhysicsImpostor.CylinderImpostor = 7;
  58943. PhysicsImpostor.ParticleImpostor = 8;
  58944. PhysicsImpostor.HeightmapImpostor = 9;
  58945. BABYLON.PhysicsImpostor = PhysicsImpostor;
  58946. })(BABYLON || (BABYLON = {}));
  58947. //# sourceMappingURL=babylon.physicsImpostor.js.map
  58948. var BABYLON;
  58949. (function (BABYLON) {
  58950. var PhysicsEngine = (function () {
  58951. function PhysicsEngine(gravity, _physicsPlugin) {
  58952. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  58953. this._physicsPlugin = _physicsPlugin;
  58954. //new methods and parameters
  58955. this._impostors = [];
  58956. this._joints = [];
  58957. if (!this._physicsPlugin.isSupported()) {
  58958. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  58959. + "Please make sure it is included.");
  58960. }
  58961. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  58962. this.setGravity(gravity);
  58963. this.setTimeStep();
  58964. }
  58965. PhysicsEngine.prototype.setGravity = function (gravity) {
  58966. this.gravity = gravity;
  58967. this._physicsPlugin.setGravity(this.gravity);
  58968. };
  58969. /**
  58970. * Set the time step of the physics engine.
  58971. * default is 1/60.
  58972. * To slow it down, enter 1/600 for example.
  58973. * To speed it up, 1/30
  58974. * @param {number} newTimeStep the new timestep to apply to this world.
  58975. */
  58976. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  58977. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  58978. this._physicsPlugin.setTimeStep(newTimeStep);
  58979. };
  58980. PhysicsEngine.prototype.dispose = function () {
  58981. this._impostors.forEach(function (impostor) {
  58982. impostor.dispose();
  58983. });
  58984. this._physicsPlugin.dispose();
  58985. };
  58986. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  58987. return this._physicsPlugin.name;
  58988. };
  58989. /**
  58990. * Adding a new impostor for the impostor tracking.
  58991. * This will be done by the impostor itself.
  58992. * @param {PhysicsImpostor} impostor the impostor to add
  58993. */
  58994. PhysicsEngine.prototype.addImpostor = function (impostor) {
  58995. impostor.uniqueId = this._impostors.push(impostor);
  58996. //if no parent, generate the body
  58997. if (!impostor.parent) {
  58998. this._physicsPlugin.generatePhysicsBody(impostor);
  58999. }
  59000. };
  59001. /**
  59002. * Remove an impostor from the engine.
  59003. * This impostor and its mesh will not longer be updated by the physics engine.
  59004. * @param {PhysicsImpostor} impostor the impostor to remove
  59005. */
  59006. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  59007. var index = this._impostors.indexOf(impostor);
  59008. if (index > -1) {
  59009. var removed = this._impostors.splice(index, 1);
  59010. //Is it needed?
  59011. if (removed.length) {
  59012. //this will also remove it from the world.
  59013. removed[0].physicsBody = null;
  59014. }
  59015. }
  59016. };
  59017. /**
  59018. * Add a joint to the physics engine
  59019. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  59020. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  59021. * @param {PhysicsJoint} the joint that will connect both impostors.
  59022. */
  59023. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  59024. var impostorJoint = {
  59025. mainImpostor: mainImpostor,
  59026. connectedImpostor: connectedImpostor,
  59027. joint: joint
  59028. };
  59029. joint.physicsPlugin = this._physicsPlugin;
  59030. this._joints.push(impostorJoint);
  59031. this._physicsPlugin.generateJoint(impostorJoint);
  59032. };
  59033. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  59034. var matchingJoints = this._joints.filter(function (impostorJoint) {
  59035. return (impostorJoint.connectedImpostor === connectedImpostor
  59036. && impostorJoint.joint === joint
  59037. && impostorJoint.mainImpostor === mainImpostor);
  59038. });
  59039. if (matchingJoints.length) {
  59040. this._physicsPlugin.removeJoint(matchingJoints[0]);
  59041. //TODO remove it from the list as well
  59042. }
  59043. };
  59044. /**
  59045. * Called by the scene. no need to call it.
  59046. */
  59047. PhysicsEngine.prototype._step = function (delta) {
  59048. var _this = this;
  59049. //check if any mesh has no body / requires an update
  59050. this._impostors.forEach(function (impostor) {
  59051. if (impostor.isBodyInitRequired()) {
  59052. _this._physicsPlugin.generatePhysicsBody(impostor);
  59053. }
  59054. });
  59055. if (delta > 0.1) {
  59056. delta = 0.1;
  59057. }
  59058. else if (delta <= 0) {
  59059. delta = 1.0 / 60.0;
  59060. }
  59061. this._physicsPlugin.executeStep(delta, this._impostors);
  59062. };
  59063. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  59064. return this._physicsPlugin;
  59065. };
  59066. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  59067. for (var i = 0; i < this._impostors.length; ++i) {
  59068. if (this._impostors[i].object === object) {
  59069. return this._impostors[i];
  59070. }
  59071. }
  59072. };
  59073. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  59074. for (var i = 0; i < this._impostors.length; ++i) {
  59075. if (this._impostors[i].physicsBody === body) {
  59076. return this._impostors[i];
  59077. }
  59078. }
  59079. };
  59080. return PhysicsEngine;
  59081. }());
  59082. // Statics
  59083. PhysicsEngine.Epsilon = 0.001;
  59084. BABYLON.PhysicsEngine = PhysicsEngine;
  59085. })(BABYLON || (BABYLON = {}));
  59086. //# sourceMappingURL=babylon.physicsEngine.js.map
  59087. var BABYLON;
  59088. (function (BABYLON) {
  59089. var CannonJSPlugin = (function () {
  59090. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  59091. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  59092. if (iterations === void 0) { iterations = 10; }
  59093. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  59094. this.name = "CannonJSPlugin";
  59095. this._physicsMaterials = [];
  59096. this._fixedTimeStep = 1 / 60;
  59097. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59098. this._currentCollisionGroup = 2;
  59099. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  59100. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  59101. this._tmpPosition = BABYLON.Vector3.Zero();
  59102. this._tmpQuaternion = new BABYLON.Quaternion();
  59103. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  59104. this._tmpDeltaRotation = new BABYLON.Quaternion();
  59105. this._tmpUnityRotation = new BABYLON.Quaternion();
  59106. if (!this.isSupported()) {
  59107. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  59108. return;
  59109. }
  59110. this.world = new CANNON.World();
  59111. this.world.broadphase = new CANNON.NaiveBroadphase();
  59112. this.world.solver.iterations = iterations;
  59113. }
  59114. CannonJSPlugin.prototype.setGravity = function (gravity) {
  59115. this.world.gravity.copy(gravity);
  59116. };
  59117. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  59118. this._fixedTimeStep = timeStep;
  59119. };
  59120. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  59121. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  59122. };
  59123. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  59124. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59125. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59126. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  59127. };
  59128. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  59129. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59130. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59131. impostor.physicsBody.applyForce(impulse, worldPoint);
  59132. };
  59133. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  59134. //parent-child relationship. Does this impostor has a parent impostor?
  59135. if (impostor.parent) {
  59136. if (impostor.physicsBody) {
  59137. this.removePhysicsBody(impostor);
  59138. //TODO is that needed?
  59139. impostor.forceUpdate();
  59140. }
  59141. return;
  59142. }
  59143. //should a new body be created for this impostor?
  59144. if (impostor.isBodyInitRequired()) {
  59145. var shape = this._createShape(impostor);
  59146. //unregister events, if body is being changed
  59147. var oldBody = impostor.physicsBody;
  59148. if (oldBody) {
  59149. this.removePhysicsBody(impostor);
  59150. }
  59151. //create the body and material
  59152. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  59153. var bodyCreationObject = {
  59154. mass: impostor.getParam("mass"),
  59155. material: material
  59156. };
  59157. // A simple extend, in case native options were used.
  59158. var nativeOptions = impostor.getParam("nativeOptions");
  59159. for (var key in nativeOptions) {
  59160. if (nativeOptions.hasOwnProperty(key)) {
  59161. bodyCreationObject[key] = nativeOptions[key];
  59162. }
  59163. }
  59164. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  59165. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  59166. this.world.addEventListener("preStep", impostor.beforeStep);
  59167. this.world.addEventListener("postStep", impostor.afterStep);
  59168. impostor.physicsBody.addShape(shape);
  59169. this.world.add(impostor.physicsBody);
  59170. //try to keep the body moving in the right direction by taking old properties.
  59171. //Should be tested!
  59172. if (oldBody) {
  59173. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  59174. impostor.physicsBody[param].copy(oldBody[param]);
  59175. });
  59176. }
  59177. this._processChildMeshes(impostor);
  59178. }
  59179. //now update the body's transformation
  59180. this._updatePhysicsBodyTransformation(impostor);
  59181. };
  59182. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  59183. var _this = this;
  59184. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  59185. if (meshChildren.length) {
  59186. var processMesh = function (localPosition, mesh) {
  59187. var childImpostor = mesh.getPhysicsImpostor();
  59188. if (childImpostor) {
  59189. var parent = childImpostor.parent;
  59190. if (parent !== mainImpostor) {
  59191. var localPosition = mesh.position;
  59192. if (childImpostor.physicsBody) {
  59193. _this.removePhysicsBody(childImpostor);
  59194. childImpostor.physicsBody = null;
  59195. }
  59196. childImpostor.parent = mainImpostor;
  59197. childImpostor.resetUpdateFlags();
  59198. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  59199. //Add the mass of the children.
  59200. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  59201. }
  59202. }
  59203. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  59204. };
  59205. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  59206. }
  59207. };
  59208. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  59209. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  59210. this.world.removeEventListener("preStep", impostor.beforeStep);
  59211. this.world.removeEventListener("postStep", impostor.afterStep);
  59212. this.world.remove(impostor.physicsBody);
  59213. };
  59214. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  59215. var mainBody = impostorJoint.mainImpostor.physicsBody;
  59216. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  59217. if (!mainBody || !connectedBody) {
  59218. return;
  59219. }
  59220. var constraint;
  59221. var jointData = impostorJoint.joint.jointData;
  59222. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59223. var constraintData = {
  59224. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  59225. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  59226. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  59227. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  59228. maxForce: jointData.nativeParams.maxForce,
  59229. collideConnected: !!jointData.collision
  59230. };
  59231. switch (impostorJoint.joint.type) {
  59232. case BABYLON.PhysicsJoint.HingeJoint:
  59233. case BABYLON.PhysicsJoint.Hinge2Joint:
  59234. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  59235. break;
  59236. case BABYLON.PhysicsJoint.DistanceJoint:
  59237. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  59238. break;
  59239. case BABYLON.PhysicsJoint.SpringJoint:
  59240. var springData = jointData;
  59241. constraint = new CANNON.Spring(mainBody, connectedBody, {
  59242. restLength: springData.length,
  59243. stiffness: springData.stiffness,
  59244. damping: springData.damping,
  59245. localAnchorA: constraintData.pivotA,
  59246. localAnchorB: constraintData.pivotB
  59247. });
  59248. break;
  59249. case BABYLON.PhysicsJoint.LockJoint:
  59250. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  59251. break;
  59252. case BABYLON.PhysicsJoint.PointToPointJoint:
  59253. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  59254. default:
  59255. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  59256. break;
  59257. }
  59258. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  59259. constraint.collideConnected = !!jointData.collision;
  59260. impostorJoint.joint.physicsJoint = constraint;
  59261. //don't add spring as constraint, as it is not one.
  59262. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  59263. this.world.addConstraint(constraint);
  59264. }
  59265. else {
  59266. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  59267. constraint.applyForce();
  59268. });
  59269. }
  59270. };
  59271. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  59272. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  59273. };
  59274. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  59275. var index;
  59276. var mat;
  59277. for (index = 0; index < this._physicsMaterials.length; index++) {
  59278. mat = this._physicsMaterials[index];
  59279. if (mat.friction === friction && mat.restitution === restitution) {
  59280. return mat;
  59281. }
  59282. }
  59283. var currentMat = new CANNON.Material(name);
  59284. currentMat.friction = friction;
  59285. currentMat.restitution = restitution;
  59286. this._physicsMaterials.push(currentMat);
  59287. return currentMat;
  59288. };
  59289. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  59290. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  59291. };
  59292. CannonJSPlugin.prototype._createShape = function (impostor) {
  59293. var object = impostor.object;
  59294. var returnValue;
  59295. var extendSize = impostor.getObjectExtendSize();
  59296. switch (impostor.type) {
  59297. case BABYLON.PhysicsImpostor.SphereImpostor:
  59298. var radiusX = extendSize.x;
  59299. var radiusY = extendSize.y;
  59300. var radiusZ = extendSize.z;
  59301. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  59302. break;
  59303. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  59304. case BABYLON.PhysicsImpostor.CylinderImpostor:
  59305. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  59306. break;
  59307. case BABYLON.PhysicsImpostor.BoxImpostor:
  59308. var box = extendSize.scale(0.5);
  59309. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  59310. break;
  59311. case BABYLON.PhysicsImpostor.PlaneImpostor:
  59312. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  59313. returnValue = new CANNON.Plane();
  59314. break;
  59315. case BABYLON.PhysicsImpostor.MeshImpostor:
  59316. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  59317. var rawFaces = object.getIndices ? object.getIndices() : [];
  59318. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  59319. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  59320. break;
  59321. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  59322. returnValue = this._createHeightmap(object);
  59323. break;
  59324. case BABYLON.PhysicsImpostor.ParticleImpostor:
  59325. returnValue = new CANNON.Particle();
  59326. break;
  59327. }
  59328. return returnValue;
  59329. };
  59330. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  59331. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59332. var matrix = [];
  59333. //For now pointDepth will not be used and will be automatically calculated.
  59334. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  59335. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  59336. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  59337. var elementSize = dim * 2 / arraySize;
  59338. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  59339. for (var i = 0; i < pos.length; i = i + 3) {
  59340. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  59341. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  59342. var y = pos[i + 1] + minY;
  59343. if (!matrix[x]) {
  59344. matrix[x] = [];
  59345. }
  59346. if (!matrix[x][z]) {
  59347. matrix[x][z] = y;
  59348. }
  59349. matrix[x][z] = Math.max(y, matrix[x][z]);
  59350. }
  59351. for (var x = 0; x <= arraySize; ++x) {
  59352. if (!matrix[x]) {
  59353. var loc = 1;
  59354. while (!matrix[(x + loc) % arraySize]) {
  59355. loc++;
  59356. }
  59357. matrix[x] = matrix[(x + loc) % arraySize].slice();
  59358. //console.log("missing x", x);
  59359. }
  59360. for (var z = 0; z <= arraySize; ++z) {
  59361. if (!matrix[x][z]) {
  59362. var loc = 1;
  59363. var newValue;
  59364. while (newValue === undefined) {
  59365. newValue = matrix[x][(z + loc++) % arraySize];
  59366. }
  59367. matrix[x][z] = newValue;
  59368. }
  59369. }
  59370. }
  59371. var shape = new CANNON.Heightfield(matrix, {
  59372. elementSize: elementSize
  59373. });
  59374. //For future reference, needed for body transformation
  59375. shape.minY = minY;
  59376. return shape;
  59377. };
  59378. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  59379. var object = impostor.object;
  59380. //make sure it is updated...
  59381. object.computeWorldMatrix && object.computeWorldMatrix(true);
  59382. // The delta between the mesh position and the mesh bounding box center
  59383. var center = impostor.getObjectCenter();
  59384. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  59385. this._tmpPosition.copyFrom(center);
  59386. var quaternion = object.rotationQuaternion;
  59387. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  59388. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  59389. //-90 DEG in X, precalculated
  59390. quaternion = quaternion.multiply(this._minus90X);
  59391. //Invert! (Precalculated, 90 deg in X)
  59392. //No need to clone. this will never change.
  59393. impostor.setDeltaRotation(this._plus90X);
  59394. }
  59395. //If it is a heightfield, if should be centered.
  59396. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  59397. var mesh = object;
  59398. //calculate the correct body position:
  59399. var rotationQuaternion = mesh.rotationQuaternion;
  59400. mesh.rotationQuaternion = this._tmpUnityRotation;
  59401. mesh.computeWorldMatrix(true);
  59402. //get original center with no rotation
  59403. var c = center.clone();
  59404. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  59405. //rotation is back
  59406. mesh.rotationQuaternion = rotationQuaternion;
  59407. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  59408. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  59409. mesh.setPivotMatrix(p);
  59410. mesh.computeWorldMatrix(true);
  59411. //calculate the translation
  59412. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  59413. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  59414. //add it inverted to the delta
  59415. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  59416. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  59417. mesh.setPivotMatrix(oldPivot);
  59418. mesh.computeWorldMatrix(true);
  59419. }
  59420. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  59421. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  59422. this._tmpPosition.copyFrom(object.position);
  59423. }
  59424. impostor.setDeltaPosition(this._tmpDeltaPosition);
  59425. //Now update the impostor object
  59426. impostor.physicsBody.position.copy(this._tmpPosition);
  59427. impostor.physicsBody.quaternion.copy(quaternion);
  59428. };
  59429. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  59430. impostor.object.position.copyFrom(impostor.physicsBody.position);
  59431. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  59432. };
  59433. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  59434. impostor.physicsBody.position.copy(newPosition);
  59435. impostor.physicsBody.quaternion.copy(newRotation);
  59436. };
  59437. CannonJSPlugin.prototype.isSupported = function () {
  59438. return window.CANNON !== undefined;
  59439. };
  59440. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  59441. impostor.physicsBody.velocity.copy(velocity);
  59442. };
  59443. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  59444. impostor.physicsBody.angularVelocity.copy(velocity);
  59445. };
  59446. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  59447. var v = impostor.physicsBody.velocity;
  59448. if (!v)
  59449. return null;
  59450. return new BABYLON.Vector3(v.x, v.y, v.z);
  59451. };
  59452. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  59453. var v = impostor.physicsBody.angularVelocity;
  59454. if (!v)
  59455. return null;
  59456. return new BABYLON.Vector3(v.x, v.y, v.z);
  59457. };
  59458. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  59459. impostor.physicsBody.mass = mass;
  59460. impostor.physicsBody.updateMassProperties();
  59461. };
  59462. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  59463. return impostor.physicsBody.mass;
  59464. };
  59465. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  59466. return impostor.physicsBody.material.friction;
  59467. };
  59468. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  59469. impostor.physicsBody.material.friction = friction;
  59470. };
  59471. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  59472. return impostor.physicsBody.material.restitution;
  59473. };
  59474. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  59475. impostor.physicsBody.material.restitution = restitution;
  59476. };
  59477. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  59478. impostor.physicsBody.sleep();
  59479. };
  59480. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  59481. impostor.physicsBody.wakeUp();
  59482. };
  59483. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  59484. joint.physicsJoint.distance = maxDistance;
  59485. };
  59486. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  59487. if (!motorIndex) {
  59488. joint.physicsJoint.enableMotor();
  59489. }
  59490. };
  59491. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  59492. if (!motorIndex) {
  59493. joint.physicsJoint.disableMotor();
  59494. }
  59495. };
  59496. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  59497. if (!motorIndex) {
  59498. joint.physicsJoint.enableMotor();
  59499. joint.physicsJoint.setMotorSpeed(speed);
  59500. if (maxForce) {
  59501. this.setLimit(joint, maxForce);
  59502. }
  59503. }
  59504. };
  59505. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  59506. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  59507. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  59508. };
  59509. CannonJSPlugin.prototype._getDebugMaterial = function (scene) {
  59510. if (!this._debugMaterial) {
  59511. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59512. this._debugMaterial.wireframe = true;
  59513. }
  59514. return this._debugMaterial;
  59515. };
  59516. CannonJSPlugin.prototype._getDebugBoxMesh = function (scene) {
  59517. if (!this._debugBoxMesh) {
  59518. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59519. this._debugBoxMesh.renderingGroupId = 1;
  59520. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59521. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59522. scene.removeMesh(this._debugBoxMesh);
  59523. }
  59524. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59525. };
  59526. CannonJSPlugin.prototype._getDebugSphereMesh = function (scene) {
  59527. if (!this._debugSphereMesh) {
  59528. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59529. this._debugSphereMesh.renderingGroupId = 1;
  59530. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59531. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59532. scene.removeMesh(this._debugSphereMesh);
  59533. }
  59534. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59535. };
  59536. CannonJSPlugin.prototype.getDebugMesh = function (impostor, scene) {
  59537. var body = impostor.physicsBody;
  59538. var shape = body.shapes[0];
  59539. var mesh;
  59540. if (shape.halfExtents) {
  59541. mesh = this._getDebugBoxMesh(scene);
  59542. mesh.scaling.x = shape.halfExtents.x * 2;
  59543. mesh.scaling.y = shape.halfExtents.y * 2;
  59544. mesh.scaling.z = shape.halfExtents.z * 2;
  59545. }
  59546. else if (shape.boundingSphereRadius) {
  59547. mesh = this._getDebugSphereMesh(scene);
  59548. mesh.scaling.x = shape.boundingSphereRadius * 2;
  59549. mesh.scaling.y = shape.boundingSphereRadius * 2;
  59550. mesh.scaling.z = shape.boundingSphereRadius * 2;
  59551. }
  59552. return mesh;
  59553. };
  59554. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  59555. var body = impostor.physicsBody;
  59556. mesh.position.x = body.position.x;
  59557. mesh.position.y = body.position.y;
  59558. mesh.position.z = body.position.z;
  59559. mesh.rotationQuaternion.x = body.quaternion.x;
  59560. mesh.rotationQuaternion.y = body.quaternion.y;
  59561. mesh.rotationQuaternion.z = body.quaternion.z;
  59562. mesh.rotationQuaternion.w = body.quaternion.w;
  59563. };
  59564. CannonJSPlugin.prototype.dispose = function () {
  59565. if (this._debugBoxMesh) {
  59566. this._debugBoxMesh.dispose();
  59567. }
  59568. if (this._debugSphereMesh) {
  59569. this._debugSphereMesh.dispose();
  59570. }
  59571. if (this._debugMaterial) {
  59572. this._debugMaterial.dispose();
  59573. }
  59574. };
  59575. return CannonJSPlugin;
  59576. }());
  59577. BABYLON.CannonJSPlugin = CannonJSPlugin;
  59578. })(BABYLON || (BABYLON = {}));
  59579. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  59580. var BABYLON;
  59581. (function (BABYLON) {
  59582. var OimoJSPlugin = (function () {
  59583. function OimoJSPlugin(iterations) {
  59584. this.name = "OimoJSPlugin";
  59585. this._tmpImpostorsArray = [];
  59586. this._tmpPositionVector = BABYLON.Vector3.Zero();
  59587. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  59588. this.world.worldscale(1);
  59589. this.world.clear();
  59590. //making sure no stats are calculated
  59591. this.world.isNoStat = true;
  59592. }
  59593. OimoJSPlugin.prototype.setGravity = function (gravity) {
  59594. this.world.gravity.copy(gravity);
  59595. };
  59596. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  59597. this.world.timeStep = timeStep;
  59598. };
  59599. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  59600. var _this = this;
  59601. impostors.forEach(function (impostor) {
  59602. impostor.beforeStep();
  59603. });
  59604. this.world.step();
  59605. impostors.forEach(function (impostor) {
  59606. impostor.afterStep();
  59607. //update the ordered impostors array
  59608. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  59609. });
  59610. //check for collisions
  59611. var contact = this.world.contacts;
  59612. while (contact !== null) {
  59613. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  59614. contact = contact.next;
  59615. continue;
  59616. }
  59617. //is this body colliding with any other? get the impostor
  59618. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  59619. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  59620. if (!mainImpostor || !collidingImpostor) {
  59621. contact = contact.next;
  59622. continue;
  59623. }
  59624. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  59625. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  59626. contact = contact.next;
  59627. }
  59628. };
  59629. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  59630. var mass = impostor.physicsBody.massInfo.mass;
  59631. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  59632. };
  59633. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  59634. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  59635. this.applyImpulse(impostor, force, contactPoint);
  59636. };
  59637. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  59638. var _this = this;
  59639. //parent-child relationship. Does this impostor has a parent impostor?
  59640. if (impostor.parent) {
  59641. if (impostor.physicsBody) {
  59642. this.removePhysicsBody(impostor);
  59643. //TODO is that needed?
  59644. impostor.forceUpdate();
  59645. }
  59646. return;
  59647. }
  59648. if (impostor.isBodyInitRequired()) {
  59649. var bodyConfig = {
  59650. name: impostor.uniqueId,
  59651. //Oimo must have mass, also for static objects.
  59652. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  59653. size: [],
  59654. type: [],
  59655. pos: [],
  59656. rot: [],
  59657. move: impostor.getParam("mass") !== 0,
  59658. //Supporting older versions of Oimo
  59659. world: this.world
  59660. };
  59661. var impostors = [impostor];
  59662. var addToArray = function (parent) {
  59663. if (!parent.getChildMeshes)
  59664. return;
  59665. parent.getChildMeshes().forEach(function (m) {
  59666. if (m.physicsImpostor) {
  59667. impostors.push(m.physicsImpostor);
  59668. m.physicsImpostor._init();
  59669. }
  59670. });
  59671. };
  59672. addToArray(impostor.object);
  59673. var checkWithEpsilon_1 = function (value) {
  59674. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  59675. };
  59676. impostors.forEach(function (i) {
  59677. //get the correct bounding box
  59678. var oldQuaternion = i.object.rotationQuaternion;
  59679. var rot = new OIMO.Euler().setFromQuaternion({
  59680. x: impostor.object.rotationQuaternion.x,
  59681. y: impostor.object.rotationQuaternion.y,
  59682. z: impostor.object.rotationQuaternion.z,
  59683. s: impostor.object.rotationQuaternion.w
  59684. });
  59685. var extendSize = i.getObjectExtendSize();
  59686. if (i === impostor) {
  59687. var center = impostor.getObjectCenter();
  59688. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  59689. //Can also use Array.prototype.push.apply
  59690. bodyConfig.pos.push(center.x);
  59691. bodyConfig.pos.push(center.y);
  59692. bodyConfig.pos.push(center.z);
  59693. //tmp solution
  59694. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  59695. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  59696. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  59697. }
  59698. else {
  59699. bodyConfig.pos.push(i.object.position.x);
  59700. bodyConfig.pos.push(i.object.position.y);
  59701. bodyConfig.pos.push(i.object.position.z);
  59702. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  59703. bodyConfig.rot.push(0);
  59704. bodyConfig.rot.push(0);
  59705. bodyConfig.rot.push(0);
  59706. }
  59707. // register mesh
  59708. switch (i.type) {
  59709. case BABYLON.PhysicsImpostor.ParticleImpostor:
  59710. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  59711. case BABYLON.PhysicsImpostor.SphereImpostor:
  59712. var radiusX = extendSize.x;
  59713. var radiusY = extendSize.y;
  59714. var radiusZ = extendSize.z;
  59715. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  59716. bodyConfig.type.push('sphere');
  59717. //due to the way oimo works with compounds, add 3 times
  59718. bodyConfig.size.push(size);
  59719. bodyConfig.size.push(size);
  59720. bodyConfig.size.push(size);
  59721. break;
  59722. case BABYLON.PhysicsImpostor.CylinderImpostor:
  59723. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  59724. var sizeY = checkWithEpsilon_1(extendSize.y);
  59725. bodyConfig.type.push('cylinder');
  59726. bodyConfig.size.push(sizeX);
  59727. bodyConfig.size.push(sizeY);
  59728. //due to the way oimo works with compounds, add one more value.
  59729. bodyConfig.size.push(sizeY);
  59730. break;
  59731. case BABYLON.PhysicsImpostor.PlaneImpostor:
  59732. case BABYLON.PhysicsImpostor.BoxImpostor:
  59733. default:
  59734. var sizeX = checkWithEpsilon_1(extendSize.x);
  59735. var sizeY = checkWithEpsilon_1(extendSize.y);
  59736. var sizeZ = checkWithEpsilon_1(extendSize.z);
  59737. bodyConfig.type.push('box');
  59738. bodyConfig.size.push(sizeX);
  59739. bodyConfig.size.push(sizeY);
  59740. bodyConfig.size.push(sizeZ);
  59741. break;
  59742. }
  59743. //actually not needed, but hey...
  59744. i.object.rotationQuaternion = oldQuaternion;
  59745. });
  59746. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  59747. }
  59748. else {
  59749. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  59750. }
  59751. impostor.setDeltaPosition(this._tmpPositionVector);
  59752. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  59753. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  59754. };
  59755. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  59756. //impostor.physicsBody.dispose();
  59757. //Same as : (older oimo versions)
  59758. this.world.removeRigidBody(impostor.physicsBody);
  59759. };
  59760. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  59761. var mainBody = impostorJoint.mainImpostor.physicsBody;
  59762. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  59763. if (!mainBody || !connectedBody) {
  59764. return;
  59765. }
  59766. var jointData = impostorJoint.joint.jointData;
  59767. var options = jointData.nativeParams || {};
  59768. var type;
  59769. var nativeJointData = {
  59770. body1: mainBody,
  59771. body2: connectedBody,
  59772. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  59773. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  59774. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  59775. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  59776. min: options.min,
  59777. max: options.max,
  59778. collision: options.collision || jointData.collision,
  59779. spring: options.spring,
  59780. //supporting older version of Oimo
  59781. world: this.world
  59782. };
  59783. switch (impostorJoint.joint.type) {
  59784. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  59785. type = "jointBall";
  59786. break;
  59787. case BABYLON.PhysicsJoint.SpringJoint:
  59788. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  59789. var springData = jointData;
  59790. nativeJointData.min = springData.length || nativeJointData.min;
  59791. //Max should also be set, just make sure it is at least min
  59792. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  59793. case BABYLON.PhysicsJoint.DistanceJoint:
  59794. type = "jointDistance";
  59795. nativeJointData.max = jointData.maxDistance;
  59796. break;
  59797. case BABYLON.PhysicsJoint.PrismaticJoint:
  59798. type = "jointPrisme";
  59799. break;
  59800. case BABYLON.PhysicsJoint.SliderJoint:
  59801. type = "jointSlide";
  59802. break;
  59803. case BABYLON.PhysicsJoint.WheelJoint:
  59804. type = "jointWheel";
  59805. break;
  59806. case BABYLON.PhysicsJoint.HingeJoint:
  59807. default:
  59808. type = "jointHinge";
  59809. break;
  59810. }
  59811. nativeJointData.type = type;
  59812. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  59813. };
  59814. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  59815. //Bug in Oimo prevents us from disposing a joint in the playground
  59816. //joint.joint.physicsJoint.dispose();
  59817. //So we will bruteforce it!
  59818. try {
  59819. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  59820. }
  59821. catch (e) {
  59822. BABYLON.Tools.Warn(e);
  59823. }
  59824. };
  59825. OimoJSPlugin.prototype.isSupported = function () {
  59826. return OIMO !== undefined;
  59827. };
  59828. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  59829. if (!impostor.physicsBody.sleeping) {
  59830. //TODO check that
  59831. if (impostor.physicsBody.shapes.next) {
  59832. var parentShape = this._getLastShape(impostor.physicsBody);
  59833. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  59834. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  59835. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  59836. }
  59837. else {
  59838. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  59839. }
  59840. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  59841. impostor.object.rotationQuaternion.normalize();
  59842. }
  59843. };
  59844. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  59845. var body = impostor.physicsBody;
  59846. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  59847. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  59848. body.syncShapes();
  59849. body.awake();
  59850. };
  59851. OimoJSPlugin.prototype._getLastShape = function (body) {
  59852. var lastShape = body.shapes;
  59853. while (lastShape.next) {
  59854. lastShape = lastShape.next;
  59855. }
  59856. return lastShape;
  59857. };
  59858. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  59859. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  59860. };
  59861. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  59862. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  59863. };
  59864. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  59865. var v = impostor.physicsBody.linearVelocity;
  59866. if (!v)
  59867. return null;
  59868. return new BABYLON.Vector3(v.x, v.y, v.z);
  59869. };
  59870. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  59871. var v = impostor.physicsBody.angularVelocity;
  59872. if (!v)
  59873. return null;
  59874. return new BABYLON.Vector3(v.x, v.y, v.z);
  59875. };
  59876. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  59877. var staticBody = mass === 0;
  59878. //this will actually set the body's density and not its mass.
  59879. //But this is how oimo treats the mass variable.
  59880. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  59881. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  59882. };
  59883. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  59884. return impostor.physicsBody.shapes.density;
  59885. };
  59886. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  59887. return impostor.physicsBody.shapes.friction;
  59888. };
  59889. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  59890. impostor.physicsBody.shapes.friction = friction;
  59891. };
  59892. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  59893. return impostor.physicsBody.shapes.restitution;
  59894. };
  59895. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  59896. impostor.physicsBody.shapes.restitution = restitution;
  59897. };
  59898. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  59899. impostor.physicsBody.sleep();
  59900. };
  59901. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  59902. impostor.physicsBody.awake();
  59903. };
  59904. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  59905. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  59906. if (minDistance !== void 0) {
  59907. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  59908. }
  59909. };
  59910. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  59911. //TODO separate rotational and transational motors.
  59912. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  59913. if (motor) {
  59914. motor.setMotor(speed, maxForce);
  59915. }
  59916. };
  59917. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  59918. //TODO separate rotational and transational motors.
  59919. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  59920. if (motor) {
  59921. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  59922. }
  59923. };
  59924. OimoJSPlugin.prototype._getDebugMaterial = function (scene) {
  59925. if (!this._debugMaterial) {
  59926. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59927. this._debugMaterial.wireframe = true;
  59928. }
  59929. return this._debugMaterial;
  59930. };
  59931. OimoJSPlugin.prototype._getDebugBoxMesh = function (scene) {
  59932. if (!this._debugBoxMesh) {
  59933. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59934. this._debugBoxMesh.renderingGroupId = 1;
  59935. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59936. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59937. scene.removeMesh(this._debugBoxMesh);
  59938. }
  59939. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59940. };
  59941. OimoJSPlugin.prototype._getDebugSphereMesh = function (scene) {
  59942. if (!this._debugSphereMesh) {
  59943. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59944. this._debugSphereMesh.renderingGroupId = 1;
  59945. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59946. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59947. scene.removeMesh(this._debugSphereMesh);
  59948. }
  59949. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59950. };
  59951. OimoJSPlugin.prototype.getDebugMesh = function (impostor, scene) {
  59952. var body = impostor.physicsBody;
  59953. var shape = body.shapes;
  59954. var mesh;
  59955. if (shape.halfWidth) {
  59956. mesh = this._getDebugBoxMesh(scene);
  59957. mesh.scaling.x = shape.halfWidth * 2;
  59958. mesh.scaling.y = shape.halfHeight * 2;
  59959. mesh.scaling.z = shape.halfDepth * 2;
  59960. }
  59961. else if (shape.radius) {
  59962. mesh = this._getDebugSphereMesh(scene);
  59963. mesh.scaling.x = shape.radius * 2;
  59964. mesh.scaling.y = shape.radius * 2;
  59965. mesh.scaling.z = shape.radius * 2;
  59966. }
  59967. return mesh;
  59968. };
  59969. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  59970. var body = impostor.physicsBody;
  59971. mesh.position.x = body.position.x;
  59972. mesh.position.y = body.position.y;
  59973. mesh.position.z = body.position.z;
  59974. mesh.rotationQuaternion.x = body.orientation.x;
  59975. mesh.rotationQuaternion.y = body.orientation.y;
  59976. mesh.rotationQuaternion.z = body.orientation.z;
  59977. mesh.rotationQuaternion.w = body.orientation.s;
  59978. };
  59979. OimoJSPlugin.prototype.dispose = function () {
  59980. if (this._debugBoxMesh) {
  59981. this._debugBoxMesh.dispose();
  59982. }
  59983. if (this._debugSphereMesh) {
  59984. this._debugSphereMesh.dispose();
  59985. }
  59986. if (this._debugMaterial) {
  59987. this._debugMaterial.dispose();
  59988. }
  59989. this.world.clear();
  59990. };
  59991. return OimoJSPlugin;
  59992. }());
  59993. BABYLON.OimoJSPlugin = OimoJSPlugin;
  59994. })(BABYLON || (BABYLON = {}));
  59995. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  59996. var BABYLON;
  59997. (function (BABYLON) {
  59998. var Internals;
  59999. (function (Internals) {
  60000. /*
  60001. * Based on jsTGALoader - Javascript loader for TGA file
  60002. * By Vincent Thibault
  60003. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  60004. */
  60005. var TGATools = (function () {
  60006. function TGATools() {
  60007. }
  60008. TGATools.GetTGAHeader = function (data) {
  60009. var offset = 0;
  60010. var header = {
  60011. id_length: data[offset++],
  60012. colormap_type: data[offset++],
  60013. image_type: data[offset++],
  60014. colormap_index: data[offset++] | data[offset++] << 8,
  60015. colormap_length: data[offset++] | data[offset++] << 8,
  60016. colormap_size: data[offset++],
  60017. origin: [
  60018. data[offset++] | data[offset++] << 8,
  60019. data[offset++] | data[offset++] << 8
  60020. ],
  60021. width: data[offset++] | data[offset++] << 8,
  60022. height: data[offset++] | data[offset++] << 8,
  60023. pixel_size: data[offset++],
  60024. flags: data[offset++]
  60025. };
  60026. return header;
  60027. };
  60028. TGATools.UploadContent = function (gl, data) {
  60029. // Not enough data to contain header ?
  60030. if (data.length < 19) {
  60031. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  60032. return;
  60033. }
  60034. // Read Header
  60035. var offset = 18;
  60036. var header = TGATools.GetTGAHeader(data);
  60037. // Assume it's a valid Targa file.
  60038. if (header.id_length + offset > data.length) {
  60039. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  60040. return;
  60041. }
  60042. // Skip not needed data
  60043. offset += header.id_length;
  60044. var use_rle = false;
  60045. var use_pal = false;
  60046. var use_rgb = false;
  60047. var use_grey = false;
  60048. // Get some informations.
  60049. switch (header.image_type) {
  60050. case TGATools._TYPE_RLE_INDEXED:
  60051. use_rle = true;
  60052. case TGATools._TYPE_INDEXED:
  60053. use_pal = true;
  60054. break;
  60055. case TGATools._TYPE_RLE_RGB:
  60056. use_rle = true;
  60057. case TGATools._TYPE_RGB:
  60058. use_rgb = true;
  60059. break;
  60060. case TGATools._TYPE_RLE_GREY:
  60061. use_rle = true;
  60062. case TGATools._TYPE_GREY:
  60063. use_grey = true;
  60064. break;
  60065. }
  60066. var pixel_data;
  60067. var numAlphaBits = header.flags & 0xf;
  60068. var pixel_size = header.pixel_size >> 3;
  60069. var pixel_total = header.width * header.height * pixel_size;
  60070. // Read palettes
  60071. var palettes;
  60072. if (use_pal) {
  60073. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  60074. }
  60075. // Read LRE
  60076. if (use_rle) {
  60077. pixel_data = new Uint8Array(pixel_total);
  60078. var c, count, i;
  60079. var localOffset = 0;
  60080. var pixels = new Uint8Array(pixel_size);
  60081. while (offset < pixel_total && localOffset < pixel_total) {
  60082. c = data[offset++];
  60083. count = (c & 0x7f) + 1;
  60084. // RLE pixels
  60085. if (c & 0x80) {
  60086. // Bind pixel tmp array
  60087. for (i = 0; i < pixel_size; ++i) {
  60088. pixels[i] = data[offset++];
  60089. }
  60090. // Copy pixel array
  60091. for (i = 0; i < count; ++i) {
  60092. pixel_data.set(pixels, localOffset + i * pixel_size);
  60093. }
  60094. localOffset += pixel_size * count;
  60095. }
  60096. else {
  60097. count *= pixel_size;
  60098. for (i = 0; i < count; ++i) {
  60099. pixel_data[localOffset + i] = data[offset++];
  60100. }
  60101. localOffset += count;
  60102. }
  60103. }
  60104. }
  60105. else {
  60106. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  60107. }
  60108. // Load to texture
  60109. var x_start, y_start, x_step, y_step, y_end, x_end;
  60110. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  60111. default:
  60112. case TGATools._ORIGIN_UL:
  60113. x_start = 0;
  60114. x_step = 1;
  60115. x_end = header.width;
  60116. y_start = 0;
  60117. y_step = 1;
  60118. y_end = header.height;
  60119. break;
  60120. case TGATools._ORIGIN_BL:
  60121. x_start = 0;
  60122. x_step = 1;
  60123. x_end = header.width;
  60124. y_start = header.height - 1;
  60125. y_step = -1;
  60126. y_end = -1;
  60127. break;
  60128. case TGATools._ORIGIN_UR:
  60129. x_start = header.width - 1;
  60130. x_step = -1;
  60131. x_end = -1;
  60132. y_start = 0;
  60133. y_step = 1;
  60134. y_end = header.height;
  60135. break;
  60136. case TGATools._ORIGIN_BR:
  60137. x_start = header.width - 1;
  60138. x_step = -1;
  60139. x_end = -1;
  60140. y_start = header.height - 1;
  60141. y_step = -1;
  60142. y_end = -1;
  60143. break;
  60144. }
  60145. // Load the specify method
  60146. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  60147. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  60148. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  60149. };
  60150. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60151. var image = pixel_data, colormap = palettes;
  60152. var width = header.width, height = header.height;
  60153. var color, i = 0, x, y;
  60154. var imageData = new Uint8Array(width * height * 4);
  60155. for (y = y_start; y !== y_end; y += y_step) {
  60156. for (x = x_start; x !== x_end; x += x_step, i++) {
  60157. color = image[i];
  60158. imageData[(x + width * y) * 4 + 3] = 255;
  60159. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  60160. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  60161. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  60162. }
  60163. }
  60164. return imageData;
  60165. };
  60166. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60167. var image = pixel_data;
  60168. var width = header.width, height = header.height;
  60169. var color, i = 0, x, y;
  60170. var imageData = new Uint8Array(width * height * 4);
  60171. for (y = y_start; y !== y_end; y += y_step) {
  60172. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60173. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  60174. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  60175. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  60176. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  60177. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  60178. }
  60179. }
  60180. return imageData;
  60181. };
  60182. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60183. var image = pixel_data;
  60184. var width = header.width, height = header.height;
  60185. var i = 0, x, y;
  60186. var imageData = new Uint8Array(width * height * 4);
  60187. for (y = y_start; y !== y_end; y += y_step) {
  60188. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  60189. imageData[(x + width * y) * 4 + 3] = 255;
  60190. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60191. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60192. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60193. }
  60194. }
  60195. return imageData;
  60196. };
  60197. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60198. var image = pixel_data;
  60199. var width = header.width, height = header.height;
  60200. var i = 0, x, y;
  60201. var imageData = new Uint8Array(width * height * 4);
  60202. for (y = y_start; y !== y_end; y += y_step) {
  60203. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  60204. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60205. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60206. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60207. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  60208. }
  60209. }
  60210. return imageData;
  60211. };
  60212. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60213. var image = pixel_data;
  60214. var width = header.width, height = header.height;
  60215. var color, i = 0, x, y;
  60216. var imageData = new Uint8Array(width * height * 4);
  60217. for (y = y_start; y !== y_end; y += y_step) {
  60218. for (x = x_start; x !== x_end; x += x_step, i++) {
  60219. color = image[i];
  60220. imageData[(x + width * y) * 4 + 0] = color;
  60221. imageData[(x + width * y) * 4 + 1] = color;
  60222. imageData[(x + width * y) * 4 + 2] = color;
  60223. imageData[(x + width * y) * 4 + 3] = 255;
  60224. }
  60225. }
  60226. return imageData;
  60227. };
  60228. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60229. var image = pixel_data;
  60230. var width = header.width, height = header.height;
  60231. var i = 0, x, y;
  60232. var imageData = new Uint8Array(width * height * 4);
  60233. for (y = y_start; y !== y_end; y += y_step) {
  60234. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60235. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  60236. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  60237. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60238. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  60239. }
  60240. }
  60241. return imageData;
  60242. };
  60243. return TGATools;
  60244. }());
  60245. TGATools._TYPE_NO_DATA = 0;
  60246. TGATools._TYPE_INDEXED = 1;
  60247. TGATools._TYPE_RGB = 2;
  60248. TGATools._TYPE_GREY = 3;
  60249. TGATools._TYPE_RLE_INDEXED = 9;
  60250. TGATools._TYPE_RLE_RGB = 10;
  60251. TGATools._TYPE_RLE_GREY = 11;
  60252. TGATools._ORIGIN_MASK = 0x30;
  60253. TGATools._ORIGIN_SHIFT = 0x04;
  60254. TGATools._ORIGIN_BL = 0x00;
  60255. TGATools._ORIGIN_BR = 0x01;
  60256. TGATools._ORIGIN_UL = 0x02;
  60257. TGATools._ORIGIN_UR = 0x03;
  60258. Internals.TGATools = TGATools;
  60259. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60260. })(BABYLON || (BABYLON = {}));
  60261. //# sourceMappingURL=babylon.tga.js.map
  60262. var BABYLON;
  60263. (function (BABYLON) {
  60264. var Internals;
  60265. (function (Internals) {
  60266. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  60267. // All values and structures referenced from:
  60268. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  60269. var DDS_MAGIC = 0x20534444;
  60270. 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;
  60271. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  60272. 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;
  60273. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  60274. function FourCCToInt32(value) {
  60275. return value.charCodeAt(0) +
  60276. (value.charCodeAt(1) << 8) +
  60277. (value.charCodeAt(2) << 16) +
  60278. (value.charCodeAt(3) << 24);
  60279. }
  60280. function Int32ToFourCC(value) {
  60281. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  60282. }
  60283. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  60284. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  60285. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  60286. var FOURCC_DX10 = FourCCToInt32("DX10");
  60287. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  60288. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  60289. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  60290. var headerLengthInt = 31; // The header length in 32 bit ints
  60291. // Offsets into the header array
  60292. var off_magic = 0;
  60293. var off_size = 1;
  60294. var off_flags = 2;
  60295. var off_height = 3;
  60296. var off_width = 4;
  60297. var off_mipmapCount = 7;
  60298. var off_pfFlags = 20;
  60299. var off_pfFourCC = 21;
  60300. var off_RGBbpp = 22;
  60301. var off_RMask = 23;
  60302. var off_GMask = 24;
  60303. var off_BMask = 25;
  60304. var off_AMask = 26;
  60305. var off_caps1 = 27;
  60306. var off_caps2 = 28;
  60307. var off_caps3 = 29;
  60308. var off_caps4 = 30;
  60309. var off_dxgiFormat = 32;
  60310. ;
  60311. var DDSTools = (function () {
  60312. function DDSTools() {
  60313. }
  60314. DDSTools.GetDDSInfo = function (arrayBuffer) {
  60315. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  60316. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  60317. var mipmapCount = 1;
  60318. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  60319. mipmapCount = Math.max(1, header[off_mipmapCount]);
  60320. }
  60321. var fourCC = header[off_pfFourCC];
  60322. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  60323. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60324. switch (fourCC) {
  60325. case FOURCC_D3DFMT_R16G16B16A16F:
  60326. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60327. break;
  60328. case FOURCC_D3DFMT_R32G32B32A32F:
  60329. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60330. break;
  60331. case FOURCC_DX10:
  60332. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  60333. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60334. break;
  60335. }
  60336. }
  60337. return {
  60338. width: header[off_width],
  60339. height: header[off_height],
  60340. mipmapCount: mipmapCount,
  60341. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  60342. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  60343. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  60344. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  60345. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  60346. dxgiFormat: dxgiFormat,
  60347. textureType: textureType
  60348. };
  60349. };
  60350. DDSTools._ToHalfFloat = function (value) {
  60351. if (!DDSTools._FloatView) {
  60352. DDSTools._FloatView = new Float32Array(1);
  60353. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  60354. }
  60355. DDSTools._FloatView[0] = value;
  60356. var x = DDSTools._Int32View[0];
  60357. var bits = (x >> 16) & 0x8000; /* Get the sign */
  60358. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  60359. var e = (x >> 23) & 0xff; /* Using int is faster here */
  60360. /* If zero, or denormal, or exponent underflows too much for a denormal
  60361. * half, return signed zero. */
  60362. if (e < 103) {
  60363. return bits;
  60364. }
  60365. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  60366. if (e > 142) {
  60367. bits |= 0x7c00;
  60368. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  60369. * not Inf, so make sure we set one mantissa bit too. */
  60370. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  60371. return bits;
  60372. }
  60373. /* If exponent underflows but not too much, return a denormal */
  60374. if (e < 113) {
  60375. m |= 0x0800;
  60376. /* Extra rounding may overflow and set mantissa to 0 and exponent
  60377. * to 1, which is OK. */
  60378. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  60379. return bits;
  60380. }
  60381. bits |= ((e - 112) << 10) | (m >> 1);
  60382. bits += m & 1;
  60383. return bits;
  60384. };
  60385. DDSTools._FromHalfFloat = function (value) {
  60386. var s = (value & 0x8000) >> 15;
  60387. var e = (value & 0x7C00) >> 10;
  60388. var f = value & 0x03FF;
  60389. if (e === 0) {
  60390. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  60391. }
  60392. else if (e == 0x1F) {
  60393. return f ? NaN : ((s ? -1 : 1) * Infinity);
  60394. }
  60395. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  60396. };
  60397. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60398. var destArray = new Float32Array(dataLength);
  60399. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  60400. var index = 0;
  60401. for (var y = 0; y < height; y++) {
  60402. for (var x = 0; x < width; x++) {
  60403. var srcPos = (x + y * width) * 4;
  60404. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  60405. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  60406. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  60407. if (DDSTools.StoreLODInAlphaChannel) {
  60408. destArray[index + 3] = lod;
  60409. }
  60410. else {
  60411. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  60412. }
  60413. index += 4;
  60414. }
  60415. }
  60416. return destArray;
  60417. };
  60418. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60419. if (DDSTools.StoreLODInAlphaChannel) {
  60420. var destArray = new Uint16Array(dataLength);
  60421. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  60422. var index = 0;
  60423. for (var y = 0; y < height; y++) {
  60424. for (var x = 0; x < width; x++) {
  60425. var srcPos = (x + y * width) * 4;
  60426. destArray[index] = srcData[srcPos];
  60427. destArray[index + 1] = srcData[srcPos + 1];
  60428. destArray[index + 2] = srcData[srcPos + 2];
  60429. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  60430. index += 4;
  60431. }
  60432. }
  60433. return destArray;
  60434. }
  60435. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  60436. };
  60437. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60438. if (DDSTools.StoreLODInAlphaChannel) {
  60439. var destArray = new Float32Array(dataLength);
  60440. var srcData = new Float32Array(arrayBuffer, dataOffset);
  60441. var index = 0;
  60442. for (var y = 0; y < height; y++) {
  60443. for (var x = 0; x < width; x++) {
  60444. var srcPos = (x + y * width) * 4;
  60445. destArray[index] = srcData[srcPos];
  60446. destArray[index + 1] = srcData[srcPos + 1];
  60447. destArray[index + 2] = srcData[srcPos + 2];
  60448. destArray[index + 3] = lod;
  60449. index += 4;
  60450. }
  60451. }
  60452. return destArray;
  60453. }
  60454. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  60455. };
  60456. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60457. var byteArray = new Uint8Array(dataLength);
  60458. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  60459. var index = 0;
  60460. for (var y = 0; y < height; y++) {
  60461. for (var x = 0; x < width; x++) {
  60462. var srcPos = (x + y * width) * 4;
  60463. byteArray[index] = srcData[srcPos + 2];
  60464. byteArray[index + 1] = srcData[srcPos + 1];
  60465. byteArray[index + 2] = srcData[srcPos];
  60466. byteArray[index + 3] = srcData[srcPos + 3];
  60467. index += 4;
  60468. }
  60469. }
  60470. return byteArray;
  60471. };
  60472. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60473. var byteArray = new Uint8Array(dataLength);
  60474. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  60475. var index = 0;
  60476. for (var y = 0; y < height; y++) {
  60477. for (var x = 0; x < width; x++) {
  60478. var srcPos = (x + y * width) * 3;
  60479. byteArray[index] = srcData[srcPos + 2];
  60480. byteArray[index + 1] = srcData[srcPos + 1];
  60481. byteArray[index + 2] = srcData[srcPos];
  60482. index += 3;
  60483. }
  60484. }
  60485. return byteArray;
  60486. };
  60487. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60488. var byteArray = new Uint8Array(dataLength);
  60489. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  60490. var index = 0;
  60491. for (var y = 0; y < height; y++) {
  60492. for (var x = 0; x < width; x++) {
  60493. var srcPos = (x + y * width);
  60494. byteArray[index] = srcData[srcPos];
  60495. index++;
  60496. }
  60497. }
  60498. return byteArray;
  60499. };
  60500. DDSTools.UploadDDSLevels = function (engine, arrayBuffer, info, loadMipmaps, faces) {
  60501. var gl = engine._gl;
  60502. var ext = engine.getCaps().s3tc;
  60503. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  60504. if (header[off_magic] != DDS_MAGIC) {
  60505. BABYLON.Tools.Error("Invalid magic number in DDS header");
  60506. return;
  60507. }
  60508. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  60509. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  60510. return;
  60511. }
  60512. if (info.isCompressed && !ext) {
  60513. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  60514. return;
  60515. }
  60516. var bpp = header[off_RGBbpp];
  60517. dataOffset = header[off_size] + 4;
  60518. var computeFormats = false;
  60519. if (info.isFourCC) {
  60520. fourCC = header[off_pfFourCC];
  60521. switch (fourCC) {
  60522. case FOURCC_DXT1:
  60523. blockBytes = 8;
  60524. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  60525. break;
  60526. case FOURCC_DXT3:
  60527. blockBytes = 16;
  60528. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  60529. break;
  60530. case FOURCC_DXT5:
  60531. blockBytes = 16;
  60532. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  60533. break;
  60534. case FOURCC_D3DFMT_R16G16B16A16F:
  60535. computeFormats = true;
  60536. break;
  60537. case FOURCC_D3DFMT_R32G32B32A32F:
  60538. computeFormats = true;
  60539. break;
  60540. case FOURCC_DX10:
  60541. // There is an additionnal header so dataOffset need to be changed
  60542. dataOffset += 5 * 4; // 5 uints
  60543. if (info.dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  60544. computeFormats = true;
  60545. break;
  60546. }
  60547. default:
  60548. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  60549. return;
  60550. }
  60551. }
  60552. if (computeFormats) {
  60553. format = engine._getWebGLTextureType(info.textureType);
  60554. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  60555. }
  60556. mipmapCount = 1;
  60557. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  60558. mipmapCount = Math.max(1, header[off_mipmapCount]);
  60559. }
  60560. for (var face = 0; face < faces; face++) {
  60561. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  60562. width = header[off_width];
  60563. height = header[off_height];
  60564. for (i = 0; i < mipmapCount; ++i) {
  60565. if (!info.isCompressed && info.isFourCC) {
  60566. dataLength = width * height * 4;
  60567. var floatArray;
  60568. if (bpp === 128) {
  60569. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60570. }
  60571. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  60572. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60573. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60574. format = engine._getWebGLTextureType(info.textureType);
  60575. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  60576. }
  60577. else {
  60578. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60579. }
  60580. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  60581. }
  60582. else if (info.isRGB) {
  60583. if (bpp === 24) {
  60584. dataLength = width * height * 3;
  60585. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60586. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  60587. }
  60588. else {
  60589. dataLength = width * height * 4;
  60590. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60591. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  60592. }
  60593. }
  60594. else if (info.isLuminance) {
  60595. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  60596. var unpaddedRowSize = width;
  60597. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  60598. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  60599. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60600. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  60601. }
  60602. else {
  60603. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  60604. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  60605. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  60606. }
  60607. dataOffset += width * height * (bpp / 8);
  60608. width *= 0.5;
  60609. height *= 0.5;
  60610. width = Math.max(1.0, width);
  60611. height = Math.max(1.0, height);
  60612. }
  60613. }
  60614. };
  60615. return DDSTools;
  60616. }());
  60617. DDSTools.StoreLODInAlphaChannel = false;
  60618. Internals.DDSTools = DDSTools;
  60619. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60620. })(BABYLON || (BABYLON = {}));
  60621. //# sourceMappingURL=babylon.dds.js.map
  60622. var BABYLON;
  60623. (function (BABYLON) {
  60624. var Internals;
  60625. (function (Internals) {
  60626. /**
  60627. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  60628. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  60629. */
  60630. var KhronosTextureContainer = (function () {
  60631. /**
  60632. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  60633. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  60634. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  60635. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  60636. */
  60637. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  60638. this.arrayBuffer = arrayBuffer;
  60639. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  60640. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  60641. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  60642. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  60643. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  60644. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  60645. BABYLON.Tools.Error("texture missing KTX identifier");
  60646. return;
  60647. }
  60648. // load the reset of the header in native 32 bit int
  60649. var header = new Int32Array(this.arrayBuffer, 12, 13);
  60650. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  60651. var oppositeEndianess = header[0] === 0x01020304;
  60652. // read all the header elements in order they exist in the file, without modification (sans endainness)
  60653. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  60654. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  60655. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  60656. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  60657. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  60658. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  60659. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  60660. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  60661. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  60662. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  60663. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  60664. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  60665. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  60666. if (this.glType !== 0) {
  60667. BABYLON.Tools.Error("only compressed formats currently supported");
  60668. return;
  60669. }
  60670. else {
  60671. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  60672. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  60673. }
  60674. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  60675. BABYLON.Tools.Error("only 2D textures currently supported");
  60676. return;
  60677. }
  60678. if (this.numberOfArrayElements !== 0) {
  60679. BABYLON.Tools.Error("texture arrays not currently supported");
  60680. return;
  60681. }
  60682. if (this.numberOfFaces !== facesExpected) {
  60683. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  60684. return;
  60685. }
  60686. // we now have a completely validated file, so could use existence of loadType as success
  60687. // would need to make this more elaborate & adjust checks above to support more than one load type
  60688. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  60689. }
  60690. // not as fast hardware based, but will probably never need to use
  60691. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  60692. return ((val & 0xFF) << 24)
  60693. | ((val & 0xFF00) << 8)
  60694. | ((val >> 8) & 0xFF00)
  60695. | ((val >> 24) & 0xFF);
  60696. };
  60697. /**
  60698. * It is assumed that the texture has already been created & is currently bound
  60699. */
  60700. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  60701. switch (this.loadType) {
  60702. case KhronosTextureContainer.COMPRESSED_2D:
  60703. this._upload2DCompressedLevels(gl, loadMipmaps);
  60704. break;
  60705. case KhronosTextureContainer.TEX_2D:
  60706. case KhronosTextureContainer.COMPRESSED_3D:
  60707. case KhronosTextureContainer.TEX_3D:
  60708. }
  60709. };
  60710. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  60711. // initialize width & height for level 1
  60712. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  60713. var width = this.pixelWidth;
  60714. var height = this.pixelHeight;
  60715. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  60716. for (var level = 0; level < mipmapCount; level++) {
  60717. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  60718. for (var face = 0; face < this.numberOfFaces; face++) {
  60719. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  60720. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  60721. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  60722. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  60723. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  60724. }
  60725. width = Math.max(1.0, width * 0.5);
  60726. height = Math.max(1.0, height * 0.5);
  60727. }
  60728. };
  60729. return KhronosTextureContainer;
  60730. }());
  60731. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  60732. // load types
  60733. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  60734. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  60735. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  60736. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  60737. Internals.KhronosTextureContainer = KhronosTextureContainer;
  60738. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60739. })(BABYLON || (BABYLON = {}));
  60740. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  60741. var BABYLON;
  60742. (function (BABYLON) {
  60743. var DynamicFloatArrayElementInfo = (function () {
  60744. function DynamicFloatArrayElementInfo() {
  60745. }
  60746. return DynamicFloatArrayElementInfo;
  60747. }());
  60748. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  60749. /**
  60750. * 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.
  60751. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  60752. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  60753. * 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.
  60754. * 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.
  60755. * 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".
  60756. */
  60757. var DynamicFloatArray = (function () {
  60758. /**
  60759. * Construct an instance of the dynamic float array
  60760. * @param stride size of one element in float (i.e. not bytes!)
  60761. * @param initialElementCount the number of available entries at construction
  60762. */
  60763. function DynamicFloatArray(stride, initialElementCount) {
  60764. this.compareValueOffset = null;
  60765. this.sortingAscending = true;
  60766. this._stride = stride;
  60767. this.buffer = new Float32Array(stride * initialElementCount);
  60768. this._lastUsed = 0;
  60769. this._firstFree = 0;
  60770. this._allEntries = new Array(initialElementCount);
  60771. this._freeEntries = new Array(initialElementCount);
  60772. for (var i = 0; i < initialElementCount; i++) {
  60773. var element = new DynamicFloatArrayElementInfo();
  60774. element.offset = i * stride;
  60775. this._allEntries[i] = element;
  60776. this._freeEntries[initialElementCount - i - 1] = element;
  60777. }
  60778. }
  60779. /**
  60780. * Allocate an element in the array.
  60781. * @return the element info instance that contains the offset into the main buffer of the element's location.
  60782. * Beware, this offset may change when you call pack()
  60783. */
  60784. DynamicFloatArray.prototype.allocElement = function () {
  60785. if (this._freeEntries.length === 0) {
  60786. this._growBuffer();
  60787. }
  60788. var el = this._freeEntries.pop();
  60789. this._lastUsed = Math.max(el.offset, this._lastUsed);
  60790. if (el.offset === this._firstFree) {
  60791. if (this._freeEntries.length > 0) {
  60792. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  60793. }
  60794. else {
  60795. this._firstFree += this._stride;
  60796. }
  60797. }
  60798. return el;
  60799. };
  60800. /**
  60801. * Free the element corresponding to the given element info
  60802. * @param elInfo the element that describe the allocated element
  60803. */
  60804. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  60805. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  60806. this._freeEntries.push(elInfo);
  60807. };
  60808. /**
  60809. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  60810. * 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().
  60811. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  60812. */
  60813. DynamicFloatArray.prototype.pack = function () {
  60814. // no free slot? no need to pack
  60815. if (this._freeEntries.length === 0) {
  60816. return this.buffer;
  60817. }
  60818. // If the buffer is already packed the last used will always be lower than the first free
  60819. // 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.
  60820. if (this._lastUsed < this._firstFree) {
  60821. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  60822. return elementsBuffer_1;
  60823. }
  60824. var s = this._stride;
  60825. // 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
  60826. var lastFree = new DynamicFloatArrayElementInfo();
  60827. lastFree.offset = this.totalElementCount * s;
  60828. this._freeEntries.push(lastFree);
  60829. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  60830. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  60831. var firstFreeSlotOffset = sortedFree[0].offset;
  60832. var freeZoneSize = 1;
  60833. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  60834. var prevOffset = sortedFree[0].offset;
  60835. for (var i = 1; i < sortedFree.length; i++) {
  60836. // 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
  60837. if (firstFreeSlotOffset >= occupiedZoneSize) {
  60838. break;
  60839. }
  60840. var curFree = sortedFree[i];
  60841. var curOffset = curFree.offset;
  60842. // Compute the distance between this offset and the previous
  60843. var distance = curOffset - prevOffset;
  60844. // If the distance is the stride size, they are adjacent, it good, move to the next
  60845. if (distance === s) {
  60846. // Free zone is one element bigger
  60847. ++freeZoneSize;
  60848. // as we're about to iterate to the next, the cur becomes the previous...
  60849. prevOffset = curOffset;
  60850. continue;
  60851. }
  60852. // Distance is bigger, which means there's x element between the previous free and this one
  60853. var usedRange = (distance / s) - 1;
  60854. // Two cases the free zone is smaller than the data to move or bigger
  60855. // Copy what can fit in the free zone
  60856. var curMoveOffset = curOffset - s;
  60857. var copyCount = Math.min(freeZoneSize, usedRange);
  60858. for (var j = 0; j < copyCount; j++) {
  60859. var freeI = firstFreeSlotOffset / s;
  60860. var curI = curMoveOffset / s;
  60861. var moveEl = sortedAll[curI];
  60862. this._moveElement(moveEl, firstFreeSlotOffset);
  60863. var replacedEl = sortedAll[freeI];
  60864. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  60865. replacedEl.offset = curMoveOffset;
  60866. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  60867. sortedAll[freeI] = moveEl;
  60868. sortedAll[curI] = replacedEl;
  60869. curMoveOffset -= s;
  60870. firstFreeSlotOffset += s;
  60871. }
  60872. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  60873. if (freeZoneSize <= usedRange) {
  60874. firstFreeSlotOffset = curMoveOffset + s;
  60875. freeZoneSize = 1 + copyCount;
  60876. }
  60877. else {
  60878. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  60879. }
  60880. // as we're about to iterate to the next, the cur becomes the previous...
  60881. prevOffset = curOffset;
  60882. }
  60883. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  60884. this._lastUsed = firstFreeSlotOffset - s;
  60885. this._firstFree = firstFreeSlotOffset;
  60886. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  60887. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  60888. this._allEntries = sortedAll;
  60889. return elementsBuffer;
  60890. };
  60891. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  60892. for (var i = 0; i < this._stride; i++) {
  60893. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  60894. }
  60895. element.offset = destOffset;
  60896. };
  60897. DynamicFloatArray.prototype._growBuffer = function () {
  60898. // Allocate the new buffer with 50% more entries, copy the content of the current one
  60899. var newElCount = Math.floor(this.totalElementCount * 1.5);
  60900. var newBuffer = new Float32Array(newElCount * this._stride);
  60901. newBuffer.set(this.buffer);
  60902. var curCount = this.totalElementCount;
  60903. var addedCount = newElCount - this.totalElementCount;
  60904. for (var i = 0; i < addedCount; i++) {
  60905. var element = new DynamicFloatArrayElementInfo();
  60906. element.offset = (curCount + i) * this.stride;
  60907. this._allEntries.push(element);
  60908. this._freeEntries[addedCount - i - 1] = element;
  60909. }
  60910. this._firstFree = curCount * this.stride;
  60911. this.buffer = newBuffer;
  60912. };
  60913. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  60914. /**
  60915. * Get the total count of entries that can fit in the current buffer
  60916. * @returns the elements count
  60917. */
  60918. get: function () {
  60919. return this._allEntries.length;
  60920. },
  60921. enumerable: true,
  60922. configurable: true
  60923. });
  60924. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  60925. /**
  60926. * Get the count of free entries that can still be allocated without resizing the buffer
  60927. * @returns the free elements count
  60928. */
  60929. get: function () {
  60930. return this._freeEntries.length;
  60931. },
  60932. enumerable: true,
  60933. configurable: true
  60934. });
  60935. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  60936. /**
  60937. * Get the count of allocated elements
  60938. * @returns the allocated elements count
  60939. */
  60940. get: function () {
  60941. return this._allEntries.length - this._freeEntries.length;
  60942. },
  60943. enumerable: true,
  60944. configurable: true
  60945. });
  60946. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  60947. /**
  60948. * Return the size of one element in float
  60949. * @returns the size in float
  60950. */
  60951. get: function () {
  60952. return this._stride;
  60953. },
  60954. enumerable: true,
  60955. configurable: true
  60956. });
  60957. DynamicFloatArray.prototype.sort = function () {
  60958. var _this = this;
  60959. if (!this.compareValueOffset) {
  60960. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  60961. }
  60962. var count = this.usedElementCount;
  60963. // Do we have to (re)create the sort table?
  60964. if (!this._sortTable || this._sortTable.length < count) {
  60965. // 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...
  60966. var newCount = Math.min(this.totalElementCount, count * 2);
  60967. this._sortTable = new Array(newCount);
  60968. }
  60969. if (!this._sortedTable || this._sortedTable.length !== count) {
  60970. this._sortedTable = new Array(count);
  60971. }
  60972. // Because, you know...
  60973. this.pack();
  60974. //let stride = this.stride;
  60975. //for (let i = 0; i < count; i++) {
  60976. // let si = this._sortTable[i];
  60977. // if (!si) {
  60978. // si = new SortInfo();
  60979. // this._sortTable[i] = si;
  60980. // }
  60981. // si.entry = this._allEntries[i];
  60982. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  60983. // si.swapedOffset = null;
  60984. // this._sortedTable[i] = si;
  60985. //}
  60986. var curOffset = 0;
  60987. var stride = this.stride;
  60988. for (var i = 0; i < count; i++, curOffset += stride) {
  60989. var si = this._sortTable[i];
  60990. if (!si) {
  60991. si = new SortInfo();
  60992. this._sortTable[i] = si;
  60993. }
  60994. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  60995. si.offset = curOffset;
  60996. si.swapedOffset = null;
  60997. this._sortedTable[i] = si;
  60998. }
  60999. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  61000. if (this.sortingAscending) {
  61001. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  61002. }
  61003. else {
  61004. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  61005. }
  61006. var swapElements = function (src, dst) {
  61007. for (var i = 0; i < stride; i++) {
  61008. var tps = _this.buffer[dst + i];
  61009. _this.buffer[dst + i] = _this.buffer[src + i];
  61010. _this.buffer[src + i] = tps;
  61011. }
  61012. };
  61013. // 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:
  61014. // 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),
  61015. // and I still want something with a good algorithm complexity.
  61016. // 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,
  61017. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  61018. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  61019. // 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
  61020. // until we find a SortInfo object without a swapedOffset which means we got the right location
  61021. // 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
  61022. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  61023. for (var i = 0; i < count; i++) {
  61024. // Get the element to move
  61025. var sourceSI = this._sortedTable[i];
  61026. var destSI = this._sortTable[i];
  61027. var sourceOff = sourceSI.offset;
  61028. // If the source changed location, find the new one
  61029. if (sourceSI.swapedOffset) {
  61030. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  61031. var curSI = sourceSI;
  61032. while (curSI.swapedOffset) {
  61033. curSI = this._sortTable[curSI.swapedOffset / stride];
  61034. }
  61035. // Finally get the right location
  61036. sourceOff = curSI.offset;
  61037. }
  61038. // Tag the element being replaced with its new location
  61039. destSI.swapedOffset = sourceOff;
  61040. // Swap elements (only if needed)
  61041. if (sourceOff !== destSI.offset) {
  61042. swapElements(sourceOff, destSI.offset);
  61043. }
  61044. // Update the offset in the corresponding DFAE
  61045. //sourceSI.entry.offset = destSI.entry.offset;
  61046. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  61047. }
  61048. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61049. return true;
  61050. };
  61051. return DynamicFloatArray;
  61052. }());
  61053. BABYLON.DynamicFloatArray = DynamicFloatArray;
  61054. var SortInfo = (function () {
  61055. function SortInfo() {
  61056. this.compareData = this.offset = this.swapedOffset = null;
  61057. }
  61058. return SortInfo;
  61059. }());
  61060. })(BABYLON || (BABYLON = {}));
  61061. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  61062. var BABYLON;
  61063. (function (BABYLON) {
  61064. var Debug;
  61065. (function (Debug) {
  61066. /**
  61067. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  61068. */
  61069. var SkeletonViewer = (function () {
  61070. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  61071. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  61072. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  61073. this.skeleton = skeleton;
  61074. this.mesh = mesh;
  61075. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  61076. this.renderingGroupId = renderingGroupId;
  61077. this.color = BABYLON.Color3.White();
  61078. this._debugLines = [];
  61079. this._isEnabled = false;
  61080. this._scene = scene;
  61081. this.update();
  61082. this._renderFunction = this.update.bind(this);
  61083. }
  61084. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  61085. get: function () {
  61086. return this._isEnabled;
  61087. },
  61088. set: function (value) {
  61089. if (this._isEnabled === value) {
  61090. return;
  61091. }
  61092. this._isEnabled = value;
  61093. if (value) {
  61094. this._scene.registerBeforeRender(this._renderFunction);
  61095. }
  61096. else {
  61097. this._scene.unregisterBeforeRender(this._renderFunction);
  61098. }
  61099. },
  61100. enumerable: true,
  61101. configurable: true
  61102. });
  61103. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  61104. if (x === void 0) { x = 0; }
  61105. if (y === void 0) { y = 0; }
  61106. if (z === void 0) { z = 0; }
  61107. var tmat = BABYLON.Tmp.Matrix[0];
  61108. var parentBone = bone.getParent();
  61109. tmat.copyFrom(bone.getLocalMatrix());
  61110. if (x !== 0 || y !== 0 || z !== 0) {
  61111. var tmat2 = BABYLON.Tmp.Matrix[1];
  61112. BABYLON.Matrix.IdentityToRef(tmat2);
  61113. tmat2.m[12] = x;
  61114. tmat2.m[13] = y;
  61115. tmat2.m[14] = z;
  61116. tmat2.multiplyToRef(tmat, tmat);
  61117. }
  61118. if (parentBone) {
  61119. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  61120. }
  61121. tmat.multiplyToRef(meshMat, tmat);
  61122. position.x = tmat.m[12];
  61123. position.y = tmat.m[13];
  61124. position.z = tmat.m[14];
  61125. };
  61126. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  61127. var len = bones.length;
  61128. var meshPos = this.mesh.position;
  61129. for (var i = 0; i < len; i++) {
  61130. var bone = bones[i];
  61131. var points = this._debugLines[i];
  61132. if (!points) {
  61133. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61134. this._debugLines[i] = points;
  61135. }
  61136. this._getBonePosition(points[0], bone, meshMat);
  61137. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  61138. points[0].subtractInPlace(meshPos);
  61139. points[1].subtractInPlace(meshPos);
  61140. }
  61141. };
  61142. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  61143. var len = bones.length;
  61144. var boneNum = 0;
  61145. var meshPos = this.mesh.position;
  61146. for (var i = len - 1; i >= 0; i--) {
  61147. var childBone = bones[i];
  61148. var parentBone = childBone.getParent();
  61149. if (!parentBone) {
  61150. continue;
  61151. }
  61152. var points = this._debugLines[boneNum];
  61153. if (!points) {
  61154. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61155. this._debugLines[boneNum] = points;
  61156. }
  61157. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  61158. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  61159. points[0].subtractInPlace(meshPos);
  61160. points[1].subtractInPlace(meshPos);
  61161. boneNum++;
  61162. }
  61163. };
  61164. SkeletonViewer.prototype.update = function () {
  61165. if (this.autoUpdateBonesMatrices) {
  61166. this.skeleton.computeAbsoluteTransforms();
  61167. }
  61168. if (this.skeleton.bones[0].length === undefined) {
  61169. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61170. }
  61171. else {
  61172. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61173. }
  61174. if (!this._debugMesh) {
  61175. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  61176. this._debugMesh.renderingGroupId = this.renderingGroupId;
  61177. }
  61178. else {
  61179. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  61180. }
  61181. this._debugMesh.position.copyFrom(this.mesh.position);
  61182. this._debugMesh.color = this.color;
  61183. };
  61184. SkeletonViewer.prototype.dispose = function () {
  61185. if (this._debugMesh) {
  61186. this.isEnabled = false;
  61187. this._debugMesh.dispose();
  61188. this._debugMesh = null;
  61189. }
  61190. };
  61191. return SkeletonViewer;
  61192. }());
  61193. Debug.SkeletonViewer = SkeletonViewer;
  61194. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61195. })(BABYLON || (BABYLON = {}));
  61196. //# sourceMappingURL=babylon.skeletonViewer.js.map
  61197. var BABYLON;
  61198. (function (BABYLON) {
  61199. var Debug;
  61200. (function (Debug) {
  61201. var AxesViewer = (function () {
  61202. function AxesViewer(scene, scaleLines) {
  61203. if (scaleLines === void 0) { scaleLines = 1; }
  61204. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61205. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61206. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61207. this.scaleLines = 1;
  61208. this.scaleLines = scaleLines;
  61209. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  61210. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  61211. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  61212. this._xmesh.renderingGroupId = 2;
  61213. this._ymesh.renderingGroupId = 2;
  61214. this._zmesh.renderingGroupId = 2;
  61215. this._xmesh.material.checkReadyOnlyOnce = true;
  61216. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  61217. this._ymesh.material.checkReadyOnlyOnce = true;
  61218. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  61219. this._zmesh.material.checkReadyOnlyOnce = true;
  61220. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  61221. this.scene = scene;
  61222. }
  61223. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  61224. var scaleLines = this.scaleLines;
  61225. this._xmesh.position.copyFrom(position);
  61226. this._ymesh.position.copyFrom(position);
  61227. this._zmesh.position.copyFrom(position);
  61228. var point2 = this._xline[1];
  61229. point2.x = xaxis.x * scaleLines;
  61230. point2.y = xaxis.y * scaleLines;
  61231. point2.z = xaxis.z * scaleLines;
  61232. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  61233. point2 = this._yline[1];
  61234. point2.x = yaxis.x * scaleLines;
  61235. point2.y = yaxis.y * scaleLines;
  61236. point2.z = yaxis.z * scaleLines;
  61237. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  61238. point2 = this._zline[1];
  61239. point2.x = zaxis.x * scaleLines;
  61240. point2.y = zaxis.y * scaleLines;
  61241. point2.z = zaxis.z * scaleLines;
  61242. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  61243. };
  61244. AxesViewer.prototype.dispose = function () {
  61245. if (this._xmesh) {
  61246. this._xmesh.dispose();
  61247. this._ymesh.dispose();
  61248. this._zmesh.dispose();
  61249. this._xmesh = null;
  61250. this._ymesh = null;
  61251. this._zmesh = null;
  61252. this._xline = null;
  61253. this._yline = null;
  61254. this._zline = null;
  61255. this.scene = null;
  61256. }
  61257. };
  61258. return AxesViewer;
  61259. }());
  61260. Debug.AxesViewer = AxesViewer;
  61261. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61262. })(BABYLON || (BABYLON = {}));
  61263. //# sourceMappingURL=babylon.axesViewer.js.map
  61264. var BABYLON;
  61265. (function (BABYLON) {
  61266. var Debug;
  61267. (function (Debug) {
  61268. var BoneAxesViewer = (function (_super) {
  61269. __extends(BoneAxesViewer, _super);
  61270. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  61271. if (scaleLines === void 0) { scaleLines = 1; }
  61272. var _this = _super.call(this, scene, scaleLines) || this;
  61273. _this.pos = BABYLON.Vector3.Zero();
  61274. _this.xaxis = BABYLON.Vector3.Zero();
  61275. _this.yaxis = BABYLON.Vector3.Zero();
  61276. _this.zaxis = BABYLON.Vector3.Zero();
  61277. _this.mesh = mesh;
  61278. _this.bone = bone;
  61279. return _this;
  61280. }
  61281. BoneAxesViewer.prototype.update = function () {
  61282. var bone = this.bone;
  61283. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  61284. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  61285. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  61286. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  61287. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  61288. };
  61289. BoneAxesViewer.prototype.dispose = function () {
  61290. if (this.pos) {
  61291. this.pos = null;
  61292. this.xaxis = null;
  61293. this.yaxis = null;
  61294. this.zaxis = null;
  61295. this.mesh = null;
  61296. this.bone = null;
  61297. _super.prototype.dispose.call(this);
  61298. }
  61299. };
  61300. return BoneAxesViewer;
  61301. }(Debug.AxesViewer));
  61302. Debug.BoneAxesViewer = BoneAxesViewer;
  61303. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61304. })(BABYLON || (BABYLON = {}));
  61305. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  61306. var BABYLON;
  61307. (function (BABYLON) {
  61308. var RayHelper = (function () {
  61309. function RayHelper(ray) {
  61310. this.ray = ray;
  61311. }
  61312. RayHelper.CreateAndShow = function (ray, scene, color) {
  61313. var helper = new RayHelper(ray);
  61314. helper.show(scene, color);
  61315. return helper;
  61316. };
  61317. RayHelper.prototype.show = function (scene, color) {
  61318. if (!this._renderFunction) {
  61319. var ray = this.ray;
  61320. this._renderFunction = this._render.bind(this);
  61321. this._scene = scene;
  61322. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  61323. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  61324. this._scene.registerBeforeRender(this._renderFunction);
  61325. }
  61326. if (color) {
  61327. this._renderLine.color.copyFrom(color);
  61328. }
  61329. };
  61330. RayHelper.prototype.hide = function () {
  61331. if (this._renderFunction) {
  61332. this._scene.unregisterBeforeRender(this._renderFunction);
  61333. this._scene = null;
  61334. this._renderFunction = null;
  61335. this._renderLine.dispose();
  61336. this._renderLine = null;
  61337. this._renderPoints = null;
  61338. }
  61339. };
  61340. RayHelper.prototype._render = function () {
  61341. var ray = this.ray;
  61342. var point = this._renderPoints[1];
  61343. var len = Math.min(ray.length, 1000000);
  61344. point.copyFrom(ray.direction);
  61345. point.scaleInPlace(len);
  61346. point.addInPlace(ray.origin);
  61347. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  61348. };
  61349. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  61350. this._attachedToMesh = mesh;
  61351. var ray = this.ray;
  61352. if (!ray.direction) {
  61353. ray.direction = BABYLON.Vector3.Zero();
  61354. }
  61355. if (!ray.origin) {
  61356. ray.origin = BABYLON.Vector3.Zero();
  61357. }
  61358. if (length) {
  61359. ray.length = length;
  61360. }
  61361. if (!meshSpaceOrigin) {
  61362. meshSpaceOrigin = BABYLON.Vector3.Zero();
  61363. }
  61364. if (!meshSpaceDirection) {
  61365. // -1 so that this will work with Mesh.lookAt
  61366. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  61367. }
  61368. if (!this._meshSpaceDirection) {
  61369. this._meshSpaceDirection = meshSpaceDirection.clone();
  61370. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  61371. }
  61372. else {
  61373. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  61374. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  61375. }
  61376. if (!this._updateToMeshFunction) {
  61377. this._updateToMeshFunction = this._updateToMesh.bind(this);
  61378. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  61379. }
  61380. this._updateToMesh();
  61381. };
  61382. RayHelper.prototype.detachFromMesh = function () {
  61383. if (this._attachedToMesh) {
  61384. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  61385. this._attachedToMesh = null;
  61386. this._updateToMeshFunction = null;
  61387. }
  61388. };
  61389. RayHelper.prototype._updateToMesh = function () {
  61390. var ray = this.ray;
  61391. if (this._attachedToMesh._isDisposed) {
  61392. this.detachFromMesh();
  61393. return;
  61394. }
  61395. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61396. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61397. };
  61398. RayHelper.prototype.dispose = function () {
  61399. this.hide();
  61400. this.detachFromMesh();
  61401. this.ray = null;
  61402. };
  61403. return RayHelper;
  61404. }());
  61405. BABYLON.RayHelper = RayHelper;
  61406. })(BABYLON || (BABYLON = {}));
  61407. //# sourceMappingURL=babylon.rayHelper.js.map
  61408. var BABYLON;
  61409. (function (BABYLON) {
  61410. var DebugLayer = (function () {
  61411. function DebugLayer(scene) {
  61412. this._scene = scene;
  61413. }
  61414. /** Creates the inspector window. */
  61415. DebugLayer.prototype._createInspector = function (config) {
  61416. if (config === void 0) { config = {}; }
  61417. var popup = config.popup || false;
  61418. var initialTab = config.initialTab || 0;
  61419. var parentElement = config.parentElement || null;
  61420. if (!this._inspector) {
  61421. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61422. } // else nothing to do,; instance is already existing
  61423. };
  61424. DebugLayer.prototype.isVisible = function () {
  61425. if (!this._inspector) {
  61426. return false;
  61427. }
  61428. return true;
  61429. };
  61430. DebugLayer.prototype.hide = function () {
  61431. if (this._inspector) {
  61432. try {
  61433. this._inspector.dispose();
  61434. }
  61435. catch (e) {
  61436. // If the inspector has been removed directly from the inspector tool
  61437. }
  61438. this._inspector = null;
  61439. }
  61440. };
  61441. DebugLayer.prototype.show = function (config) {
  61442. if (config === void 0) { config = {}; }
  61443. if (typeof INSPECTOR == 'undefined') {
  61444. // Load inspector and add it to the DOM
  61445. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  61446. }
  61447. else {
  61448. // Otherwise creates the inspector
  61449. this._createInspector(config);
  61450. }
  61451. };
  61452. return DebugLayer;
  61453. }());
  61454. // Get protocol used - http or https
  61455. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61456. BABYLON.DebugLayer = DebugLayer;
  61457. })(BABYLON || (BABYLON = {}));
  61458. //# sourceMappingURL=babylon.debugLayer.js.map
  61459. var BABYLON;
  61460. (function (BABYLON) {
  61461. var Debug;
  61462. (function (Debug) {
  61463. var PhysicsViewer = (function () {
  61464. function PhysicsViewer(scene) {
  61465. this._impostors = [];
  61466. this._meshes = [];
  61467. this._numMeshes = 0;
  61468. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61469. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  61470. }
  61471. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61472. var plugin = this._physicsEnginePlugin;
  61473. for (var i = 0; i < this._numMeshes; i++) {
  61474. if (this._impostors[i].isDisposed) {
  61475. this.hideImpostor(this._impostors[i--]);
  61476. }
  61477. else {
  61478. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  61479. }
  61480. }
  61481. };
  61482. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61483. for (var i = 0; i < this._numMeshes; i++) {
  61484. if (this._impostors[i] == impostor) {
  61485. return;
  61486. }
  61487. }
  61488. var debugMesh = this._physicsEnginePlugin.getDebugMesh(impostor, this._scene);
  61489. if (debugMesh) {
  61490. this._impostors[this._numMeshes] = impostor;
  61491. this._meshes[this._numMeshes] = debugMesh;
  61492. if (this._numMeshes === 0) {
  61493. this._renderFunction = this._updateDebugMeshes.bind(this);
  61494. this._scene.registerBeforeRender(this._renderFunction);
  61495. }
  61496. this._numMeshes++;
  61497. }
  61498. };
  61499. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61500. var removed = false;
  61501. for (var i = 0; i < this._numMeshes; i++) {
  61502. if (this._impostors[i] == impostor) {
  61503. this._scene.removeMesh(this._meshes[i]);
  61504. this._meshes[i].dispose();
  61505. this._numMeshes--;
  61506. if (this._numMeshes > 0) {
  61507. this._meshes[i] = this._meshes[this._numMeshes];
  61508. this._impostors[i] = this._impostors[this._numMeshes];
  61509. this._meshes[this._numMeshes] = null;
  61510. this._impostors[this._numMeshes] = null;
  61511. }
  61512. else {
  61513. this._meshes[0] = null;
  61514. this._impostors[0] = null;
  61515. }
  61516. removed = true;
  61517. break;
  61518. }
  61519. }
  61520. if (removed && this._numMeshes === 0) {
  61521. this._scene.unregisterBeforeRender(this._renderFunction);
  61522. }
  61523. };
  61524. PhysicsViewer.prototype.dispose = function () {
  61525. for (var i = 0; i < this._numMeshes; i++) {
  61526. this.hideImpostor(this._impostors[i]);
  61527. }
  61528. this._impostors.length = 0;
  61529. this._scene = null;
  61530. this._physicsEnginePlugin = null;
  61531. };
  61532. return PhysicsViewer;
  61533. }());
  61534. Debug.PhysicsViewer = PhysicsViewer;
  61535. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61536. })(BABYLON || (BABYLON = {}));
  61537. //# sourceMappingURL=babylon.physicsViewer.js.map
  61538. var BABYLON;
  61539. (function (BABYLON) {
  61540. var BoundingBoxRenderer = (function () {
  61541. function BoundingBoxRenderer(scene) {
  61542. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61543. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61544. this.showBackLines = true;
  61545. this.renderList = new BABYLON.SmartArray(32);
  61546. this._vertexBuffers = {};
  61547. this._scene = scene;
  61548. }
  61549. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61550. if (this._colorShader) {
  61551. return;
  61552. }
  61553. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  61554. attributes: [BABYLON.VertexBuffer.PositionKind],
  61555. uniforms: ["world", "viewProjection", "color"]
  61556. });
  61557. var engine = this._scene.getEngine();
  61558. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  61559. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61560. 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]);
  61561. };
  61562. BoundingBoxRenderer.prototype.reset = function () {
  61563. this.renderList.reset();
  61564. };
  61565. BoundingBoxRenderer.prototype.render = function () {
  61566. if (this.renderList.length === 0) {
  61567. return;
  61568. }
  61569. this._prepareRessources();
  61570. if (!this._colorShader.isReady()) {
  61571. return;
  61572. }
  61573. var engine = this._scene.getEngine();
  61574. engine.setDepthWrite(false);
  61575. this._colorShader._preBind();
  61576. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61577. var boundingBox = this.renderList.data[boundingBoxIndex];
  61578. var min = boundingBox.minimum;
  61579. var max = boundingBox.maximum;
  61580. var diff = max.subtract(min);
  61581. var median = min.add(diff.scale(0.5));
  61582. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61583. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61584. .multiply(boundingBox.getWorldMatrix());
  61585. // VBOs
  61586. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61587. if (this.showBackLines) {
  61588. // Back
  61589. engine.setDepthFunctionToGreaterOrEqual();
  61590. this._scene.resetCachedMaterial();
  61591. this._colorShader.setColor4("color", this.backColor.toColor4());
  61592. this._colorShader.bind(worldMatrix);
  61593. // Draw order
  61594. engine.draw(false, 0, 24);
  61595. }
  61596. // Front
  61597. engine.setDepthFunctionToLess();
  61598. this._scene.resetCachedMaterial();
  61599. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61600. this._colorShader.bind(worldMatrix);
  61601. // Draw order
  61602. engine.draw(false, 0, 24);
  61603. }
  61604. this._colorShader.unbind();
  61605. engine.setDepthFunctionToLessOrEqual();
  61606. engine.setDepthWrite(true);
  61607. };
  61608. BoundingBoxRenderer.prototype.dispose = function () {
  61609. if (!this._colorShader) {
  61610. return;
  61611. }
  61612. this.renderList.dispose();
  61613. this._colorShader.dispose();
  61614. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61615. if (buffer) {
  61616. buffer.dispose();
  61617. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61618. }
  61619. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61620. };
  61621. return BoundingBoxRenderer;
  61622. }());
  61623. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61624. })(BABYLON || (BABYLON = {}));
  61625. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61626. var BABYLON;
  61627. (function (BABYLON) {
  61628. var MorphTarget = (function () {
  61629. function MorphTarget(name, influence) {
  61630. if (influence === void 0) { influence = 0; }
  61631. this.name = name;
  61632. this.animations = new Array();
  61633. this.onInfluenceChanged = new BABYLON.Observable();
  61634. this.influence = influence;
  61635. }
  61636. Object.defineProperty(MorphTarget.prototype, "influence", {
  61637. get: function () {
  61638. return this._influence;
  61639. },
  61640. set: function (influence) {
  61641. if (this._influence === influence) {
  61642. return;
  61643. }
  61644. var previous = this._influence;
  61645. this._influence = influence;
  61646. if (this.onInfluenceChanged.hasObservers) {
  61647. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  61648. }
  61649. },
  61650. enumerable: true,
  61651. configurable: true
  61652. });
  61653. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  61654. get: function () {
  61655. return this._normals !== undefined;
  61656. },
  61657. enumerable: true,
  61658. configurable: true
  61659. });
  61660. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  61661. get: function () {
  61662. return this._tangents !== undefined;
  61663. },
  61664. enumerable: true,
  61665. configurable: true
  61666. });
  61667. MorphTarget.prototype.setPositions = function (data) {
  61668. this._positions = new Float32Array(data);
  61669. };
  61670. MorphTarget.prototype.getPositions = function () {
  61671. return this._positions;
  61672. };
  61673. MorphTarget.prototype.setNormals = function (data) {
  61674. this._normals = new Float32Array(data);
  61675. };
  61676. MorphTarget.prototype.getNormals = function () {
  61677. return this._normals;
  61678. };
  61679. MorphTarget.prototype.setTangents = function (data) {
  61680. this._tangents = new Float32Array(data);
  61681. };
  61682. MorphTarget.prototype.getTangents = function () {
  61683. return this._tangents;
  61684. };
  61685. /**
  61686. * Serializes the current target into a Serialization object.
  61687. * Returns the serialized object.
  61688. */
  61689. MorphTarget.prototype.serialize = function () {
  61690. var serializationObject = {};
  61691. serializationObject.name = this.name;
  61692. serializationObject.influence = this.influence;
  61693. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  61694. if (this.hasNormals) {
  61695. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  61696. }
  61697. if (this.hasTangents) {
  61698. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  61699. }
  61700. return serializationObject;
  61701. };
  61702. // Statics
  61703. MorphTarget.Parse = function (serializationObject) {
  61704. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  61705. result.setPositions(serializationObject.positions);
  61706. if (serializationObject.normals) {
  61707. result.setNormals(serializationObject.normals);
  61708. }
  61709. if (serializationObject.tangents) {
  61710. result.setTangents(serializationObject.tangents);
  61711. }
  61712. return result;
  61713. };
  61714. MorphTarget.FromMesh = function (mesh, name, influence) {
  61715. if (!name) {
  61716. name = mesh.name;
  61717. }
  61718. var result = new MorphTarget(name, influence);
  61719. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  61720. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61721. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  61722. }
  61723. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  61724. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  61725. }
  61726. return result;
  61727. };
  61728. return MorphTarget;
  61729. }());
  61730. BABYLON.MorphTarget = MorphTarget;
  61731. })(BABYLON || (BABYLON = {}));
  61732. //# sourceMappingURL=babylon.morphTarget.js.map
  61733. var BABYLON;
  61734. (function (BABYLON) {
  61735. var MorphTargetManager = (function () {
  61736. function MorphTargetManager(scene) {
  61737. this._targets = new Array();
  61738. this._targetObservable = new Array();
  61739. this._activeTargets = new BABYLON.SmartArray(16);
  61740. this._supportsNormals = false;
  61741. this._supportsTangents = false;
  61742. this._vertexCount = 0;
  61743. this._uniqueId = 0;
  61744. if (!scene) {
  61745. scene = BABYLON.Engine.LastCreatedScene;
  61746. }
  61747. this._scene = scene;
  61748. this._scene.morphTargetManagers.push(this);
  61749. this._uniqueId = scene.getUniqueId();
  61750. }
  61751. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  61752. get: function () {
  61753. return this._uniqueId;
  61754. },
  61755. enumerable: true,
  61756. configurable: true
  61757. });
  61758. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  61759. get: function () {
  61760. return this._vertexCount;
  61761. },
  61762. enumerable: true,
  61763. configurable: true
  61764. });
  61765. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  61766. get: function () {
  61767. return this._supportsNormals;
  61768. },
  61769. enumerable: true,
  61770. configurable: true
  61771. });
  61772. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  61773. get: function () {
  61774. return this._supportsTangents;
  61775. },
  61776. enumerable: true,
  61777. configurable: true
  61778. });
  61779. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  61780. get: function () {
  61781. return this._targets.length;
  61782. },
  61783. enumerable: true,
  61784. configurable: true
  61785. });
  61786. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  61787. get: function () {
  61788. return this._activeTargets.length;
  61789. },
  61790. enumerable: true,
  61791. configurable: true
  61792. });
  61793. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  61794. get: function () {
  61795. return this._influences;
  61796. },
  61797. enumerable: true,
  61798. configurable: true
  61799. });
  61800. MorphTargetManager.prototype.getActiveTarget = function (index) {
  61801. return this._activeTargets.data[index];
  61802. };
  61803. MorphTargetManager.prototype.getTarget = function (index) {
  61804. return this._targets[index];
  61805. };
  61806. MorphTargetManager.prototype.addTarget = function (target) {
  61807. var _this = this;
  61808. if (this._vertexCount) {
  61809. if (this._vertexCount !== target.getPositions().length / 3) {
  61810. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  61811. return;
  61812. }
  61813. }
  61814. this._targets.push(target);
  61815. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  61816. _this._syncActiveTargets(needUpdate);
  61817. }));
  61818. this._syncActiveTargets(true);
  61819. };
  61820. MorphTargetManager.prototype.removeTarget = function (target) {
  61821. var index = this._targets.indexOf(target);
  61822. if (index >= 0) {
  61823. this._targets.splice(index, 1);
  61824. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  61825. this._vertexCount = 0;
  61826. this._syncActiveTargets(true);
  61827. }
  61828. };
  61829. /**
  61830. * Serializes the current manager into a Serialization object.
  61831. * Returns the serialized object.
  61832. */
  61833. MorphTargetManager.prototype.serialize = function () {
  61834. var serializationObject = {};
  61835. serializationObject.id = this.uniqueId;
  61836. serializationObject.targets = [];
  61837. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  61838. var target = _a[_i];
  61839. serializationObject.targets.push(target.serialize());
  61840. }
  61841. return serializationObject;
  61842. };
  61843. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  61844. this._syncActiveTargets(needUpdate);
  61845. };
  61846. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  61847. this._activeTargets.reset();
  61848. var tempInfluences = [];
  61849. this._supportsNormals = true;
  61850. this._supportsTangents = true;
  61851. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  61852. var target = _a[_i];
  61853. if (target.influence > 0) {
  61854. this._activeTargets.push(target);
  61855. tempInfluences.push(target.influence);
  61856. this._supportsNormals = this._supportsNormals && target.hasNormals;
  61857. this._supportsTangents = this._supportsTangents && target.hasTangents;
  61858. if (this._vertexCount === 0) {
  61859. this._vertexCount = target.getPositions().length / 3;
  61860. }
  61861. }
  61862. }
  61863. this._influences = new Float32Array(tempInfluences);
  61864. if (needUpdate) {
  61865. // Flag meshes as dirty to resync with the active targets
  61866. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  61867. var mesh = _c[_b];
  61868. if (mesh.morphTargetManager === this) {
  61869. mesh._syncGeometryWithMorphTargetManager();
  61870. }
  61871. }
  61872. }
  61873. };
  61874. // Statics
  61875. MorphTargetManager.Parse = function (serializationObject, scene) {
  61876. var result = new MorphTargetManager(scene);
  61877. result._uniqueId = serializationObject.id;
  61878. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  61879. var targetData = _a[_i];
  61880. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  61881. }
  61882. return result;
  61883. };
  61884. return MorphTargetManager;
  61885. }());
  61886. BABYLON.MorphTargetManager = MorphTargetManager;
  61887. })(BABYLON || (BABYLON = {}));
  61888. //# sourceMappingURL=babylon.morphTargetManager.js.map
  61889. var BABYLON;
  61890. (function (BABYLON) {
  61891. /**
  61892. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  61893. * It can help converting any input color in a desired output one. This can then be used to create effects
  61894. * from sepia, black and white to sixties or futuristic rendering...
  61895. *
  61896. * The only supported format is currently 3dl.
  61897. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  61898. */
  61899. var ColorGradingTexture = (function (_super) {
  61900. __extends(ColorGradingTexture, _super);
  61901. /**
  61902. * Instantiates a ColorGradingTexture from the following parameters.
  61903. *
  61904. * @param url The location of the color gradind data (currently only supporting 3dl)
  61905. * @param scene The scene the texture will be used in
  61906. */
  61907. function ColorGradingTexture(url, scene) {
  61908. var _this = _super.call(this, scene) || this;
  61909. if (!url) {
  61910. return _this;
  61911. }
  61912. _this._textureMatrix = BABYLON.Matrix.Identity();
  61913. _this.name = url;
  61914. _this.url = url;
  61915. _this.hasAlpha = false;
  61916. _this.isCube = false;
  61917. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61918. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61919. _this.anisotropicFilteringLevel = 1;
  61920. _this._texture = _this._getFromCache(url, true);
  61921. if (!_this._texture) {
  61922. if (!scene.useDelayedTextureLoading) {
  61923. _this.loadTexture();
  61924. }
  61925. else {
  61926. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61927. }
  61928. }
  61929. return _this;
  61930. }
  61931. /**
  61932. * Returns the texture matrix used in most of the material.
  61933. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  61934. */
  61935. ColorGradingTexture.prototype.getTextureMatrix = function () {
  61936. return this._textureMatrix;
  61937. };
  61938. /**
  61939. * Occurs when the file being loaded is a .3dl LUT file.
  61940. */
  61941. ColorGradingTexture.prototype.load3dlTexture = function () {
  61942. var _this = this;
  61943. var mipLevels = 0;
  61944. var floatArrayView = null;
  61945. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61946. this._texture = texture;
  61947. var callback = function (text) {
  61948. var data;
  61949. var tempData;
  61950. var line;
  61951. var lines = text.split('\n');
  61952. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  61953. var maxColor = 0;
  61954. for (var i = 0; i < lines.length; i++) {
  61955. line = lines[i];
  61956. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  61957. continue;
  61958. if (line.indexOf('#') === 0)
  61959. continue;
  61960. var words = line.split(" ");
  61961. if (size === 0) {
  61962. // Number of space + one
  61963. size = words.length;
  61964. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  61965. tempData = new Float32Array(size * size * size * 4);
  61966. continue;
  61967. }
  61968. if (size != 0) {
  61969. var r = Math.max(parseInt(words[0]), 0);
  61970. var g = Math.max(parseInt(words[1]), 0);
  61971. var b = Math.max(parseInt(words[2]), 0);
  61972. maxColor = Math.max(r, maxColor);
  61973. maxColor = Math.max(g, maxColor);
  61974. maxColor = Math.max(b, maxColor);
  61975. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  61976. tempData[pixelStorageIndex + 0] = r;
  61977. tempData[pixelStorageIndex + 1] = g;
  61978. tempData[pixelStorageIndex + 2] = b;
  61979. pixelIndexSlice++;
  61980. if (pixelIndexSlice % size == 0) {
  61981. pixelIndexH++;
  61982. pixelIndexSlice = 0;
  61983. if (pixelIndexH % size == 0) {
  61984. pixelIndexW++;
  61985. pixelIndexH = 0;
  61986. }
  61987. }
  61988. }
  61989. }
  61990. for (var i = 0; i < tempData.length; i++) {
  61991. if (i > 0 && (i + 1) % 4 === 0) {
  61992. data[i] = 255;
  61993. }
  61994. else {
  61995. var value = tempData[i];
  61996. data[i] = (value / maxColor * 255);
  61997. }
  61998. }
  61999. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  62000. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  62001. };
  62002. BABYLON.Tools.LoadFile(this.url, callback);
  62003. return this._texture;
  62004. };
  62005. /**
  62006. * Starts the loading process of the texture.
  62007. */
  62008. ColorGradingTexture.prototype.loadTexture = function () {
  62009. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  62010. this.load3dlTexture();
  62011. }
  62012. };
  62013. /**
  62014. * Clones the color gradind texture.
  62015. */
  62016. ColorGradingTexture.prototype.clone = function () {
  62017. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  62018. // Base texture
  62019. newTexture.level = this.level;
  62020. return newTexture;
  62021. };
  62022. /**
  62023. * Called during delayed load for textures.
  62024. */
  62025. ColorGradingTexture.prototype.delayLoad = function () {
  62026. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62027. return;
  62028. }
  62029. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62030. this._texture = this._getFromCache(this.url, true);
  62031. if (!this._texture) {
  62032. this.loadTexture();
  62033. }
  62034. };
  62035. /**
  62036. * Parses a color grading texture serialized by Babylon.
  62037. * @param parsedTexture The texture information being parsedTexture
  62038. * @param scene The scene to load the texture in
  62039. * @param rootUrl The root url of the data assets to load
  62040. * @return A color gradind texture
  62041. */
  62042. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62043. var texture = null;
  62044. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  62045. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  62046. texture.name = parsedTexture.name;
  62047. texture.level = parsedTexture.level;
  62048. }
  62049. return texture;
  62050. };
  62051. /**
  62052. * Serializes the LUT texture to json format.
  62053. */
  62054. ColorGradingTexture.prototype.serialize = function () {
  62055. if (!this.name) {
  62056. return null;
  62057. }
  62058. var serializationObject = {};
  62059. serializationObject.name = this.name;
  62060. serializationObject.level = this.level;
  62061. serializationObject.customType = "BABYLON.ColorGradingTexture";
  62062. return serializationObject;
  62063. };
  62064. return ColorGradingTexture;
  62065. }(BABYLON.BaseTexture));
  62066. /**
  62067. * Empty line regex stored for GC.
  62068. */
  62069. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  62070. BABYLON.ColorGradingTexture = ColorGradingTexture;
  62071. })(BABYLON || (BABYLON = {}));
  62072. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  62073. var BABYLON;
  62074. (function (BABYLON) {
  62075. /**
  62076. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  62077. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  62078. * 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;
  62079. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  62080. */
  62081. var ColorCurves = (function () {
  62082. function ColorCurves() {
  62083. this._dirty = true;
  62084. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  62085. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  62086. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  62087. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  62088. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  62089. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  62090. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  62091. this._globalHue = 30;
  62092. this._globalDensity = 0;
  62093. this._globalSaturation = 0;
  62094. this._globalExposure = 0;
  62095. this._highlightsHue = 30;
  62096. this._highlightsDensity = 0;
  62097. this._highlightsSaturation = 0;
  62098. this._highlightsExposure = 0;
  62099. this._midtonesHue = 30;
  62100. this._midtonesDensity = 0;
  62101. this._midtonesSaturation = 0;
  62102. this._midtonesExposure = 0;
  62103. this._shadowsHue = 30;
  62104. this._shadowsDensity = 0;
  62105. this._shadowsSaturation = 0;
  62106. this._shadowsExposure = 0;
  62107. }
  62108. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  62109. /**
  62110. * Gets the global Hue value.
  62111. * 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).
  62112. */
  62113. get: function () {
  62114. return this._globalHue;
  62115. },
  62116. /**
  62117. * Sets the global Hue value.
  62118. * 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).
  62119. */
  62120. set: function (value) {
  62121. this._globalHue = value;
  62122. this._dirty = true;
  62123. },
  62124. enumerable: true,
  62125. configurable: true
  62126. });
  62127. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  62128. /**
  62129. * Gets the global Density value.
  62130. * 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.
  62131. * Values less than zero provide a filter of opposite hue.
  62132. */
  62133. get: function () {
  62134. return this._globalDensity;
  62135. },
  62136. /**
  62137. * Sets the global Density value.
  62138. * 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.
  62139. * Values less than zero provide a filter of opposite hue.
  62140. */
  62141. set: function (value) {
  62142. this._globalDensity = value;
  62143. this._dirty = true;
  62144. },
  62145. enumerable: true,
  62146. configurable: true
  62147. });
  62148. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  62149. /**
  62150. * Gets the global Saturation value.
  62151. * 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.
  62152. */
  62153. get: function () {
  62154. return this._globalSaturation;
  62155. },
  62156. /**
  62157. * Sets the global Saturation value.
  62158. * 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.
  62159. */
  62160. set: function (value) {
  62161. this._globalSaturation = value;
  62162. this._dirty = true;
  62163. },
  62164. enumerable: true,
  62165. configurable: true
  62166. });
  62167. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  62168. /**
  62169. * Gets the highlights Hue value.
  62170. * 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).
  62171. */
  62172. get: function () {
  62173. return this._highlightsHue;
  62174. },
  62175. /**
  62176. * Sets the highlights Hue value.
  62177. * 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).
  62178. */
  62179. set: function (value) {
  62180. this._highlightsHue = value;
  62181. this._dirty = true;
  62182. },
  62183. enumerable: true,
  62184. configurable: true
  62185. });
  62186. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  62187. /**
  62188. * Gets the highlights Density value.
  62189. * 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.
  62190. * Values less than zero provide a filter of opposite hue.
  62191. */
  62192. get: function () {
  62193. return this._highlightsDensity;
  62194. },
  62195. /**
  62196. * Sets the highlights Density value.
  62197. * 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.
  62198. * Values less than zero provide a filter of opposite hue.
  62199. */
  62200. set: function (value) {
  62201. this._highlightsDensity = value;
  62202. this._dirty = true;
  62203. },
  62204. enumerable: true,
  62205. configurable: true
  62206. });
  62207. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  62208. /**
  62209. * Gets the highlights Saturation value.
  62210. * 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.
  62211. */
  62212. get: function () {
  62213. return this._highlightsSaturation;
  62214. },
  62215. /**
  62216. * Sets the highlights Saturation value.
  62217. * 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.
  62218. */
  62219. set: function (value) {
  62220. this._highlightsSaturation = value;
  62221. this._dirty = true;
  62222. },
  62223. enumerable: true,
  62224. configurable: true
  62225. });
  62226. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  62227. /**
  62228. * Gets the highlights Exposure value.
  62229. * 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.
  62230. */
  62231. get: function () {
  62232. return this._highlightsExposure;
  62233. },
  62234. /**
  62235. * Sets the highlights Exposure value.
  62236. * 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.
  62237. */
  62238. set: function (value) {
  62239. this._highlightsExposure = value;
  62240. this._dirty = true;
  62241. },
  62242. enumerable: true,
  62243. configurable: true
  62244. });
  62245. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  62246. /**
  62247. * Gets the midtones Hue value.
  62248. * 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).
  62249. */
  62250. get: function () {
  62251. return this._midtonesHue;
  62252. },
  62253. /**
  62254. * Sets the midtones Hue value.
  62255. * 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).
  62256. */
  62257. set: function (value) {
  62258. this._midtonesHue = value;
  62259. this._dirty = true;
  62260. },
  62261. enumerable: true,
  62262. configurable: true
  62263. });
  62264. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  62265. /**
  62266. * Gets the midtones Density value.
  62267. * 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.
  62268. * Values less than zero provide a filter of opposite hue.
  62269. */
  62270. get: function () {
  62271. return this._midtonesDensity;
  62272. },
  62273. /**
  62274. * Sets the midtones Density value.
  62275. * 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.
  62276. * Values less than zero provide a filter of opposite hue.
  62277. */
  62278. set: function (value) {
  62279. this._midtonesDensity = value;
  62280. this._dirty = true;
  62281. },
  62282. enumerable: true,
  62283. configurable: true
  62284. });
  62285. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  62286. /**
  62287. * Gets the midtones Saturation value.
  62288. * 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.
  62289. */
  62290. get: function () {
  62291. return this._midtonesSaturation;
  62292. },
  62293. /**
  62294. * Sets the midtones Saturation value.
  62295. * 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.
  62296. */
  62297. set: function (value) {
  62298. this._midtonesSaturation = value;
  62299. this._dirty = true;
  62300. },
  62301. enumerable: true,
  62302. configurable: true
  62303. });
  62304. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  62305. /**
  62306. * Gets the midtones Exposure value.
  62307. * 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.
  62308. */
  62309. get: function () {
  62310. return this._midtonesExposure;
  62311. },
  62312. /**
  62313. * Sets the midtones Exposure value.
  62314. * 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.
  62315. */
  62316. set: function (value) {
  62317. this._midtonesExposure = value;
  62318. this._dirty = true;
  62319. },
  62320. enumerable: true,
  62321. configurable: true
  62322. });
  62323. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  62324. /**
  62325. * Gets the shadows Hue value.
  62326. * 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).
  62327. */
  62328. get: function () {
  62329. return this._shadowsHue;
  62330. },
  62331. /**
  62332. * Sets the shadows Hue value.
  62333. * 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).
  62334. */
  62335. set: function (value) {
  62336. this._shadowsHue = value;
  62337. this._dirty = true;
  62338. },
  62339. enumerable: true,
  62340. configurable: true
  62341. });
  62342. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  62343. /**
  62344. * Gets the shadows Density value.
  62345. * 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.
  62346. * Values less than zero provide a filter of opposite hue.
  62347. */
  62348. get: function () {
  62349. return this._shadowsDensity;
  62350. },
  62351. /**
  62352. * Sets the shadows Density value.
  62353. * 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.
  62354. * Values less than zero provide a filter of opposite hue.
  62355. */
  62356. set: function (value) {
  62357. this._shadowsDensity = value;
  62358. this._dirty = true;
  62359. },
  62360. enumerable: true,
  62361. configurable: true
  62362. });
  62363. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  62364. /**
  62365. * Gets the shadows Saturation value.
  62366. * 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.
  62367. */
  62368. get: function () {
  62369. return this._shadowsSaturation;
  62370. },
  62371. /**
  62372. * Sets the shadows Saturation value.
  62373. * 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.
  62374. */
  62375. set: function (value) {
  62376. this._shadowsSaturation = value;
  62377. this._dirty = true;
  62378. },
  62379. enumerable: true,
  62380. configurable: true
  62381. });
  62382. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  62383. /**
  62384. * Gets the shadows Exposure value.
  62385. * 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.
  62386. */
  62387. get: function () {
  62388. return this._shadowsExposure;
  62389. },
  62390. /**
  62391. * Sets the shadows Exposure value.
  62392. * 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.
  62393. */
  62394. set: function (value) {
  62395. this._shadowsExposure = value;
  62396. this._dirty = true;
  62397. },
  62398. enumerable: true,
  62399. configurable: true
  62400. });
  62401. /**
  62402. * Binds the color curves to the shader.
  62403. * @param colorCurves The color curve to bind
  62404. * @param effect The effect to bind to
  62405. */
  62406. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  62407. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  62408. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  62409. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  62410. if (colorCurves._dirty) {
  62411. colorCurves._dirty = false;
  62412. // Fill in global info.
  62413. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  62414. // Compute highlights info.
  62415. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  62416. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  62417. // Compute midtones info.
  62418. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  62419. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  62420. // Compute shadows info.
  62421. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  62422. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  62423. // Compute deltas (neutral is midtones).
  62424. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  62425. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  62426. }
  62427. if (effect) {
  62428. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  62429. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  62430. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  62431. }
  62432. };
  62433. /**
  62434. * Prepare the list of uniforms associated with the ColorCurves effects.
  62435. * @param uniformsList The list of uniforms used in the effect
  62436. */
  62437. ColorCurves.PrepareUniforms = function (uniformsList) {
  62438. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  62439. };
  62440. /**
  62441. * Returns color grading data based on a hue, density, saturation and exposure value.
  62442. * @param filterHue The hue of the color filter.
  62443. * @param filterDensity The density of the color filter.
  62444. * @param saturation The saturation.
  62445. * @param exposure The exposure.
  62446. * @param result The result data container.
  62447. */
  62448. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  62449. if (hue == null) {
  62450. return;
  62451. }
  62452. hue = ColorCurves.clamp(hue, 0, 360);
  62453. density = ColorCurves.clamp(density, -100, 100);
  62454. saturation = ColorCurves.clamp(saturation, -100, 100);
  62455. exposure = ColorCurves.clamp(exposure, -100, 100);
  62456. // Remap the slider/config filter density with non-linear mapping and also scale by half
  62457. // so that the maximum filter density is only 50% control. This provides fine control
  62458. // for small values and reasonable range.
  62459. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  62460. density *= 0.5;
  62461. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  62462. if (density < 0) {
  62463. density *= -1;
  62464. hue = (hue + 180) % 360;
  62465. }
  62466. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  62467. result.scaleToRef(2, result);
  62468. result.a = 1 + 0.01 * saturation;
  62469. };
  62470. /**
  62471. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  62472. * @param value The input slider value in range [-100,100].
  62473. * @returns Adjusted value.
  62474. */
  62475. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  62476. value /= 100;
  62477. var x = Math.abs(value);
  62478. x = Math.pow(x, 2);
  62479. if (value < 0) {
  62480. x *= -1;
  62481. }
  62482. x *= 100;
  62483. return x;
  62484. };
  62485. /**
  62486. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  62487. * @param hue The hue (H) input.
  62488. * @param saturation The saturation (S) input.
  62489. * @param brightness The brightness (B) input.
  62490. * @result An RGBA color represented as Vector4.
  62491. */
  62492. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  62493. var h = ColorCurves.clamp(hue, 0, 360);
  62494. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  62495. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  62496. if (s === 0) {
  62497. result.r = v;
  62498. result.g = v;
  62499. result.b = v;
  62500. }
  62501. else {
  62502. // sector 0 to 5
  62503. h /= 60;
  62504. var i = Math.floor(h);
  62505. // fractional part of h
  62506. var f = h - i;
  62507. var p = v * (1 - s);
  62508. var q = v * (1 - s * f);
  62509. var t = v * (1 - s * (1 - f));
  62510. switch (i) {
  62511. case 0:
  62512. result.r = v;
  62513. result.g = t;
  62514. result.b = p;
  62515. break;
  62516. case 1:
  62517. result.r = q;
  62518. result.g = v;
  62519. result.b = p;
  62520. break;
  62521. case 2:
  62522. result.r = p;
  62523. result.g = v;
  62524. result.b = t;
  62525. break;
  62526. case 3:
  62527. result.r = p;
  62528. result.g = q;
  62529. result.b = v;
  62530. break;
  62531. case 4:
  62532. result.r = t;
  62533. result.g = p;
  62534. result.b = v;
  62535. break;
  62536. default:
  62537. result.r = v;
  62538. result.g = p;
  62539. result.b = q;
  62540. break;
  62541. }
  62542. }
  62543. result.a = 1;
  62544. };
  62545. /**
  62546. * Returns a value clamped between min and max
  62547. * @param value The value to clamp
  62548. * @param min The minimum of value
  62549. * @param max The maximum of value
  62550. * @returns The clamped value.
  62551. */
  62552. ColorCurves.clamp = function (value, min, max) {
  62553. return Math.min(Math.max(value, min), max);
  62554. };
  62555. /**
  62556. * Clones the current color curve instance.
  62557. * @return The cloned curves
  62558. */
  62559. ColorCurves.prototype.clone = function () {
  62560. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  62561. };
  62562. /**
  62563. * Serializes the current color curve instance to a json representation.
  62564. * @return a JSON representation
  62565. */
  62566. ColorCurves.prototype.serialize = function () {
  62567. return BABYLON.SerializationHelper.Serialize(this);
  62568. };
  62569. /**
  62570. * Parses the color curve from a json representation.
  62571. * @param source the JSON source to parse
  62572. * @return The parsed curves
  62573. */
  62574. ColorCurves.Parse = function (source) {
  62575. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  62576. };
  62577. return ColorCurves;
  62578. }());
  62579. __decorate([
  62580. BABYLON.serialize()
  62581. ], ColorCurves.prototype, "_globalHue", void 0);
  62582. __decorate([
  62583. BABYLON.serialize()
  62584. ], ColorCurves.prototype, "_globalDensity", void 0);
  62585. __decorate([
  62586. BABYLON.serialize()
  62587. ], ColorCurves.prototype, "_globalSaturation", void 0);
  62588. __decorate([
  62589. BABYLON.serialize()
  62590. ], ColorCurves.prototype, "_globalExposure", void 0);
  62591. __decorate([
  62592. BABYLON.serialize()
  62593. ], ColorCurves.prototype, "_highlightsHue", void 0);
  62594. __decorate([
  62595. BABYLON.serialize()
  62596. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  62597. __decorate([
  62598. BABYLON.serialize()
  62599. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  62600. __decorate([
  62601. BABYLON.serialize()
  62602. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  62603. __decorate([
  62604. BABYLON.serialize()
  62605. ], ColorCurves.prototype, "_midtonesHue", void 0);
  62606. __decorate([
  62607. BABYLON.serialize()
  62608. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  62609. __decorate([
  62610. BABYLON.serialize()
  62611. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  62612. __decorate([
  62613. BABYLON.serialize()
  62614. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  62615. BABYLON.ColorCurves = ColorCurves;
  62616. })(BABYLON || (BABYLON = {}));
  62617. //# sourceMappingURL=babylon.colorCurves.js.map
  62618. var BABYLON;
  62619. (function (BABYLON) {
  62620. var Octree = (function () {
  62621. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  62622. if (maxDepth === void 0) { maxDepth = 2; }
  62623. this.maxDepth = maxDepth;
  62624. this.dynamicContent = new Array();
  62625. this._maxBlockCapacity = maxBlockCapacity || 64;
  62626. this._selectionContent = new BABYLON.SmartArray(1024);
  62627. this._creationFunc = creationFunc;
  62628. }
  62629. // Methods
  62630. Octree.prototype.update = function (worldMin, worldMax, entries) {
  62631. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  62632. };
  62633. Octree.prototype.addMesh = function (entry) {
  62634. for (var index = 0; index < this.blocks.length; index++) {
  62635. var block = this.blocks[index];
  62636. block.addEntry(entry);
  62637. }
  62638. };
  62639. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  62640. this._selectionContent.reset();
  62641. for (var index = 0; index < this.blocks.length; index++) {
  62642. var block = this.blocks[index];
  62643. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  62644. }
  62645. if (allowDuplicate) {
  62646. this._selectionContent.concat(this.dynamicContent);
  62647. }
  62648. else {
  62649. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62650. }
  62651. return this._selectionContent;
  62652. };
  62653. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  62654. this._selectionContent.reset();
  62655. for (var index = 0; index < this.blocks.length; index++) {
  62656. var block = this.blocks[index];
  62657. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  62658. }
  62659. if (allowDuplicate) {
  62660. this._selectionContent.concat(this.dynamicContent);
  62661. }
  62662. else {
  62663. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62664. }
  62665. return this._selectionContent;
  62666. };
  62667. Octree.prototype.intersectsRay = function (ray) {
  62668. this._selectionContent.reset();
  62669. for (var index = 0; index < this.blocks.length; index++) {
  62670. var block = this.blocks[index];
  62671. block.intersectsRay(ray, this._selectionContent);
  62672. }
  62673. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62674. return this._selectionContent;
  62675. };
  62676. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  62677. target.blocks = new Array();
  62678. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  62679. // Segmenting space
  62680. for (var x = 0; x < 2; x++) {
  62681. for (var y = 0; y < 2; y++) {
  62682. for (var z = 0; z < 2; z++) {
  62683. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  62684. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  62685. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  62686. block.addEntries(entries);
  62687. target.blocks.push(block);
  62688. }
  62689. }
  62690. }
  62691. };
  62692. return Octree;
  62693. }());
  62694. Octree.CreationFuncForMeshes = function (entry, block) {
  62695. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  62696. block.entries.push(entry);
  62697. }
  62698. };
  62699. Octree.CreationFuncForSubMeshes = function (entry, block) {
  62700. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  62701. block.entries.push(entry);
  62702. }
  62703. };
  62704. BABYLON.Octree = Octree;
  62705. })(BABYLON || (BABYLON = {}));
  62706. //# sourceMappingURL=babylon.octree.js.map
  62707. var BABYLON;
  62708. (function (BABYLON) {
  62709. var OctreeBlock = (function () {
  62710. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  62711. this.entries = new Array();
  62712. this._boundingVectors = new Array();
  62713. this._capacity = capacity;
  62714. this._depth = depth;
  62715. this._maxDepth = maxDepth;
  62716. this._creationFunc = creationFunc;
  62717. this._minPoint = minPoint;
  62718. this._maxPoint = maxPoint;
  62719. this._boundingVectors.push(minPoint.clone());
  62720. this._boundingVectors.push(maxPoint.clone());
  62721. this._boundingVectors.push(minPoint.clone());
  62722. this._boundingVectors[2].x = maxPoint.x;
  62723. this._boundingVectors.push(minPoint.clone());
  62724. this._boundingVectors[3].y = maxPoint.y;
  62725. this._boundingVectors.push(minPoint.clone());
  62726. this._boundingVectors[4].z = maxPoint.z;
  62727. this._boundingVectors.push(maxPoint.clone());
  62728. this._boundingVectors[5].z = minPoint.z;
  62729. this._boundingVectors.push(maxPoint.clone());
  62730. this._boundingVectors[6].x = minPoint.x;
  62731. this._boundingVectors.push(maxPoint.clone());
  62732. this._boundingVectors[7].y = minPoint.y;
  62733. }
  62734. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  62735. // Property
  62736. get: function () {
  62737. return this._capacity;
  62738. },
  62739. enumerable: true,
  62740. configurable: true
  62741. });
  62742. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  62743. get: function () {
  62744. return this._minPoint;
  62745. },
  62746. enumerable: true,
  62747. configurable: true
  62748. });
  62749. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  62750. get: function () {
  62751. return this._maxPoint;
  62752. },
  62753. enumerable: true,
  62754. configurable: true
  62755. });
  62756. // Methods
  62757. OctreeBlock.prototype.addEntry = function (entry) {
  62758. if (this.blocks) {
  62759. for (var index = 0; index < this.blocks.length; index++) {
  62760. var block = this.blocks[index];
  62761. block.addEntry(entry);
  62762. }
  62763. return;
  62764. }
  62765. this._creationFunc(entry, this);
  62766. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  62767. this.createInnerBlocks();
  62768. }
  62769. };
  62770. OctreeBlock.prototype.addEntries = function (entries) {
  62771. for (var index = 0; index < entries.length; index++) {
  62772. var mesh = entries[index];
  62773. this.addEntry(mesh);
  62774. }
  62775. };
  62776. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  62777. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  62778. if (this.blocks) {
  62779. for (var index = 0; index < this.blocks.length; index++) {
  62780. var block = this.blocks[index];
  62781. block.select(frustumPlanes, selection, allowDuplicate);
  62782. }
  62783. return;
  62784. }
  62785. if (allowDuplicate) {
  62786. selection.concat(this.entries);
  62787. }
  62788. else {
  62789. selection.concatWithNoDuplicate(this.entries);
  62790. }
  62791. }
  62792. };
  62793. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  62794. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  62795. if (this.blocks) {
  62796. for (var index = 0; index < this.blocks.length; index++) {
  62797. var block = this.blocks[index];
  62798. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  62799. }
  62800. return;
  62801. }
  62802. if (allowDuplicate) {
  62803. selection.concat(this.entries);
  62804. }
  62805. else {
  62806. selection.concatWithNoDuplicate(this.entries);
  62807. }
  62808. }
  62809. };
  62810. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  62811. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  62812. if (this.blocks) {
  62813. for (var index = 0; index < this.blocks.length; index++) {
  62814. var block = this.blocks[index];
  62815. block.intersectsRay(ray, selection);
  62816. }
  62817. return;
  62818. }
  62819. selection.concatWithNoDuplicate(this.entries);
  62820. }
  62821. };
  62822. OctreeBlock.prototype.createInnerBlocks = function () {
  62823. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  62824. };
  62825. return OctreeBlock;
  62826. }());
  62827. BABYLON.OctreeBlock = OctreeBlock;
  62828. })(BABYLON || (BABYLON = {}));
  62829. //# sourceMappingURL=babylon.octreeBlock.js.map
  62830. var BABYLON;
  62831. (function (BABYLON) {
  62832. var SIMDVector3 = (function () {
  62833. function SIMDVector3() {
  62834. }
  62835. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  62836. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  62837. };
  62838. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  62839. var m = transformation.m;
  62840. var m0 = SIMD.Float32x4.load(m, 0);
  62841. var m1 = SIMD.Float32x4.load(m, 4);
  62842. var m2 = SIMD.Float32x4.load(m, 8);
  62843. var m3 = SIMD.Float32x4.load(m, 12);
  62844. 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));
  62845. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  62846. result.x = SIMD.Float32x4.extractLane(r, 0);
  62847. result.y = SIMD.Float32x4.extractLane(r, 1);
  62848. result.z = SIMD.Float32x4.extractLane(r, 2);
  62849. };
  62850. return SIMDVector3;
  62851. }());
  62852. var SIMDMatrix = (function () {
  62853. function SIMDMatrix() {
  62854. }
  62855. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  62856. var tm = this.m;
  62857. var om = other.m;
  62858. var m0 = SIMD.Float32x4.load(om, 0);
  62859. var m1 = SIMD.Float32x4.load(om, 4);
  62860. var m2 = SIMD.Float32x4.load(om, 8);
  62861. var m3 = SIMD.Float32x4.load(om, 12);
  62862. for (var i = 0; i < 16; i += 4) {
  62863. 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)))));
  62864. }
  62865. return this;
  62866. };
  62867. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  62868. var src = this.m;
  62869. var dest = other.m;
  62870. // Load the 4 rows
  62871. var src0 = SIMD.Float32x4.load(src, 0);
  62872. var src1 = SIMD.Float32x4.load(src, 4);
  62873. var src2 = SIMD.Float32x4.load(src, 8);
  62874. var src3 = SIMD.Float32x4.load(src, 12);
  62875. // Transpose the source matrix. Sort of. Not a true transpose operation
  62876. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  62877. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  62878. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  62879. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  62880. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  62881. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  62882. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  62883. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  62884. // This is a true transposition, but it will lead to an incorrect result
  62885. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  62886. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  62887. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  62888. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  62889. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  62890. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  62891. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  62892. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  62893. // ----
  62894. tmp1 = SIMD.Float32x4.mul(row2, row3);
  62895. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62896. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  62897. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  62898. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62899. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  62900. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  62901. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  62902. // ----
  62903. tmp1 = SIMD.Float32x4.mul(row1, row2);
  62904. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62905. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  62906. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  62907. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62908. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  62909. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  62910. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  62911. // ----
  62912. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  62913. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62914. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  62915. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  62916. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  62917. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62918. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  62919. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  62920. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  62921. // ----
  62922. tmp1 = SIMD.Float32x4.mul(row0, row1);
  62923. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62924. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  62925. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  62926. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62927. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  62928. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  62929. // ----
  62930. tmp1 = SIMD.Float32x4.mul(row0, row3);
  62931. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62932. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  62933. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  62934. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62935. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  62936. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  62937. // ----
  62938. tmp1 = SIMD.Float32x4.mul(row0, row2);
  62939. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62940. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  62941. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  62942. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62943. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  62944. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  62945. // Compute determinant
  62946. var det = SIMD.Float32x4.mul(row0, minor0);
  62947. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  62948. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  62949. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  62950. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  62951. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  62952. // These shuffles aren't necessary if the faulty transposition is done
  62953. // up at the top of this function.
  62954. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  62955. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  62956. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  62957. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  62958. // Compute final values by multiplying with 1/det
  62959. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  62960. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  62961. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  62962. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  62963. return this;
  62964. };
  62965. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  62966. var out = result.m;
  62967. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  62968. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  62969. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  62970. // cc.kmVec3Subtract(f, pCenter, pEye);
  62971. var f = SIMD.Float32x4.sub(center, eye);
  62972. // cc.kmVec3Normalize(f, f);
  62973. var tmp = SIMD.Float32x4.mul(f, f);
  62974. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62975. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62976. // cc.kmVec3Assign(up, pUp);
  62977. // cc.kmVec3Normalize(up, up);
  62978. tmp = SIMD.Float32x4.mul(up, up);
  62979. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62980. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62981. // cc.kmVec3Cross(s, f, up);
  62982. 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)));
  62983. // cc.kmVec3Normalize(s, s);
  62984. tmp = SIMD.Float32x4.mul(s, s);
  62985. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62986. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62987. // cc.kmVec3Cross(u, s, f);
  62988. 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)));
  62989. // cc.kmVec3Normalize(s, s);
  62990. tmp = SIMD.Float32x4.mul(s, s);
  62991. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62992. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62993. var zero = SIMD.Float32x4.splat(0.0);
  62994. s = SIMD.Float32x4.neg(s);
  62995. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  62996. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  62997. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  62998. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  62999. 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);
  63000. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  63001. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  63002. 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)))));
  63003. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  63004. 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)))));
  63005. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  63006. 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)))));
  63007. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  63008. 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)))));
  63009. };
  63010. return SIMDMatrix;
  63011. }());
  63012. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  63013. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  63014. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  63015. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  63016. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  63017. var SIMDHelper = (function () {
  63018. function SIMDHelper() {
  63019. }
  63020. Object.defineProperty(SIMDHelper, "IsEnabled", {
  63021. get: function () {
  63022. return SIMDHelper._isEnabled;
  63023. },
  63024. enumerable: true,
  63025. configurable: true
  63026. });
  63027. SIMDHelper.DisableSIMD = function () {
  63028. // Replace functions
  63029. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  63030. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  63031. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  63032. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  63033. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  63034. SIMDHelper._isEnabled = false;
  63035. };
  63036. SIMDHelper.EnableSIMD = function () {
  63037. if (self.SIMD === undefined) {
  63038. return;
  63039. }
  63040. // check if polyfills needed
  63041. if (!self.Math.fround) {
  63042. self.Math.fround = (function (array) { return function (x) {
  63043. return array[0] = x, array[0];
  63044. }; })(new Float32Array(1));
  63045. }
  63046. if (!self.Math.imul) {
  63047. self.Math.imul = function (a, b) {
  63048. var ah = (a >>> 16) & 0xffff;
  63049. var al = a & 0xffff;
  63050. var bh = (b >>> 16) & 0xffff;
  63051. var bl = b & 0xffff;
  63052. // the shift by 0 fixes the sign on the high part
  63053. // the final |0 converts the unsigned value into a signed value
  63054. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  63055. };
  63056. }
  63057. // Replace functions
  63058. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  63059. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  63060. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  63061. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  63062. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  63063. SIMDHelper._isEnabled = true;
  63064. };
  63065. return SIMDHelper;
  63066. }());
  63067. SIMDHelper._isEnabled = false;
  63068. BABYLON.SIMDHelper = SIMDHelper;
  63069. })(BABYLON || (BABYLON = {}));
  63070. //# sourceMappingURL=babylon.math.SIMD.js.map
  63071. var BABYLON;
  63072. (function (BABYLON) {
  63073. var VRDistortionCorrectionPostProcess = (function (_super) {
  63074. __extends(VRDistortionCorrectionPostProcess, _super);
  63075. //ANY
  63076. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  63077. var _this = _super.call(this, name, "vrDistortionCorrection", [
  63078. 'LensCenter',
  63079. 'Scale',
  63080. 'ScaleIn',
  63081. 'HmdWarpParam'
  63082. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  63083. _this._isRightEye = isRightEye;
  63084. _this._distortionFactors = vrMetrics.distortionK;
  63085. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  63086. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  63087. _this.onSizeChangedObservable.add(function () {
  63088. _this.aspectRatio = _this.width * .5 / _this.height;
  63089. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  63090. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  63091. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  63092. });
  63093. _this.onApplyObservable.add(function (effect) {
  63094. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  63095. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  63096. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  63097. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  63098. });
  63099. return _this;
  63100. }
  63101. return VRDistortionCorrectionPostProcess;
  63102. }(BABYLON.PostProcess));
  63103. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  63104. })(BABYLON || (BABYLON = {}));
  63105. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  63106. var BABYLON;
  63107. (function (BABYLON) {
  63108. var AnaglyphPostProcess = (function (_super) {
  63109. __extends(AnaglyphPostProcess, _super);
  63110. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  63111. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  63112. _this._passedProcess = rigCameras[0]._rigPostProcess;
  63113. _this.onApplyObservable.add(function (effect) {
  63114. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  63115. });
  63116. return _this;
  63117. }
  63118. return AnaglyphPostProcess;
  63119. }(BABYLON.PostProcess));
  63120. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  63121. })(BABYLON || (BABYLON = {}));
  63122. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  63123. var BABYLON;
  63124. (function (BABYLON) {
  63125. var StereoscopicInterlacePostProcess = (function (_super) {
  63126. __extends(StereoscopicInterlacePostProcess, _super);
  63127. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  63128. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  63129. _this._passedProcess = rigCameras[0]._rigPostProcess;
  63130. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  63131. _this.onSizeChangedObservable.add(function () {
  63132. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  63133. });
  63134. _this.onApplyObservable.add(function (effect) {
  63135. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  63136. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  63137. });
  63138. return _this;
  63139. }
  63140. return StereoscopicInterlacePostProcess;
  63141. }(BABYLON.PostProcess));
  63142. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  63143. })(BABYLON || (BABYLON = {}));
  63144. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  63145. var BABYLON;
  63146. (function (BABYLON) {
  63147. var FreeCameraDeviceOrientationInput = (function () {
  63148. function FreeCameraDeviceOrientationInput() {
  63149. var _this = this;
  63150. this._screenOrientationAngle = 0;
  63151. this._screenQuaternion = new BABYLON.Quaternion();
  63152. this._alpha = 0;
  63153. this._beta = 0;
  63154. this._gamma = 0;
  63155. this._orientationChanged = function () {
  63156. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  63157. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  63158. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  63159. };
  63160. this._deviceOrientation = function (evt) {
  63161. _this._alpha = evt.alpha;
  63162. _this._beta = evt.beta;
  63163. _this._gamma = evt.gamma;
  63164. };
  63165. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  63166. this._orientationChanged();
  63167. }
  63168. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  63169. get: function () {
  63170. return this._camera;
  63171. },
  63172. set: function (camera) {
  63173. this._camera = camera;
  63174. if (!this._camera.rotationQuaternion)
  63175. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  63176. },
  63177. enumerable: true,
  63178. configurable: true
  63179. });
  63180. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  63181. window.addEventListener("orientationchange", this._orientationChanged);
  63182. window.addEventListener("deviceorientation", this._deviceOrientation);
  63183. //In certain cases, the attach control is called AFTER orientation was changed,
  63184. //So this is needed.
  63185. this._orientationChanged();
  63186. };
  63187. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  63188. window.removeEventListener("orientationchange", this._orientationChanged);
  63189. window.removeEventListener("deviceorientation", this._deviceOrientation);
  63190. };
  63191. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  63192. //if no device orientation provided, don't update the rotation.
  63193. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  63194. if (!this._alpha)
  63195. return;
  63196. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  63197. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  63198. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  63199. //Mirror on XY Plane
  63200. this._camera.rotationQuaternion.z *= -1;
  63201. this._camera.rotationQuaternion.w *= -1;
  63202. };
  63203. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  63204. return "FreeCameraDeviceOrientationInput";
  63205. };
  63206. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  63207. return "deviceOrientation";
  63208. };
  63209. return FreeCameraDeviceOrientationInput;
  63210. }());
  63211. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  63212. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  63213. })(BABYLON || (BABYLON = {}));
  63214. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  63215. var BABYLON;
  63216. (function (BABYLON) {
  63217. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  63218. function ArcRotateCameraVRDeviceOrientationInput() {
  63219. this.alphaCorrection = 1;
  63220. this.betaCorrection = 1;
  63221. this.gammaCorrection = 1;
  63222. this._alpha = 0;
  63223. this._beta = 0;
  63224. this._gamma = 0;
  63225. this._dirty = false;
  63226. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  63227. }
  63228. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  63229. this.camera.attachControl(element, noPreventDefault);
  63230. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  63231. };
  63232. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  63233. var camera = this.camera;
  63234. this._alpha = +evt.alpha | 0;
  63235. this._beta = +evt.beta | 0;
  63236. this._gamma = +evt.gamma | 0;
  63237. this._dirty = true;
  63238. };
  63239. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  63240. if (this._dirty) {
  63241. this._dirty = false;
  63242. if (this._gamma < 0) {
  63243. this._gamma = 180 + this._gamma;
  63244. }
  63245. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  63246. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  63247. }
  63248. };
  63249. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  63250. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  63251. };
  63252. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  63253. return "ArcRotateCameraVRDeviceOrientationInput";
  63254. };
  63255. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  63256. return "VRDeviceOrientation";
  63257. };
  63258. return ArcRotateCameraVRDeviceOrientationInput;
  63259. }());
  63260. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  63261. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  63262. })(BABYLON || (BABYLON = {}));
  63263. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  63264. var BABYLON;
  63265. (function (BABYLON) {
  63266. var VRCameraMetrics = (function () {
  63267. function VRCameraMetrics() {
  63268. this.compensateDistortion = true;
  63269. }
  63270. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  63271. get: function () {
  63272. return this.hResolution / (2 * this.vResolution);
  63273. },
  63274. enumerable: true,
  63275. configurable: true
  63276. });
  63277. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  63278. get: function () {
  63279. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  63280. },
  63281. enumerable: true,
  63282. configurable: true
  63283. });
  63284. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  63285. get: function () {
  63286. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  63287. var h = (4 * meters) / this.hScreenSize;
  63288. return BABYLON.Matrix.Translation(h, 0, 0);
  63289. },
  63290. enumerable: true,
  63291. configurable: true
  63292. });
  63293. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  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, "leftPreViewMatrix", {
  63303. get: function () {
  63304. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  63305. },
  63306. enumerable: true,
  63307. configurable: true
  63308. });
  63309. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  63310. get: function () {
  63311. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  63312. },
  63313. enumerable: true,
  63314. configurable: true
  63315. });
  63316. VRCameraMetrics.GetDefault = function () {
  63317. var result = new VRCameraMetrics();
  63318. result.hResolution = 1280;
  63319. result.vResolution = 800;
  63320. result.hScreenSize = 0.149759993;
  63321. result.vScreenSize = 0.0935999975;
  63322. result.vScreenCenter = 0.0467999987;
  63323. result.eyeToScreenDistance = 0.0410000011;
  63324. result.lensSeparationDistance = 0.0635000020;
  63325. result.interpupillaryDistance = 0.0640000030;
  63326. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  63327. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  63328. result.postProcessScaleFactor = 1.714605507808412;
  63329. result.lensCenterOffset = 0.151976421;
  63330. return result;
  63331. };
  63332. return VRCameraMetrics;
  63333. }());
  63334. BABYLON.VRCameraMetrics = VRCameraMetrics;
  63335. })(BABYLON || (BABYLON = {}));
  63336. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  63337. var BABYLON;
  63338. (function (BABYLON) {
  63339. var WebVRFreeCamera = (function (_super) {
  63340. __extends(WebVRFreeCamera, _super);
  63341. function WebVRFreeCamera(name, position, scene, webVROptions) {
  63342. if (webVROptions === void 0) { webVROptions = {}; }
  63343. var _this = _super.call(this, name, position, scene) || this;
  63344. _this.webVROptions = webVROptions;
  63345. _this._vrDevice = null;
  63346. _this.rawPose = null;
  63347. _this._vrEnabled = false;
  63348. _this._specsVersion = 1.1;
  63349. _this._attached = false;
  63350. _this._positionOffset = BABYLON.Vector3.Zero();
  63351. _this._descendants = [];
  63352. _this.devicePosition = BABYLON.Vector3.Zero();
  63353. _this.deviceScaleFactor = 1;
  63354. _this.controllers = [];
  63355. _this.nonVRControllers = [];
  63356. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  63357. //legacy support - the compensation boolean was removed.
  63358. if (arguments.length === 5) {
  63359. _this.webVROptions = arguments[4];
  63360. }
  63361. // default webVR options
  63362. if (_this.webVROptions.trackPosition == undefined) {
  63363. _this.webVROptions.trackPosition = true;
  63364. }
  63365. if (_this.webVROptions.controllerMeshes == undefined) {
  63366. _this.webVROptions.controllerMeshes = true;
  63367. }
  63368. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  63369. _this.webVROptions.defaultLightningOnControllers = true;
  63370. }
  63371. _this.rotationQuaternion = new BABYLON.Quaternion();
  63372. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63373. if (_this.webVROptions && _this.webVROptions.positionScale) {
  63374. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  63375. }
  63376. //enable VR
  63377. _this.getEngine().initWebVR();
  63378. //check specs version
  63379. if (!window.VRFrameData) {
  63380. _this._specsVersion = 1.0;
  63381. _this._frameData = {};
  63382. }
  63383. else {
  63384. _this._frameData = new VRFrameData();
  63385. }
  63386. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  63387. if (!device) {
  63388. return;
  63389. }
  63390. _this._vrEnabled = true;
  63391. _this._vrDevice = device;
  63392. //reset the rig parameters.
  63393. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  63394. if (_this._attached) {
  63395. _this.getEngine().enableVR(_this._vrDevice);
  63396. }
  63397. });
  63398. // try to attach the controllers, if found.
  63399. _this.initControllers();
  63400. /**
  63401. * The idea behind the following lines:
  63402. * objects that have the camera as parent should actually have the rig cameras as a parent.
  63403. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  63404. * the second will not show it correctly.
  63405. *
  63406. * To solve this - each object that has the camera as parent will be added to a protected array.
  63407. * When the rig camera renders, it will take this array and set all of those to be its children.
  63408. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  63409. * Amazing!
  63410. */
  63411. scene.onBeforeCameraRenderObservable.add(function (camera) {
  63412. if (camera.parent === _this && _this.rigParenting) {
  63413. _this._descendants = _this.getDescendants(true, function (n) {
  63414. // don't take the cameras or the controllers!
  63415. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  63416. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  63417. return !isController && !isRigCamera;
  63418. });
  63419. _this._descendants.forEach(function (node) {
  63420. node.parent = camera;
  63421. });
  63422. }
  63423. });
  63424. scene.onAfterCameraRenderObservable.add(function (camera) {
  63425. if (camera.parent === _this && _this.rigParenting) {
  63426. _this._descendants.forEach(function (node) {
  63427. node.parent = _this;
  63428. });
  63429. }
  63430. });
  63431. return _this;
  63432. }
  63433. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  63434. set: function (callback) {
  63435. this._onControllersAttached = callback;
  63436. // after setting - if the controllers are already set, execute the callback.
  63437. if (this.controllers.length >= 2) {
  63438. callback(this.controllers);
  63439. }
  63440. },
  63441. enumerable: true,
  63442. configurable: true
  63443. });
  63444. Object.defineProperty(WebVRFreeCamera.prototype, "onNonVRControllerAttached", {
  63445. set: function (callback) {
  63446. this._onNonVRControllerAttached = callback;
  63447. this.nonVRControllers.forEach(function (controller) {
  63448. callback(controller);
  63449. });
  63450. },
  63451. enumerable: true,
  63452. configurable: true
  63453. });
  63454. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  63455. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  63456. var gp = _a[_i];
  63457. if (gp.hand === name) {
  63458. return gp;
  63459. }
  63460. }
  63461. return undefined;
  63462. };
  63463. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  63464. get: function () {
  63465. if (!this._leftController) {
  63466. this._leftController = this.getControllerByName("left");
  63467. }
  63468. return this._leftController;
  63469. },
  63470. enumerable: true,
  63471. configurable: true
  63472. });
  63473. ;
  63474. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  63475. get: function () {
  63476. if (!this._rightController) {
  63477. this._rightController = this.getControllerByName("right");
  63478. }
  63479. return this._rightController;
  63480. },
  63481. enumerable: true,
  63482. configurable: true
  63483. });
  63484. ;
  63485. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  63486. if (length === void 0) { length = 100; }
  63487. if (this.leftCamera) {
  63488. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  63489. }
  63490. else {
  63491. return _super.prototype.getForwardRay.call(this, length);
  63492. }
  63493. };
  63494. WebVRFreeCamera.prototype._checkInputs = function () {
  63495. if (this._vrEnabled) {
  63496. if (this._specsVersion === 1.1) {
  63497. this._vrDevice.getFrameData(this._frameData);
  63498. }
  63499. else {
  63500. //backwards comp
  63501. var pose = this._vrDevice.getPose();
  63502. this._frameData.pose = pose;
  63503. // calculate view and projection matrix
  63504. }
  63505. this.updateFromDevice(this._frameData.pose);
  63506. }
  63507. _super.prototype._checkInputs.call(this);
  63508. };
  63509. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  63510. if (poseData && poseData.orientation) {
  63511. this.rawPose = poseData;
  63512. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  63513. if (this.getScene().useRightHandedSystem) {
  63514. this.deviceRotationQuaternion.z *= -1;
  63515. this.deviceRotationQuaternion.w *= -1;
  63516. }
  63517. if (this.webVROptions.trackPosition && this.rawPose.position) {
  63518. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  63519. if (this.getScene().useRightHandedSystem) {
  63520. this.devicePosition.z *= -1;
  63521. }
  63522. }
  63523. }
  63524. };
  63525. /**
  63526. * WebVR's attach control will start broadcasting frames to the device.
  63527. * Note that in certain browsers (chrome for example) this function must be called
  63528. * within a user-interaction callback. Example:
  63529. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  63530. *
  63531. * @param {HTMLElement} element
  63532. * @param {boolean} [noPreventDefault]
  63533. *
  63534. * @memberOf WebVRFreeCamera
  63535. */
  63536. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  63537. _super.prototype.attachControl.call(this, element, noPreventDefault);
  63538. this._attached = true;
  63539. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  63540. if (this._vrEnabled) {
  63541. this.getEngine().enableVR(this._vrDevice);
  63542. }
  63543. };
  63544. WebVRFreeCamera.prototype.detachControl = function (element) {
  63545. _super.prototype.detachControl.call(this, element);
  63546. this._vrEnabled = false;
  63547. this._attached = false;
  63548. this.getEngine().disableVR();
  63549. };
  63550. WebVRFreeCamera.prototype.getClassName = function () {
  63551. return "WebVRFreeCamera";
  63552. };
  63553. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  63554. //uses the vrDisplay's "resetPose()".
  63555. //pitch and roll won't be affected.
  63556. this._vrDevice.resetPose();
  63557. };
  63558. WebVRFreeCamera.prototype._updateRigCameras = function () {
  63559. var camLeft = this._rigCameras[0];
  63560. var camRight = this._rigCameras[1];
  63561. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63562. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63563. camLeft.position.copyFrom(this.devicePosition);
  63564. camRight.position.copyFrom(this.devicePosition);
  63565. };
  63566. /**
  63567. * This function is called by the two RIG cameras.
  63568. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  63569. */
  63570. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  63571. var _this = this;
  63572. //WebVR 1.0
  63573. if (this._cameraRigParams["specs"] === 1.0) {
  63574. this._updateCameraRotationMatrix();
  63575. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  63576. // Computing target and final matrix
  63577. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  63578. if (this.getScene().useRightHandedSystem) {
  63579. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  63580. }
  63581. else {
  63582. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  63583. }
  63584. //now move the eye in the right direction
  63585. var eyeParams = this._cameraRigParams["eyeParameters"];
  63586. var offset = eyeParams.offset;
  63587. // it will actually always be 0, but just in case
  63588. if (this.getScene().useRightHandedSystem) {
  63589. offset[2] *= -1;
  63590. }
  63591. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  63592. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  63593. }
  63594. else {
  63595. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  63596. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  63597. if (!this.getScene().useRightHandedSystem) {
  63598. [2, 6, 8, 9, 14].forEach(function (num) {
  63599. _this._webvrViewMatrix.m[num] *= -1;
  63600. });
  63601. }
  63602. // update the camera rotation matrix
  63603. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  63604. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  63605. // Computing target and final matrix
  63606. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  63607. }
  63608. var parentCamera = this._cameraRigParams["parentCamera"];
  63609. // should the view matrix be updated with scale and position offset?
  63610. if (parentCamera.deviceScaleFactor !== 1) {
  63611. this._webvrViewMatrix.invert();
  63612. // scale the position, if set
  63613. if (parentCamera.deviceScaleFactor) {
  63614. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  63615. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  63616. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  63617. }
  63618. this._webvrViewMatrix.invert();
  63619. }
  63620. return this._webvrViewMatrix;
  63621. };
  63622. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  63623. var _this = this;
  63624. if (this._cameraRigParams["specs"] === 1.0) {
  63625. var eyeParams = this._cameraRigParams["eyeParameters"];
  63626. // deprecated!!
  63627. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  63628. }
  63629. else {
  63630. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  63631. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  63632. //babylon compatible matrix
  63633. if (!this.getScene().useRightHandedSystem) {
  63634. [8, 9, 10, 11].forEach(function (num) {
  63635. _this._projectionMatrix.m[num] *= -1;
  63636. });
  63637. }
  63638. }
  63639. return this._projectionMatrix;
  63640. };
  63641. WebVRFreeCamera.prototype.initControllers = function () {
  63642. var _this = this;
  63643. this.controllers = [];
  63644. new BABYLON.Gamepads(function (gp) {
  63645. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  63646. var webVrController = gp;
  63647. if (_this.webVROptions.controllerMeshes) {
  63648. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  63649. if (_this.webVROptions.defaultLightningOnControllers) {
  63650. if (!_this._lightOnControllers) {
  63651. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  63652. }
  63653. loadedMesh.getChildren().forEach(function (mesh) {
  63654. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  63655. });
  63656. }
  63657. });
  63658. }
  63659. webVrController.attachToPoseControlledCamera(_this);
  63660. // since this is async - sanity check. Is the controller already stored?
  63661. if (_this.controllers.indexOf(webVrController) === -1) {
  63662. //add to the controllers array
  63663. _this.controllers.push(webVrController);
  63664. //did we find enough controllers? Great! let the developer know.
  63665. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  63666. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  63667. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  63668. // So we're overriding setting left & right manually to be sure
  63669. var firstViveWandDetected = false;
  63670. for (var i = 0; i < _this.controllers.length; i++) {
  63671. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  63672. if (!firstViveWandDetected) {
  63673. firstViveWandDetected = true;
  63674. _this.controllers[i].hand = "left";
  63675. }
  63676. else {
  63677. _this.controllers[i].hand = "right";
  63678. }
  63679. }
  63680. }
  63681. _this._onControllersAttached(_this.controllers);
  63682. }
  63683. }
  63684. }
  63685. else {
  63686. _this.nonVRControllers.push(gp);
  63687. if (_this._onNonVRControllerAttached) {
  63688. _this._onNonVRControllerAttached(gp);
  63689. }
  63690. }
  63691. });
  63692. };
  63693. return WebVRFreeCamera;
  63694. }(BABYLON.FreeCamera));
  63695. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  63696. })(BABYLON || (BABYLON = {}));
  63697. //# sourceMappingURL=babylon.webVRCamera.js.map
  63698. /// <reference path="babylon.freeCamera.ts" />
  63699. var BABYLON;
  63700. (function (BABYLON) {
  63701. // We're mainly based on the logic defined into the FreeCamera code
  63702. var DeviceOrientationCamera = (function (_super) {
  63703. __extends(DeviceOrientationCamera, _super);
  63704. function DeviceOrientationCamera(name, position, scene) {
  63705. var _this = _super.call(this, name, position, scene) || this;
  63706. _this._quaternionCache = new BABYLON.Quaternion();
  63707. _this.inputs.addDeviceOrientation();
  63708. return _this;
  63709. }
  63710. DeviceOrientationCamera.prototype.getClassName = function () {
  63711. return "DeviceOrientationCamera";
  63712. };
  63713. DeviceOrientationCamera.prototype._checkInputs = function () {
  63714. _super.prototype._checkInputs.call(this);
  63715. this._quaternionCache.copyFrom(this.rotationQuaternion);
  63716. if (this._initialQuaternion) {
  63717. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  63718. }
  63719. };
  63720. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  63721. var _this = this;
  63722. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  63723. //can only work if this camera has a rotation quaternion already.
  63724. if (!this.rotationQuaternion)
  63725. return;
  63726. if (!this._initialQuaternion) {
  63727. this._initialQuaternion = new BABYLON.Quaternion();
  63728. }
  63729. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  63730. ['x', 'y', 'z'].forEach(function (axisName) {
  63731. if (!axis[axisName]) {
  63732. _this._initialQuaternion[axisName] = 0;
  63733. }
  63734. else {
  63735. _this._initialQuaternion[axisName] *= -1;
  63736. }
  63737. });
  63738. this._initialQuaternion.normalize();
  63739. //force rotation update
  63740. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  63741. };
  63742. return DeviceOrientationCamera;
  63743. }(BABYLON.FreeCamera));
  63744. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  63745. })(BABYLON || (BABYLON = {}));
  63746. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  63747. var BABYLON;
  63748. (function (BABYLON) {
  63749. var VRDeviceOrientationFreeCamera = (function (_super) {
  63750. __extends(VRDeviceOrientationFreeCamera, _super);
  63751. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  63752. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63753. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63754. var _this = _super.call(this, name, position, scene) || this;
  63755. vrCameraMetrics.compensateDistortion = compensateDistortion;
  63756. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  63757. return _this;
  63758. }
  63759. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  63760. return "VRDeviceOrientationFreeCamera";
  63761. };
  63762. return VRDeviceOrientationFreeCamera;
  63763. }(BABYLON.DeviceOrientationCamera));
  63764. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  63765. var VRDeviceOrientationGamepadCamera = (function (_super) {
  63766. __extends(VRDeviceOrientationGamepadCamera, _super);
  63767. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  63768. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63769. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63770. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  63771. _this.inputs.addGamepad();
  63772. return _this;
  63773. }
  63774. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  63775. return "VRDeviceOrientationGamepadCamera";
  63776. };
  63777. return VRDeviceOrientationGamepadCamera;
  63778. }(VRDeviceOrientationFreeCamera));
  63779. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  63780. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  63781. __extends(VRDeviceOrientationArcRotateCamera, _super);
  63782. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  63783. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63784. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63785. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63786. vrCameraMetrics.compensateDistortion = compensateDistortion;
  63787. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  63788. _this.inputs.addVRDeviceOrientation();
  63789. return _this;
  63790. }
  63791. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  63792. return "VRDeviceOrientationArcRotateCamera";
  63793. };
  63794. return VRDeviceOrientationArcRotateCamera;
  63795. }(BABYLON.ArcRotateCamera));
  63796. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  63797. })(BABYLON || (BABYLON = {}));
  63798. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  63799. /// <reference path="babylon.freeCamera.ts" />
  63800. /// <reference path="babylon.arcRotateCamera.ts" />
  63801. /// <reference path="babylon.gamepadCamera.ts" />
  63802. /// <reference path="babylon.universalCamera.ts" />
  63803. var BABYLON;
  63804. (function (BABYLON) {
  63805. var AnaglyphFreeCamera = (function (_super) {
  63806. __extends(AnaglyphFreeCamera, _super);
  63807. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  63808. var _this = _super.call(this, name, position, scene) || this;
  63809. _this.interaxialDistance = interaxialDistance;
  63810. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63811. return _this;
  63812. }
  63813. AnaglyphFreeCamera.prototype.getClassName = function () {
  63814. return "AnaglyphFreeCamera";
  63815. };
  63816. return AnaglyphFreeCamera;
  63817. }(BABYLON.FreeCamera));
  63818. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  63819. var AnaglyphArcRotateCamera = (function (_super) {
  63820. __extends(AnaglyphArcRotateCamera, _super);
  63821. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  63822. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63823. _this.interaxialDistance = interaxialDistance;
  63824. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63825. return _this;
  63826. }
  63827. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  63828. return "AnaglyphArcRotateCamera";
  63829. };
  63830. return AnaglyphArcRotateCamera;
  63831. }(BABYLON.ArcRotateCamera));
  63832. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  63833. var AnaglyphGamepadCamera = (function (_super) {
  63834. __extends(AnaglyphGamepadCamera, _super);
  63835. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  63836. var _this = _super.call(this, name, position, scene) || this;
  63837. _this.interaxialDistance = interaxialDistance;
  63838. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63839. return _this;
  63840. }
  63841. AnaglyphGamepadCamera.prototype.getClassName = function () {
  63842. return "AnaglyphGamepadCamera";
  63843. };
  63844. return AnaglyphGamepadCamera;
  63845. }(BABYLON.GamepadCamera));
  63846. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  63847. var AnaglyphUniversalCamera = (function (_super) {
  63848. __extends(AnaglyphUniversalCamera, _super);
  63849. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  63850. var _this = _super.call(this, name, position, scene) || this;
  63851. _this.interaxialDistance = interaxialDistance;
  63852. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63853. return _this;
  63854. }
  63855. AnaglyphUniversalCamera.prototype.getClassName = function () {
  63856. return "AnaglyphUniversalCamera";
  63857. };
  63858. return AnaglyphUniversalCamera;
  63859. }(BABYLON.UniversalCamera));
  63860. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  63861. var StereoscopicFreeCamera = (function (_super) {
  63862. __extends(StereoscopicFreeCamera, _super);
  63863. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63864. var _this = _super.call(this, name, position, scene) || this;
  63865. _this.interaxialDistance = interaxialDistance;
  63866. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63867. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63868. return _this;
  63869. }
  63870. StereoscopicFreeCamera.prototype.getClassName = function () {
  63871. return "StereoscopicFreeCamera";
  63872. };
  63873. return StereoscopicFreeCamera;
  63874. }(BABYLON.FreeCamera));
  63875. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  63876. var StereoscopicArcRotateCamera = (function (_super) {
  63877. __extends(StereoscopicArcRotateCamera, _super);
  63878. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  63879. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63880. _this.interaxialDistance = interaxialDistance;
  63881. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63882. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63883. return _this;
  63884. }
  63885. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  63886. return "StereoscopicArcRotateCamera";
  63887. };
  63888. return StereoscopicArcRotateCamera;
  63889. }(BABYLON.ArcRotateCamera));
  63890. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  63891. var StereoscopicGamepadCamera = (function (_super) {
  63892. __extends(StereoscopicGamepadCamera, _super);
  63893. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63894. var _this = _super.call(this, name, position, scene) || this;
  63895. _this.interaxialDistance = interaxialDistance;
  63896. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63897. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63898. return _this;
  63899. }
  63900. StereoscopicGamepadCamera.prototype.getClassName = function () {
  63901. return "StereoscopicGamepadCamera";
  63902. };
  63903. return StereoscopicGamepadCamera;
  63904. }(BABYLON.GamepadCamera));
  63905. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  63906. var StereoscopicUniversalCamera = (function (_super) {
  63907. __extends(StereoscopicUniversalCamera, _super);
  63908. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63909. var _this = _super.call(this, name, position, scene) || this;
  63910. _this.interaxialDistance = interaxialDistance;
  63911. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63912. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63913. return _this;
  63914. }
  63915. StereoscopicUniversalCamera.prototype.getClassName = function () {
  63916. return "StereoscopicUniversalCamera";
  63917. };
  63918. return StereoscopicUniversalCamera;
  63919. }(BABYLON.UniversalCamera));
  63920. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  63921. })(BABYLON || (BABYLON = {}));
  63922. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  63923. // Mainly based on these 2 articles :
  63924. // 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
  63925. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  63926. var BABYLON;
  63927. (function (BABYLON) {
  63928. var JoystickAxis;
  63929. (function (JoystickAxis) {
  63930. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  63931. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  63932. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  63933. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  63934. var VirtualJoystick = (function () {
  63935. function VirtualJoystick(leftJoystick) {
  63936. var _this = this;
  63937. if (leftJoystick) {
  63938. this._leftJoystick = true;
  63939. }
  63940. else {
  63941. this._leftJoystick = false;
  63942. }
  63943. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  63944. VirtualJoystick._globalJoystickIndex++;
  63945. // By default left & right arrow keys are moving the X
  63946. // and up & down keys are moving the Y
  63947. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  63948. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  63949. this.reverseLeftRight = false;
  63950. this.reverseUpDown = false;
  63951. // collections of pointers
  63952. this._touches = new BABYLON.StringDictionary();
  63953. this.deltaPosition = BABYLON.Vector3.Zero();
  63954. this._joystickSensibility = 25;
  63955. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  63956. this._rotationSpeed = 25;
  63957. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  63958. this._rotateOnAxisRelativeToMesh = false;
  63959. this._onResize = function (evt) {
  63960. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  63961. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  63962. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  63963. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  63964. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  63965. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  63966. };
  63967. // injecting a canvas element on top of the canvas 3D game
  63968. if (!VirtualJoystick.vjCanvas) {
  63969. window.addEventListener("resize", this._onResize, false);
  63970. VirtualJoystick.vjCanvas = document.createElement("canvas");
  63971. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  63972. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  63973. VirtualJoystick.vjCanvas.width = window.innerWidth;
  63974. VirtualJoystick.vjCanvas.height = window.innerHeight;
  63975. VirtualJoystick.vjCanvas.style.width = "100%";
  63976. VirtualJoystick.vjCanvas.style.height = "100%";
  63977. VirtualJoystick.vjCanvas.style.position = "absolute";
  63978. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  63979. VirtualJoystick.vjCanvas.style.top = "0px";
  63980. VirtualJoystick.vjCanvas.style.left = "0px";
  63981. VirtualJoystick.vjCanvas.style.zIndex = "5";
  63982. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  63983. // Support for jQuery PEP polyfill
  63984. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  63985. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  63986. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  63987. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  63988. document.body.appendChild(VirtualJoystick.vjCanvas);
  63989. }
  63990. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  63991. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  63992. this.pressed = false;
  63993. // default joystick color
  63994. this._joystickColor = "cyan";
  63995. this._joystickPointerID = -1;
  63996. // current joystick position
  63997. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  63998. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  63999. // origin joystick position
  64000. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  64001. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  64002. this._onPointerDownHandlerRef = function (evt) {
  64003. _this._onPointerDown(evt);
  64004. };
  64005. this._onPointerMoveHandlerRef = function (evt) {
  64006. _this._onPointerMove(evt);
  64007. };
  64008. this._onPointerOutHandlerRef = function (evt) {
  64009. _this._onPointerUp(evt);
  64010. };
  64011. this._onPointerUpHandlerRef = function (evt) {
  64012. _this._onPointerUp(evt);
  64013. };
  64014. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  64015. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  64016. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  64017. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  64018. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  64019. evt.preventDefault(); // Disables system menu
  64020. }, false);
  64021. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  64022. }
  64023. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  64024. this._joystickSensibility = newJoystickSensibility;
  64025. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  64026. };
  64027. VirtualJoystick.prototype._onPointerDown = function (e) {
  64028. var positionOnScreenCondition;
  64029. e.preventDefault();
  64030. if (this._leftJoystick === true) {
  64031. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  64032. }
  64033. else {
  64034. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  64035. }
  64036. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  64037. // First contact will be dedicated to the virtual joystick
  64038. this._joystickPointerID = e.pointerId;
  64039. this._joystickPointerStartPos.x = e.clientX;
  64040. this._joystickPointerStartPos.y = e.clientY;
  64041. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  64042. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  64043. this._deltaJoystickVector.x = 0;
  64044. this._deltaJoystickVector.y = 0;
  64045. this.pressed = true;
  64046. this._touches.add(e.pointerId.toString(), e);
  64047. }
  64048. else {
  64049. // You can only trigger the action buttons with a joystick declared
  64050. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  64051. this._action();
  64052. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  64053. }
  64054. }
  64055. };
  64056. VirtualJoystick.prototype._onPointerMove = function (e) {
  64057. // If the current pointer is the one associated to the joystick (first touch contact)
  64058. if (this._joystickPointerID == e.pointerId) {
  64059. this._joystickPointerPos.x = e.clientX;
  64060. this._joystickPointerPos.y = e.clientY;
  64061. this._deltaJoystickVector = this._joystickPointerPos.clone();
  64062. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  64063. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  64064. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  64065. switch (this._axisTargetedByLeftAndRight) {
  64066. case JoystickAxis.X:
  64067. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  64068. break;
  64069. case JoystickAxis.Y:
  64070. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  64071. break;
  64072. case JoystickAxis.Z:
  64073. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  64074. break;
  64075. }
  64076. var directionUpDown = this.reverseUpDown ? 1 : -1;
  64077. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  64078. switch (this._axisTargetedByUpAndDown) {
  64079. case JoystickAxis.X:
  64080. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  64081. break;
  64082. case JoystickAxis.Y:
  64083. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  64084. break;
  64085. case JoystickAxis.Z:
  64086. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  64087. break;
  64088. }
  64089. }
  64090. else {
  64091. var data = this._touches.get(e.pointerId.toString());
  64092. if (data) {
  64093. data.x = e.clientX;
  64094. data.y = e.clientY;
  64095. }
  64096. }
  64097. };
  64098. VirtualJoystick.prototype._onPointerUp = function (e) {
  64099. if (this._joystickPointerID == e.pointerId) {
  64100. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  64101. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  64102. this._joystickPointerID = -1;
  64103. this.pressed = false;
  64104. }
  64105. else {
  64106. var touch = this._touches.get(e.pointerId.toString());
  64107. if (touch) {
  64108. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  64109. }
  64110. }
  64111. this._deltaJoystickVector.x = 0;
  64112. this._deltaJoystickVector.y = 0;
  64113. this._touches.remove(e.pointerId.toString());
  64114. };
  64115. /**
  64116. * Change the color of the virtual joystick
  64117. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  64118. */
  64119. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  64120. this._joystickColor = newColor;
  64121. };
  64122. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  64123. this._action = action;
  64124. };
  64125. // Define which axis you'd like to control for left & right
  64126. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  64127. switch (axis) {
  64128. case JoystickAxis.X:
  64129. case JoystickAxis.Y:
  64130. case JoystickAxis.Z:
  64131. this._axisTargetedByLeftAndRight = axis;
  64132. break;
  64133. default:
  64134. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  64135. break;
  64136. }
  64137. };
  64138. // Define which axis you'd like to control for up & down
  64139. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  64140. switch (axis) {
  64141. case JoystickAxis.X:
  64142. case JoystickAxis.Y:
  64143. case JoystickAxis.Z:
  64144. this._axisTargetedByUpAndDown = axis;
  64145. break;
  64146. default:
  64147. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  64148. break;
  64149. }
  64150. };
  64151. VirtualJoystick.prototype._clearCanvas = function () {
  64152. if (this._leftJoystick) {
  64153. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  64154. }
  64155. else {
  64156. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  64157. }
  64158. };
  64159. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  64160. var _this = this;
  64161. if (this.pressed) {
  64162. this._touches.forEach(function (key, touch) {
  64163. if (touch.pointerId === _this._joystickPointerID) {
  64164. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  64165. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  64166. VirtualJoystick.vjCanvasContext.beginPath();
  64167. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  64168. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64169. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  64170. VirtualJoystick.vjCanvasContext.stroke();
  64171. VirtualJoystick.vjCanvasContext.closePath();
  64172. VirtualJoystick.vjCanvasContext.beginPath();
  64173. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64174. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  64175. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  64176. VirtualJoystick.vjCanvasContext.stroke();
  64177. VirtualJoystick.vjCanvasContext.closePath();
  64178. VirtualJoystick.vjCanvasContext.beginPath();
  64179. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64180. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  64181. VirtualJoystick.vjCanvasContext.stroke();
  64182. VirtualJoystick.vjCanvasContext.closePath();
  64183. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  64184. }
  64185. else {
  64186. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  64187. VirtualJoystick.vjCanvasContext.beginPath();
  64188. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  64189. VirtualJoystick.vjCanvasContext.beginPath();
  64190. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  64191. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  64192. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  64193. VirtualJoystick.vjCanvasContext.stroke();
  64194. VirtualJoystick.vjCanvasContext.closePath();
  64195. touch.prevX = touch.x;
  64196. touch.prevY = touch.y;
  64197. }
  64198. ;
  64199. });
  64200. }
  64201. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  64202. };
  64203. VirtualJoystick.prototype.releaseCanvas = function () {
  64204. if (VirtualJoystick.vjCanvas) {
  64205. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  64206. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  64207. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  64208. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  64209. window.removeEventListener("resize", this._onResize);
  64210. document.body.removeChild(VirtualJoystick.vjCanvas);
  64211. VirtualJoystick.vjCanvas = null;
  64212. }
  64213. };
  64214. return VirtualJoystick;
  64215. }());
  64216. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  64217. VirtualJoystick._globalJoystickIndex = 0;
  64218. BABYLON.VirtualJoystick = VirtualJoystick;
  64219. })(BABYLON || (BABYLON = {}));
  64220. //# sourceMappingURL=babylon.virtualJoystick.js.map
  64221. var BABYLON;
  64222. (function (BABYLON) {
  64223. // We're mainly based on the logic defined into the FreeCamera code
  64224. var VirtualJoysticksCamera = (function (_super) {
  64225. __extends(VirtualJoysticksCamera, _super);
  64226. function VirtualJoysticksCamera(name, position, scene) {
  64227. var _this = _super.call(this, name, position, scene) || this;
  64228. _this.inputs.addVirtualJoystick();
  64229. return _this;
  64230. }
  64231. VirtualJoysticksCamera.prototype.getClassName = function () {
  64232. return "VirtualJoysticksCamera";
  64233. };
  64234. return VirtualJoysticksCamera;
  64235. }(BABYLON.FreeCamera));
  64236. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  64237. })(BABYLON || (BABYLON = {}));
  64238. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  64239. var BABYLON;
  64240. (function (BABYLON) {
  64241. var FreeCameraVirtualJoystickInput = (function () {
  64242. function FreeCameraVirtualJoystickInput() {
  64243. }
  64244. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  64245. return this._leftjoystick;
  64246. };
  64247. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  64248. return this._rightjoystick;
  64249. };
  64250. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  64251. if (this._leftjoystick) {
  64252. var camera = this.camera;
  64253. var speed = camera._computeLocalCameraSpeed() * 50;
  64254. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  64255. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  64256. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  64257. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  64258. if (!this._leftjoystick.pressed) {
  64259. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  64260. }
  64261. if (!this._rightjoystick.pressed) {
  64262. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  64263. }
  64264. }
  64265. };
  64266. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  64267. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  64268. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  64269. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  64270. this._leftjoystick.setJoystickSensibility(0.15);
  64271. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  64272. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  64273. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  64274. this._rightjoystick.reverseUpDown = true;
  64275. this._rightjoystick.setJoystickSensibility(0.05);
  64276. this._rightjoystick.setJoystickColor("yellow");
  64277. };
  64278. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  64279. this._leftjoystick.releaseCanvas();
  64280. this._rightjoystick.releaseCanvas();
  64281. };
  64282. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  64283. return "FreeCameraVirtualJoystickInput";
  64284. };
  64285. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  64286. return "virtualJoystick";
  64287. };
  64288. return FreeCameraVirtualJoystickInput;
  64289. }());
  64290. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  64291. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  64292. })(BABYLON || (BABYLON = {}));
  64293. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  64294. var BABYLON;
  64295. (function (BABYLON) {
  64296. var SimplificationSettings = (function () {
  64297. function SimplificationSettings(quality, distance, optimizeMesh) {
  64298. this.quality = quality;
  64299. this.distance = distance;
  64300. this.optimizeMesh = optimizeMesh;
  64301. }
  64302. return SimplificationSettings;
  64303. }());
  64304. BABYLON.SimplificationSettings = SimplificationSettings;
  64305. var SimplificationQueue = (function () {
  64306. function SimplificationQueue() {
  64307. this.running = false;
  64308. this._simplificationArray = [];
  64309. }
  64310. SimplificationQueue.prototype.addTask = function (task) {
  64311. this._simplificationArray.push(task);
  64312. };
  64313. SimplificationQueue.prototype.executeNext = function () {
  64314. var task = this._simplificationArray.pop();
  64315. if (task) {
  64316. this.running = true;
  64317. this.runSimplification(task);
  64318. }
  64319. else {
  64320. this.running = false;
  64321. }
  64322. };
  64323. SimplificationQueue.prototype.runSimplification = function (task) {
  64324. var _this = this;
  64325. if (task.parallelProcessing) {
  64326. //parallel simplifier
  64327. task.settings.forEach(function (setting) {
  64328. var simplifier = _this.getSimplifier(task);
  64329. simplifier.simplify(setting, function (newMesh) {
  64330. task.mesh.addLODLevel(setting.distance, newMesh);
  64331. newMesh.isVisible = true;
  64332. //check if it is the last
  64333. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  64334. //all done, run the success callback.
  64335. task.successCallback();
  64336. }
  64337. _this.executeNext();
  64338. });
  64339. });
  64340. }
  64341. else {
  64342. //single simplifier.
  64343. var simplifier = this.getSimplifier(task);
  64344. var runDecimation = function (setting, callback) {
  64345. simplifier.simplify(setting, function (newMesh) {
  64346. task.mesh.addLODLevel(setting.distance, newMesh);
  64347. newMesh.isVisible = true;
  64348. //run the next quality level
  64349. callback();
  64350. });
  64351. };
  64352. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  64353. runDecimation(task.settings[loop.index], function () {
  64354. loop.executeNext();
  64355. });
  64356. }, function () {
  64357. //execution ended, run the success callback.
  64358. if (task.successCallback) {
  64359. task.successCallback();
  64360. }
  64361. _this.executeNext();
  64362. });
  64363. }
  64364. };
  64365. SimplificationQueue.prototype.getSimplifier = function (task) {
  64366. switch (task.simplificationType) {
  64367. case SimplificationType.QUADRATIC:
  64368. default:
  64369. return new QuadraticErrorSimplification(task.mesh);
  64370. }
  64371. };
  64372. return SimplificationQueue;
  64373. }());
  64374. BABYLON.SimplificationQueue = SimplificationQueue;
  64375. /**
  64376. * The implemented types of simplification.
  64377. * At the moment only Quadratic Error Decimation is implemented.
  64378. */
  64379. var SimplificationType;
  64380. (function (SimplificationType) {
  64381. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  64382. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  64383. var DecimationTriangle = (function () {
  64384. function DecimationTriangle(vertices) {
  64385. this.vertices = vertices;
  64386. this.error = new Array(4);
  64387. this.deleted = false;
  64388. this.isDirty = false;
  64389. this.deletePending = false;
  64390. this.borderFactor = 0;
  64391. }
  64392. return DecimationTriangle;
  64393. }());
  64394. BABYLON.DecimationTriangle = DecimationTriangle;
  64395. var DecimationVertex = (function () {
  64396. function DecimationVertex(position, id) {
  64397. this.position = position;
  64398. this.id = id;
  64399. this.isBorder = true;
  64400. this.q = new QuadraticMatrix();
  64401. this.triangleCount = 0;
  64402. this.triangleStart = 0;
  64403. this.originalOffsets = [];
  64404. }
  64405. DecimationVertex.prototype.updatePosition = function (newPosition) {
  64406. this.position.copyFrom(newPosition);
  64407. };
  64408. return DecimationVertex;
  64409. }());
  64410. BABYLON.DecimationVertex = DecimationVertex;
  64411. var QuadraticMatrix = (function () {
  64412. function QuadraticMatrix(data) {
  64413. this.data = new Array(10);
  64414. for (var i = 0; i < 10; ++i) {
  64415. if (data && data[i]) {
  64416. this.data[i] = data[i];
  64417. }
  64418. else {
  64419. this.data[i] = 0;
  64420. }
  64421. }
  64422. }
  64423. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  64424. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  64425. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  64426. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  64427. return det;
  64428. };
  64429. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  64430. for (var i = 0; i < 10; ++i) {
  64431. this.data[i] += matrix.data[i];
  64432. }
  64433. };
  64434. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  64435. for (var i = 0; i < 10; ++i) {
  64436. this.data[i] += data[i];
  64437. }
  64438. };
  64439. QuadraticMatrix.prototype.add = function (matrix) {
  64440. var m = new QuadraticMatrix();
  64441. for (var i = 0; i < 10; ++i) {
  64442. m.data[i] = this.data[i] + matrix.data[i];
  64443. }
  64444. return m;
  64445. };
  64446. QuadraticMatrix.FromData = function (a, b, c, d) {
  64447. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  64448. };
  64449. //returning an array to avoid garbage collection
  64450. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  64451. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  64452. };
  64453. return QuadraticMatrix;
  64454. }());
  64455. BABYLON.QuadraticMatrix = QuadraticMatrix;
  64456. var Reference = (function () {
  64457. function Reference(vertexId, triangleId) {
  64458. this.vertexId = vertexId;
  64459. this.triangleId = triangleId;
  64460. }
  64461. return Reference;
  64462. }());
  64463. BABYLON.Reference = Reference;
  64464. /**
  64465. * An implementation of the Quadratic Error simplification algorithm.
  64466. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  64467. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  64468. * @author RaananW
  64469. */
  64470. var QuadraticErrorSimplification = (function () {
  64471. function QuadraticErrorSimplification(_mesh) {
  64472. this._mesh = _mesh;
  64473. this.initialized = false;
  64474. this.syncIterations = 5000;
  64475. this.aggressiveness = 7;
  64476. this.decimationIterations = 100;
  64477. this.boundingBoxEpsilon = BABYLON.Epsilon;
  64478. }
  64479. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  64480. var _this = this;
  64481. this.initDecimatedMesh();
  64482. //iterating through the submeshes array, one after the other.
  64483. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  64484. _this.initWithMesh(loop.index, function () {
  64485. _this.runDecimation(settings, loop.index, function () {
  64486. loop.executeNext();
  64487. });
  64488. }, settings.optimizeMesh);
  64489. }, function () {
  64490. setTimeout(function () {
  64491. successCallback(_this._reconstructedMesh);
  64492. }, 0);
  64493. });
  64494. };
  64495. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  64496. var _this = this;
  64497. var gCount = 0;
  64498. triangle.vertices.forEach(function (vertex) {
  64499. var count = 0;
  64500. var vPos = vertex.position;
  64501. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  64502. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  64503. ++count;
  64504. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  64505. ++count;
  64506. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  64507. ++count;
  64508. if (count > 1) {
  64509. ++gCount;
  64510. }
  64511. ;
  64512. });
  64513. if (gCount > 1) {
  64514. console.log(triangle, gCount);
  64515. }
  64516. return gCount > 1;
  64517. };
  64518. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  64519. var _this = this;
  64520. var targetCount = ~~(this.triangles.length * settings.quality);
  64521. var deletedTriangles = 0;
  64522. var triangleCount = this.triangles.length;
  64523. var iterationFunction = function (iteration, callback) {
  64524. setTimeout(function () {
  64525. if (iteration % 5 === 0) {
  64526. _this.updateMesh(iteration === 0);
  64527. }
  64528. for (var i = 0; i < _this.triangles.length; ++i) {
  64529. _this.triangles[i].isDirty = false;
  64530. }
  64531. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  64532. var trianglesIterator = function (i) {
  64533. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  64534. var t = _this.triangles[tIdx];
  64535. if (!t)
  64536. return;
  64537. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  64538. return;
  64539. }
  64540. for (var j = 0; j < 3; ++j) {
  64541. if (t.error[j] < threshold) {
  64542. var deleted0 = [];
  64543. var deleted1 = [];
  64544. var v0 = t.vertices[j];
  64545. var v1 = t.vertices[(j + 1) % 3];
  64546. if (v0.isBorder || v1.isBorder)
  64547. continue;
  64548. var p = BABYLON.Vector3.Zero();
  64549. var n = BABYLON.Vector3.Zero();
  64550. var uv = BABYLON.Vector2.Zero();
  64551. var color = new BABYLON.Color4(0, 0, 0, 1);
  64552. _this.calculateError(v0, v1, p, n, uv, color);
  64553. var delTr = [];
  64554. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  64555. continue;
  64556. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  64557. continue;
  64558. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  64559. continue;
  64560. var uniqueArray = [];
  64561. delTr.forEach(function (deletedT) {
  64562. if (uniqueArray.indexOf(deletedT) === -1) {
  64563. deletedT.deletePending = true;
  64564. uniqueArray.push(deletedT);
  64565. }
  64566. });
  64567. if (uniqueArray.length % 2 !== 0) {
  64568. continue;
  64569. }
  64570. v0.q = v1.q.add(v0.q);
  64571. v0.updatePosition(p);
  64572. var tStart = _this.references.length;
  64573. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  64574. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  64575. var tCount = _this.references.length - tStart;
  64576. if (tCount <= v0.triangleCount) {
  64577. if (tCount) {
  64578. for (var c = 0; c < tCount; c++) {
  64579. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  64580. }
  64581. }
  64582. }
  64583. else {
  64584. v0.triangleStart = tStart;
  64585. }
  64586. v0.triangleCount = tCount;
  64587. break;
  64588. }
  64589. }
  64590. };
  64591. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  64592. }, 0);
  64593. };
  64594. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  64595. if (triangleCount - deletedTriangles <= targetCount)
  64596. loop.breakLoop();
  64597. else {
  64598. iterationFunction(loop.index, function () {
  64599. loop.executeNext();
  64600. });
  64601. }
  64602. }, function () {
  64603. setTimeout(function () {
  64604. //reconstruct this part of the mesh
  64605. _this.reconstructMesh(submeshIndex);
  64606. successCallback();
  64607. }, 0);
  64608. });
  64609. };
  64610. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  64611. var _this = this;
  64612. this.vertices = [];
  64613. this.triangles = [];
  64614. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64615. var indices = this._mesh.getIndices();
  64616. var submesh = this._mesh.subMeshes[submeshIndex];
  64617. var findInVertices = function (positionToSearch) {
  64618. if (optimizeMesh) {
  64619. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  64620. if (_this.vertices[ii].position.equals(positionToSearch)) {
  64621. return _this.vertices[ii];
  64622. }
  64623. }
  64624. }
  64625. return null;
  64626. };
  64627. var vertexReferences = [];
  64628. var vertexInit = function (i) {
  64629. var offset = i + submesh.verticesStart;
  64630. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  64631. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  64632. vertex.originalOffsets.push(offset);
  64633. if (vertex.id === _this.vertices.length) {
  64634. _this.vertices.push(vertex);
  64635. }
  64636. vertexReferences.push(vertex.id);
  64637. };
  64638. //var totalVertices = mesh.getTotalVertices();
  64639. var totalVertices = submesh.verticesCount;
  64640. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  64641. var indicesInit = function (i) {
  64642. var offset = (submesh.indexStart / 3) + i;
  64643. var pos = (offset * 3);
  64644. var i0 = indices[pos + 0];
  64645. var i1 = indices[pos + 1];
  64646. var i2 = indices[pos + 2];
  64647. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  64648. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  64649. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  64650. var triangle = new DecimationTriangle([v0, v1, v2]);
  64651. triangle.originalOffset = pos;
  64652. _this.triangles.push(triangle);
  64653. };
  64654. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  64655. _this.init(callback);
  64656. });
  64657. });
  64658. };
  64659. QuadraticErrorSimplification.prototype.init = function (callback) {
  64660. var _this = this;
  64661. var triangleInit1 = function (i) {
  64662. var t = _this.triangles[i];
  64663. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  64664. for (var j = 0; j < 3; j++) {
  64665. 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))));
  64666. }
  64667. };
  64668. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  64669. var triangleInit2 = function (i) {
  64670. var t = _this.triangles[i];
  64671. for (var j = 0; j < 3; ++j) {
  64672. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  64673. }
  64674. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  64675. };
  64676. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  64677. _this.initialized = true;
  64678. callback();
  64679. });
  64680. });
  64681. };
  64682. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  64683. var newTriangles = [];
  64684. var i;
  64685. for (i = 0; i < this.vertices.length; ++i) {
  64686. this.vertices[i].triangleCount = 0;
  64687. }
  64688. var t;
  64689. var j;
  64690. for (i = 0; i < this.triangles.length; ++i) {
  64691. if (!this.triangles[i].deleted) {
  64692. t = this.triangles[i];
  64693. for (j = 0; j < 3; ++j) {
  64694. t.vertices[j].triangleCount = 1;
  64695. }
  64696. newTriangles.push(t);
  64697. }
  64698. }
  64699. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  64700. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  64701. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  64702. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  64703. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64704. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64705. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64706. var vertexCount = 0;
  64707. for (i = 0; i < this.vertices.length; ++i) {
  64708. var vertex = this.vertices[i];
  64709. vertex.id = vertexCount;
  64710. if (vertex.triangleCount) {
  64711. vertex.originalOffsets.forEach(function (originalOffset) {
  64712. newPositionData.push(vertex.position.x);
  64713. newPositionData.push(vertex.position.y);
  64714. newPositionData.push(vertex.position.z);
  64715. newNormalData.push(normalData[originalOffset * 3]);
  64716. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  64717. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  64718. if (uvs && uvs.length) {
  64719. newUVsData.push(uvs[(originalOffset * 2)]);
  64720. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  64721. }
  64722. else if (colorsData && colorsData.length) {
  64723. newColorsData.push(colorsData[(originalOffset * 4)]);
  64724. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  64725. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  64726. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  64727. }
  64728. ++vertexCount;
  64729. });
  64730. }
  64731. }
  64732. var startingIndex = this._reconstructedMesh.getTotalIndices();
  64733. var startingVertex = this._reconstructedMesh.getTotalVertices();
  64734. var submeshesArray = this._reconstructedMesh.subMeshes;
  64735. this._reconstructedMesh.subMeshes = [];
  64736. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  64737. var originalIndices = this._mesh.getIndices();
  64738. for (i = 0; i < newTriangles.length; ++i) {
  64739. t = newTriangles[i]; //now get the new referencing point for each vertex
  64740. [0, 1, 2].forEach(function (idx) {
  64741. var id = originalIndices[t.originalOffset + idx];
  64742. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  64743. if (offset < 0)
  64744. offset = 0;
  64745. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  64746. });
  64747. }
  64748. //overwriting the old vertex buffers and indices.
  64749. this._reconstructedMesh.setIndices(newIndicesArray);
  64750. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  64751. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  64752. if (newUVsData.length > 0)
  64753. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  64754. if (newColorsData.length > 0)
  64755. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  64756. //create submesh
  64757. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  64758. if (submeshIndex > 0) {
  64759. this._reconstructedMesh.subMeshes = [];
  64760. submeshesArray.forEach(function (submesh) {
  64761. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  64762. });
  64763. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  64764. }
  64765. };
  64766. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  64767. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  64768. this._reconstructedMesh.material = this._mesh.material;
  64769. this._reconstructedMesh.parent = this._mesh.parent;
  64770. this._reconstructedMesh.isVisible = false;
  64771. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  64772. };
  64773. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  64774. for (var i = 0; i < vertex1.triangleCount; ++i) {
  64775. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  64776. if (t.deleted)
  64777. continue;
  64778. var s = this.references[vertex1.triangleStart + i].vertexId;
  64779. var v1 = t.vertices[(s + 1) % 3];
  64780. var v2 = t.vertices[(s + 2) % 3];
  64781. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  64782. deletedArray[i] = true;
  64783. delTr.push(t);
  64784. continue;
  64785. }
  64786. var d1 = v1.position.subtract(point);
  64787. d1 = d1.normalize();
  64788. var d2 = v2.position.subtract(point);
  64789. d2 = d2.normalize();
  64790. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  64791. return true;
  64792. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  64793. deletedArray[i] = false;
  64794. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  64795. return true;
  64796. }
  64797. return false;
  64798. };
  64799. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  64800. var newDeleted = deletedTriangles;
  64801. for (var i = 0; i < vertex.triangleCount; ++i) {
  64802. var ref = this.references[vertex.triangleStart + i];
  64803. var t = this.triangles[ref.triangleId];
  64804. if (t.deleted)
  64805. continue;
  64806. if (deletedArray[i] && t.deletePending) {
  64807. t.deleted = true;
  64808. newDeleted++;
  64809. continue;
  64810. }
  64811. t.vertices[ref.vertexId] = origVertex;
  64812. t.isDirty = true;
  64813. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  64814. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  64815. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  64816. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  64817. this.references.push(ref);
  64818. }
  64819. return newDeleted;
  64820. };
  64821. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  64822. for (var i = 0; i < this.vertices.length; ++i) {
  64823. var vCount = [];
  64824. var vId = [];
  64825. var v = this.vertices[i];
  64826. var j;
  64827. for (j = 0; j < v.triangleCount; ++j) {
  64828. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  64829. for (var ii = 0; ii < 3; ii++) {
  64830. var ofs = 0;
  64831. var vv = triangle.vertices[ii];
  64832. while (ofs < vCount.length) {
  64833. if (vId[ofs] === vv.id)
  64834. break;
  64835. ++ofs;
  64836. }
  64837. if (ofs === vCount.length) {
  64838. vCount.push(1);
  64839. vId.push(vv.id);
  64840. }
  64841. else {
  64842. vCount[ofs]++;
  64843. }
  64844. }
  64845. }
  64846. for (j = 0; j < vCount.length; ++j) {
  64847. if (vCount[j] === 1) {
  64848. this.vertices[vId[j]].isBorder = true;
  64849. }
  64850. else {
  64851. this.vertices[vId[j]].isBorder = false;
  64852. }
  64853. }
  64854. }
  64855. };
  64856. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  64857. if (identifyBorders === void 0) { identifyBorders = false; }
  64858. var i;
  64859. if (!identifyBorders) {
  64860. var newTrianglesVector = [];
  64861. for (i = 0; i < this.triangles.length; ++i) {
  64862. if (!this.triangles[i].deleted) {
  64863. newTrianglesVector.push(this.triangles[i]);
  64864. }
  64865. }
  64866. this.triangles = newTrianglesVector;
  64867. }
  64868. for (i = 0; i < this.vertices.length; ++i) {
  64869. this.vertices[i].triangleCount = 0;
  64870. this.vertices[i].triangleStart = 0;
  64871. }
  64872. var t;
  64873. var j;
  64874. var v;
  64875. for (i = 0; i < this.triangles.length; ++i) {
  64876. t = this.triangles[i];
  64877. for (j = 0; j < 3; ++j) {
  64878. v = t.vertices[j];
  64879. v.triangleCount++;
  64880. }
  64881. }
  64882. var tStart = 0;
  64883. for (i = 0; i < this.vertices.length; ++i) {
  64884. this.vertices[i].triangleStart = tStart;
  64885. tStart += this.vertices[i].triangleCount;
  64886. this.vertices[i].triangleCount = 0;
  64887. }
  64888. var newReferences = new Array(this.triangles.length * 3);
  64889. for (i = 0; i < this.triangles.length; ++i) {
  64890. t = this.triangles[i];
  64891. for (j = 0; j < 3; ++j) {
  64892. v = t.vertices[j];
  64893. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  64894. v.triangleCount++;
  64895. }
  64896. }
  64897. this.references = newReferences;
  64898. if (identifyBorders) {
  64899. this.identifyBorder();
  64900. }
  64901. };
  64902. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  64903. var x = point.x;
  64904. var y = point.y;
  64905. var z = point.z;
  64906. 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
  64907. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  64908. };
  64909. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  64910. var q = vertex1.q.add(vertex2.q);
  64911. var border = vertex1.isBorder && vertex2.isBorder;
  64912. var error = 0;
  64913. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  64914. if (qDet !== 0 && !border) {
  64915. if (!pointResult) {
  64916. pointResult = BABYLON.Vector3.Zero();
  64917. }
  64918. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  64919. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  64920. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  64921. error = this.vertexError(q, pointResult);
  64922. }
  64923. else {
  64924. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  64925. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  64926. var error1 = this.vertexError(q, vertex1.position);
  64927. var error2 = this.vertexError(q, vertex2.position);
  64928. var error3 = this.vertexError(q, p3);
  64929. error = Math.min(error1, error2, error3);
  64930. if (error === error1) {
  64931. if (pointResult) {
  64932. pointResult.copyFrom(vertex1.position);
  64933. }
  64934. }
  64935. else if (error === error2) {
  64936. if (pointResult) {
  64937. pointResult.copyFrom(vertex2.position);
  64938. }
  64939. }
  64940. else {
  64941. if (pointResult) {
  64942. pointResult.copyFrom(p3);
  64943. }
  64944. }
  64945. }
  64946. return error;
  64947. };
  64948. return QuadraticErrorSimplification;
  64949. }());
  64950. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  64951. })(BABYLON || (BABYLON = {}));
  64952. //# sourceMappingURL=babylon.meshSimplification.js.map
  64953. var BABYLON;
  64954. (function (BABYLON) {
  64955. var Internals;
  64956. (function (Internals) {
  64957. var MeshLODLevel = (function () {
  64958. function MeshLODLevel(distance, mesh) {
  64959. this.distance = distance;
  64960. this.mesh = mesh;
  64961. }
  64962. return MeshLODLevel;
  64963. }());
  64964. Internals.MeshLODLevel = MeshLODLevel;
  64965. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64966. })(BABYLON || (BABYLON = {}));
  64967. //# sourceMappingURL=babylon.meshLODLevel.js.map
  64968. var BABYLON;
  64969. (function (BABYLON) {
  64970. // Standard optimizations
  64971. var SceneOptimization = (function () {
  64972. function SceneOptimization(priority) {
  64973. if (priority === void 0) { priority = 0; }
  64974. this.priority = priority;
  64975. this.apply = function (scene) {
  64976. return true; // Return true if everything that can be done was applied
  64977. };
  64978. }
  64979. return SceneOptimization;
  64980. }());
  64981. BABYLON.SceneOptimization = SceneOptimization;
  64982. var TextureOptimization = (function (_super) {
  64983. __extends(TextureOptimization, _super);
  64984. function TextureOptimization(priority, maximumSize) {
  64985. if (priority === void 0) { priority = 0; }
  64986. if (maximumSize === void 0) { maximumSize = 1024; }
  64987. var _this = _super.call(this, priority) || this;
  64988. _this.priority = priority;
  64989. _this.maximumSize = maximumSize;
  64990. _this.apply = function (scene) {
  64991. var allDone = true;
  64992. for (var index = 0; index < scene.textures.length; index++) {
  64993. var texture = scene.textures[index];
  64994. if (!texture.canRescale) {
  64995. continue;
  64996. }
  64997. var currentSize = texture.getSize();
  64998. var maxDimension = Math.max(currentSize.width, currentSize.height);
  64999. if (maxDimension > _this.maximumSize) {
  65000. texture.scale(0.5);
  65001. allDone = false;
  65002. }
  65003. }
  65004. return allDone;
  65005. };
  65006. return _this;
  65007. }
  65008. return TextureOptimization;
  65009. }(SceneOptimization));
  65010. BABYLON.TextureOptimization = TextureOptimization;
  65011. var HardwareScalingOptimization = (function (_super) {
  65012. __extends(HardwareScalingOptimization, _super);
  65013. function HardwareScalingOptimization(priority, maximumScale) {
  65014. if (priority === void 0) { priority = 0; }
  65015. if (maximumScale === void 0) { maximumScale = 2; }
  65016. var _this = _super.call(this, priority) || this;
  65017. _this.priority = priority;
  65018. _this.maximumScale = maximumScale;
  65019. _this._currentScale = 1;
  65020. _this.apply = function (scene) {
  65021. _this._currentScale++;
  65022. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  65023. return _this._currentScale >= _this.maximumScale;
  65024. };
  65025. return _this;
  65026. }
  65027. return HardwareScalingOptimization;
  65028. }(SceneOptimization));
  65029. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  65030. var ShadowsOptimization = (function (_super) {
  65031. __extends(ShadowsOptimization, _super);
  65032. function ShadowsOptimization() {
  65033. var _this = _super !== null && _super.apply(this, arguments) || this;
  65034. _this.apply = function (scene) {
  65035. scene.shadowsEnabled = false;
  65036. return true;
  65037. };
  65038. return _this;
  65039. }
  65040. return ShadowsOptimization;
  65041. }(SceneOptimization));
  65042. BABYLON.ShadowsOptimization = ShadowsOptimization;
  65043. var PostProcessesOptimization = (function (_super) {
  65044. __extends(PostProcessesOptimization, _super);
  65045. function PostProcessesOptimization() {
  65046. var _this = _super !== null && _super.apply(this, arguments) || this;
  65047. _this.apply = function (scene) {
  65048. scene.postProcessesEnabled = false;
  65049. return true;
  65050. };
  65051. return _this;
  65052. }
  65053. return PostProcessesOptimization;
  65054. }(SceneOptimization));
  65055. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  65056. var LensFlaresOptimization = (function (_super) {
  65057. __extends(LensFlaresOptimization, _super);
  65058. function LensFlaresOptimization() {
  65059. var _this = _super !== null && _super.apply(this, arguments) || this;
  65060. _this.apply = function (scene) {
  65061. scene.lensFlaresEnabled = false;
  65062. return true;
  65063. };
  65064. return _this;
  65065. }
  65066. return LensFlaresOptimization;
  65067. }(SceneOptimization));
  65068. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  65069. var ParticlesOptimization = (function (_super) {
  65070. __extends(ParticlesOptimization, _super);
  65071. function ParticlesOptimization() {
  65072. var _this = _super !== null && _super.apply(this, arguments) || this;
  65073. _this.apply = function (scene) {
  65074. scene.particlesEnabled = false;
  65075. return true;
  65076. };
  65077. return _this;
  65078. }
  65079. return ParticlesOptimization;
  65080. }(SceneOptimization));
  65081. BABYLON.ParticlesOptimization = ParticlesOptimization;
  65082. var RenderTargetsOptimization = (function (_super) {
  65083. __extends(RenderTargetsOptimization, _super);
  65084. function RenderTargetsOptimization() {
  65085. var _this = _super !== null && _super.apply(this, arguments) || this;
  65086. _this.apply = function (scene) {
  65087. scene.renderTargetsEnabled = false;
  65088. return true;
  65089. };
  65090. return _this;
  65091. }
  65092. return RenderTargetsOptimization;
  65093. }(SceneOptimization));
  65094. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  65095. var MergeMeshesOptimization = (function (_super) {
  65096. __extends(MergeMeshesOptimization, _super);
  65097. function MergeMeshesOptimization() {
  65098. var _this = _super !== null && _super.apply(this, arguments) || this;
  65099. _this._canBeMerged = function (abstractMesh) {
  65100. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  65101. return false;
  65102. }
  65103. var mesh = abstractMesh;
  65104. if (!mesh.isVisible || !mesh.isEnabled()) {
  65105. return false;
  65106. }
  65107. if (mesh.instances.length > 0) {
  65108. return false;
  65109. }
  65110. if (mesh.skeleton || mesh.hasLODLevels) {
  65111. return false;
  65112. }
  65113. if (mesh.parent) {
  65114. return false;
  65115. }
  65116. return true;
  65117. };
  65118. _this.apply = function (scene, updateSelectionTree) {
  65119. var globalPool = scene.meshes.slice(0);
  65120. var globalLength = globalPool.length;
  65121. for (var index = 0; index < globalLength; index++) {
  65122. var currentPool = new Array();
  65123. var current = globalPool[index];
  65124. // Checks
  65125. if (!_this._canBeMerged(current)) {
  65126. continue;
  65127. }
  65128. currentPool.push(current);
  65129. // Find compatible meshes
  65130. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  65131. var otherMesh = globalPool[subIndex];
  65132. if (!_this._canBeMerged(otherMesh)) {
  65133. continue;
  65134. }
  65135. if (otherMesh.material !== current.material) {
  65136. continue;
  65137. }
  65138. if (otherMesh.checkCollisions !== current.checkCollisions) {
  65139. continue;
  65140. }
  65141. currentPool.push(otherMesh);
  65142. globalLength--;
  65143. globalPool.splice(subIndex, 1);
  65144. subIndex--;
  65145. }
  65146. if (currentPool.length < 2) {
  65147. continue;
  65148. }
  65149. // Merge meshes
  65150. BABYLON.Mesh.MergeMeshes(currentPool);
  65151. }
  65152. if (updateSelectionTree != undefined) {
  65153. if (updateSelectionTree) {
  65154. scene.createOrUpdateSelectionOctree();
  65155. }
  65156. }
  65157. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  65158. scene.createOrUpdateSelectionOctree();
  65159. }
  65160. return true;
  65161. };
  65162. return _this;
  65163. }
  65164. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  65165. get: function () {
  65166. return MergeMeshesOptimization._UpdateSelectionTree;
  65167. },
  65168. set: function (value) {
  65169. MergeMeshesOptimization._UpdateSelectionTree = value;
  65170. },
  65171. enumerable: true,
  65172. configurable: true
  65173. });
  65174. return MergeMeshesOptimization;
  65175. }(SceneOptimization));
  65176. MergeMeshesOptimization._UpdateSelectionTree = false;
  65177. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  65178. // Options
  65179. var SceneOptimizerOptions = (function () {
  65180. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  65181. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  65182. if (trackerDuration === void 0) { trackerDuration = 2000; }
  65183. this.targetFrameRate = targetFrameRate;
  65184. this.trackerDuration = trackerDuration;
  65185. this.optimizations = new Array();
  65186. }
  65187. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  65188. var result = new SceneOptimizerOptions(targetFrameRate);
  65189. var priority = 0;
  65190. result.optimizations.push(new MergeMeshesOptimization(priority));
  65191. result.optimizations.push(new ShadowsOptimization(priority));
  65192. result.optimizations.push(new LensFlaresOptimization(priority));
  65193. // Next priority
  65194. priority++;
  65195. result.optimizations.push(new PostProcessesOptimization(priority));
  65196. result.optimizations.push(new ParticlesOptimization(priority));
  65197. // Next priority
  65198. priority++;
  65199. result.optimizations.push(new TextureOptimization(priority, 1024));
  65200. return result;
  65201. };
  65202. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  65203. var result = new SceneOptimizerOptions(targetFrameRate);
  65204. var priority = 0;
  65205. result.optimizations.push(new MergeMeshesOptimization(priority));
  65206. result.optimizations.push(new ShadowsOptimization(priority));
  65207. result.optimizations.push(new LensFlaresOptimization(priority));
  65208. // Next priority
  65209. priority++;
  65210. result.optimizations.push(new PostProcessesOptimization(priority));
  65211. result.optimizations.push(new ParticlesOptimization(priority));
  65212. // Next priority
  65213. priority++;
  65214. result.optimizations.push(new TextureOptimization(priority, 512));
  65215. // Next priority
  65216. priority++;
  65217. result.optimizations.push(new RenderTargetsOptimization(priority));
  65218. // Next priority
  65219. priority++;
  65220. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  65221. return result;
  65222. };
  65223. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  65224. var result = new SceneOptimizerOptions(targetFrameRate);
  65225. var priority = 0;
  65226. result.optimizations.push(new MergeMeshesOptimization(priority));
  65227. result.optimizations.push(new ShadowsOptimization(priority));
  65228. result.optimizations.push(new LensFlaresOptimization(priority));
  65229. // Next priority
  65230. priority++;
  65231. result.optimizations.push(new PostProcessesOptimization(priority));
  65232. result.optimizations.push(new ParticlesOptimization(priority));
  65233. // Next priority
  65234. priority++;
  65235. result.optimizations.push(new TextureOptimization(priority, 256));
  65236. // Next priority
  65237. priority++;
  65238. result.optimizations.push(new RenderTargetsOptimization(priority));
  65239. // Next priority
  65240. priority++;
  65241. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  65242. return result;
  65243. };
  65244. return SceneOptimizerOptions;
  65245. }());
  65246. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  65247. // Scene optimizer tool
  65248. var SceneOptimizer = (function () {
  65249. function SceneOptimizer() {
  65250. }
  65251. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  65252. // TODO: add an epsilon
  65253. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  65254. if (onSuccess) {
  65255. onSuccess();
  65256. }
  65257. return;
  65258. }
  65259. // Apply current level of optimizations
  65260. var allDone = true;
  65261. var noOptimizationApplied = true;
  65262. for (var index = 0; index < options.optimizations.length; index++) {
  65263. var optimization = options.optimizations[index];
  65264. if (optimization.priority === currentPriorityLevel) {
  65265. noOptimizationApplied = false;
  65266. allDone = allDone && optimization.apply(scene);
  65267. }
  65268. }
  65269. // If no optimization was applied, this is a failure :(
  65270. if (noOptimizationApplied) {
  65271. if (onFailure) {
  65272. onFailure();
  65273. }
  65274. return;
  65275. }
  65276. // If all optimizations were done, move to next level
  65277. if (allDone) {
  65278. currentPriorityLevel++;
  65279. }
  65280. // Let's the system running for a specific amount of time before checking FPS
  65281. scene.executeWhenReady(function () {
  65282. setTimeout(function () {
  65283. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  65284. }, options.trackerDuration);
  65285. });
  65286. };
  65287. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  65288. if (!options) {
  65289. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  65290. }
  65291. // Let's the system running for a specific amount of time before checking FPS
  65292. scene.executeWhenReady(function () {
  65293. setTimeout(function () {
  65294. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  65295. }, options.trackerDuration);
  65296. });
  65297. };
  65298. return SceneOptimizer;
  65299. }());
  65300. BABYLON.SceneOptimizer = SceneOptimizer;
  65301. })(BABYLON || (BABYLON = {}));
  65302. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  65303. var BABYLON;
  65304. (function (BABYLON) {
  65305. var OutlineRenderer = (function () {
  65306. function OutlineRenderer(scene) {
  65307. this.zOffset = 1;
  65308. this._scene = scene;
  65309. }
  65310. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  65311. var _this = this;
  65312. if (useOverlay === void 0) { useOverlay = false; }
  65313. var scene = this._scene;
  65314. var engine = this._scene.getEngine();
  65315. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65316. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  65317. return;
  65318. }
  65319. var mesh = subMesh.getRenderingMesh();
  65320. var material = subMesh.getMaterial();
  65321. engine.enableEffect(this._effect);
  65322. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  65323. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  65324. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65325. // Bones
  65326. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65327. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65328. }
  65329. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65330. // Alpha test
  65331. if (material && material.needAlphaTesting()) {
  65332. var alphaTexture = material.getAlphaTestTexture();
  65333. this._effect.setTexture("diffuseSampler", alphaTexture);
  65334. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65335. }
  65336. engine.setZOffset(-this.zOffset);
  65337. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  65338. engine.setZOffset(0);
  65339. };
  65340. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  65341. var defines = [];
  65342. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  65343. var mesh = subMesh.getMesh();
  65344. var material = subMesh.getMaterial();
  65345. // Alpha test
  65346. if (material && material.needAlphaTesting()) {
  65347. defines.push("#define ALPHATEST");
  65348. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65349. attribs.push(BABYLON.VertexBuffer.UVKind);
  65350. defines.push("#define UV1");
  65351. }
  65352. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65353. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65354. defines.push("#define UV2");
  65355. }
  65356. }
  65357. // Bones
  65358. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65359. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65360. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65361. if (mesh.numBoneInfluencers > 4) {
  65362. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65363. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65364. }
  65365. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65366. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65367. }
  65368. else {
  65369. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65370. }
  65371. // Instances
  65372. if (useInstances) {
  65373. defines.push("#define INSTANCES");
  65374. attribs.push("world0");
  65375. attribs.push("world1");
  65376. attribs.push("world2");
  65377. attribs.push("world3");
  65378. }
  65379. // Get correct effect
  65380. var join = defines.join("\n");
  65381. if (this._cachedDefines !== join) {
  65382. this._cachedDefines = join;
  65383. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  65384. }
  65385. return this._effect.isReady();
  65386. };
  65387. return OutlineRenderer;
  65388. }());
  65389. BABYLON.OutlineRenderer = OutlineRenderer;
  65390. })(BABYLON || (BABYLON = {}));
  65391. //# sourceMappingURL=babylon.outlineRenderer.js.map
  65392. var BABYLON;
  65393. (function (BABYLON) {
  65394. var FaceAdjacencies = (function () {
  65395. function FaceAdjacencies() {
  65396. this.edges = new Array();
  65397. this.edgesConnectedCount = 0;
  65398. }
  65399. return FaceAdjacencies;
  65400. }());
  65401. var EdgesRenderer = (function () {
  65402. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  65403. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  65404. if (epsilon === void 0) { epsilon = 0.95; }
  65405. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  65406. this.edgesWidthScalerForOrthographic = 1000.0;
  65407. this.edgesWidthScalerForPerspective = 50.0;
  65408. this._linesPositions = new Array();
  65409. this._linesNormals = new Array();
  65410. this._linesIndices = new Array();
  65411. this._buffers = {};
  65412. this._checkVerticesInsteadOfIndices = false;
  65413. this._source = source;
  65414. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  65415. this._epsilon = epsilon;
  65416. this._prepareRessources();
  65417. this._generateEdgesLines();
  65418. }
  65419. EdgesRenderer.prototype._prepareRessources = function () {
  65420. if (this._lineShader) {
  65421. return;
  65422. }
  65423. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  65424. attributes: ["position", "normal"],
  65425. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  65426. });
  65427. this._lineShader.disableDepthWrite = true;
  65428. this._lineShader.backFaceCulling = false;
  65429. };
  65430. EdgesRenderer.prototype.dispose = function () {
  65431. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  65432. if (buffer) {
  65433. buffer.dispose();
  65434. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  65435. }
  65436. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  65437. if (buffer) {
  65438. buffer.dispose();
  65439. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  65440. }
  65441. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  65442. this._lineShader.dispose();
  65443. };
  65444. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  65445. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  65446. return 0;
  65447. }
  65448. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  65449. return 1;
  65450. }
  65451. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  65452. return 2;
  65453. }
  65454. return -1;
  65455. };
  65456. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  65457. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  65458. return 0;
  65459. }
  65460. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  65461. return 1;
  65462. }
  65463. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  65464. return 2;
  65465. }
  65466. return -1;
  65467. };
  65468. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  65469. var needToCreateLine;
  65470. if (edge === undefined) {
  65471. needToCreateLine = true;
  65472. }
  65473. else {
  65474. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  65475. needToCreateLine = dotProduct < this._epsilon;
  65476. }
  65477. if (needToCreateLine) {
  65478. var offset = this._linesPositions.length / 3;
  65479. var normal = p0.subtract(p1);
  65480. normal.normalize();
  65481. // Positions
  65482. this._linesPositions.push(p0.x);
  65483. this._linesPositions.push(p0.y);
  65484. this._linesPositions.push(p0.z);
  65485. this._linesPositions.push(p0.x);
  65486. this._linesPositions.push(p0.y);
  65487. this._linesPositions.push(p0.z);
  65488. this._linesPositions.push(p1.x);
  65489. this._linesPositions.push(p1.y);
  65490. this._linesPositions.push(p1.z);
  65491. this._linesPositions.push(p1.x);
  65492. this._linesPositions.push(p1.y);
  65493. this._linesPositions.push(p1.z);
  65494. // Normals
  65495. this._linesNormals.push(p1.x);
  65496. this._linesNormals.push(p1.y);
  65497. this._linesNormals.push(p1.z);
  65498. this._linesNormals.push(-1);
  65499. this._linesNormals.push(p1.x);
  65500. this._linesNormals.push(p1.y);
  65501. this._linesNormals.push(p1.z);
  65502. this._linesNormals.push(1);
  65503. this._linesNormals.push(p0.x);
  65504. this._linesNormals.push(p0.y);
  65505. this._linesNormals.push(p0.z);
  65506. this._linesNormals.push(-1);
  65507. this._linesNormals.push(p0.x);
  65508. this._linesNormals.push(p0.y);
  65509. this._linesNormals.push(p0.z);
  65510. this._linesNormals.push(1);
  65511. // Indices
  65512. this._linesIndices.push(offset);
  65513. this._linesIndices.push(offset + 1);
  65514. this._linesIndices.push(offset + 2);
  65515. this._linesIndices.push(offset);
  65516. this._linesIndices.push(offset + 2);
  65517. this._linesIndices.push(offset + 3);
  65518. }
  65519. };
  65520. EdgesRenderer.prototype._generateEdgesLines = function () {
  65521. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65522. var indices = this._source.getIndices();
  65523. // First let's find adjacencies
  65524. var adjacencies = new Array();
  65525. var faceNormals = new Array();
  65526. var index;
  65527. var faceAdjacencies;
  65528. // Prepare faces
  65529. for (index = 0; index < indices.length; index += 3) {
  65530. faceAdjacencies = new FaceAdjacencies();
  65531. var p0Index = indices[index];
  65532. var p1Index = indices[index + 1];
  65533. var p2Index = indices[index + 2];
  65534. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  65535. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  65536. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  65537. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  65538. faceNormal.normalize();
  65539. faceNormals.push(faceNormal);
  65540. adjacencies.push(faceAdjacencies);
  65541. }
  65542. // Scan
  65543. for (index = 0; index < adjacencies.length; index++) {
  65544. faceAdjacencies = adjacencies[index];
  65545. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  65546. var otherFaceAdjacencies = adjacencies[otherIndex];
  65547. if (faceAdjacencies.edgesConnectedCount === 3) {
  65548. break;
  65549. }
  65550. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  65551. continue;
  65552. }
  65553. var otherP0 = indices[otherIndex * 3];
  65554. var otherP1 = indices[otherIndex * 3 + 1];
  65555. var otherP2 = indices[otherIndex * 3 + 2];
  65556. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  65557. var otherEdgeIndex;
  65558. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  65559. continue;
  65560. }
  65561. switch (edgeIndex) {
  65562. case 0:
  65563. if (this._checkVerticesInsteadOfIndices) {
  65564. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65565. }
  65566. else {
  65567. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  65568. }
  65569. break;
  65570. case 1:
  65571. if (this._checkVerticesInsteadOfIndices) {
  65572. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65573. }
  65574. else {
  65575. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  65576. }
  65577. break;
  65578. case 2:
  65579. if (this._checkVerticesInsteadOfIndices) {
  65580. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65581. }
  65582. else {
  65583. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  65584. }
  65585. break;
  65586. }
  65587. if (otherEdgeIndex === -1) {
  65588. continue;
  65589. }
  65590. faceAdjacencies.edges[edgeIndex] = otherIndex;
  65591. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  65592. faceAdjacencies.edgesConnectedCount++;
  65593. otherFaceAdjacencies.edgesConnectedCount++;
  65594. if (faceAdjacencies.edgesConnectedCount === 3) {
  65595. break;
  65596. }
  65597. }
  65598. }
  65599. }
  65600. // Create lines
  65601. for (index = 0; index < adjacencies.length; index++) {
  65602. // 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
  65603. var current = adjacencies[index];
  65604. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  65605. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  65606. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  65607. }
  65608. // Merge into a single mesh
  65609. var engine = this._source.getScene().getEngine();
  65610. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  65611. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  65612. this._ib = engine.createIndexBuffer(this._linesIndices);
  65613. this._indicesCount = this._linesIndices.length;
  65614. };
  65615. EdgesRenderer.prototype.render = function () {
  65616. if (!this._lineShader.isReady()) {
  65617. return;
  65618. }
  65619. var scene = this._source.getScene();
  65620. var engine = scene.getEngine();
  65621. this._lineShader._preBind();
  65622. // VBOs
  65623. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  65624. scene.resetCachedMaterial();
  65625. this._lineShader.setColor4("color", this._source.edgesColor);
  65626. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  65627. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  65628. }
  65629. else {
  65630. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  65631. }
  65632. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  65633. this._lineShader.bind(this._source.getWorldMatrix());
  65634. // Draw order
  65635. engine.draw(true, 0, this._indicesCount);
  65636. this._lineShader.unbind();
  65637. engine.setDepthWrite(true);
  65638. };
  65639. return EdgesRenderer;
  65640. }());
  65641. BABYLON.EdgesRenderer = EdgesRenderer;
  65642. })(BABYLON || (BABYLON = {}));
  65643. //# sourceMappingURL=babylon.edgesRenderer.js.map
  65644. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  65645. /// <reference path="..\Math\babylon.math.ts" />
  65646. var BABYLON;
  65647. (function (BABYLON) {
  65648. /**
  65649. * Special Glow Blur post process only blurring the alpha channel
  65650. * It enforces keeping the most luminous color in the color channel.
  65651. */
  65652. var GlowBlurPostProcess = (function (_super) {
  65653. __extends(GlowBlurPostProcess, _super);
  65654. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  65655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65656. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  65657. _this.direction = direction;
  65658. _this.kernel = kernel;
  65659. _this.onApplyObservable.add(function (effect) {
  65660. effect.setFloat2("screenSize", _this.width, _this.height);
  65661. effect.setVector2("direction", _this.direction);
  65662. effect.setFloat("blurWidth", _this.kernel);
  65663. });
  65664. return _this;
  65665. }
  65666. return GlowBlurPostProcess;
  65667. }(BABYLON.PostProcess));
  65668. /**
  65669. * The highlight layer Helps adding a glow effect around a mesh.
  65670. *
  65671. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  65672. * glowy meshes to your scene.
  65673. *
  65674. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  65675. */
  65676. var HighlightLayer = (function () {
  65677. /**
  65678. * Instantiates a new highlight Layer and references it to the scene..
  65679. * @param name The name of the layer
  65680. * @param scene The scene to use the layer in
  65681. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  65682. */
  65683. function HighlightLayer(name, scene, options) {
  65684. this.name = name;
  65685. this._vertexBuffers = {};
  65686. this._mainTextureDesiredSize = { width: 0, height: 0 };
  65687. this._meshes = {};
  65688. this._maxSize = 0;
  65689. this._shouldRender = false;
  65690. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  65691. this._excludedMeshes = {};
  65692. /**
  65693. * Specifies whether or not the inner glow is ACTIVE in the layer.
  65694. */
  65695. this.innerGlow = true;
  65696. /**
  65697. * Specifies whether or not the outer glow is ACTIVE in the layer.
  65698. */
  65699. this.outerGlow = true;
  65700. /**
  65701. * Specifies wether the highlight layer is enabled or not.
  65702. */
  65703. this.isEnabled = true;
  65704. /**
  65705. * An event triggered when the highlight layer has been disposed.
  65706. * @type {BABYLON.Observable}
  65707. */
  65708. this.onDisposeObservable = new BABYLON.Observable();
  65709. /**
  65710. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  65711. * @type {BABYLON.Observable}
  65712. */
  65713. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  65714. /**
  65715. * An event triggered when the highlight layer is being blurred.
  65716. * @type {BABYLON.Observable}
  65717. */
  65718. this.onBeforeBlurObservable = new BABYLON.Observable();
  65719. /**
  65720. * An event triggered when the highlight layer has been blurred.
  65721. * @type {BABYLON.Observable}
  65722. */
  65723. this.onAfterBlurObservable = new BABYLON.Observable();
  65724. /**
  65725. * An event triggered when the glowing blurred texture is being merged in the scene.
  65726. * @type {BABYLON.Observable}
  65727. */
  65728. this.onBeforeComposeObservable = new BABYLON.Observable();
  65729. /**
  65730. * An event triggered when the glowing blurred texture has been merged in the scene.
  65731. * @type {BABYLON.Observable}
  65732. */
  65733. this.onAfterComposeObservable = new BABYLON.Observable();
  65734. /**
  65735. * An event triggered when the highlight layer changes its size.
  65736. * @type {BABYLON.Observable}
  65737. */
  65738. this.onSizeChangedObservable = new BABYLON.Observable();
  65739. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65740. var engine = scene.getEngine();
  65741. this._engine = engine;
  65742. this._maxSize = this._engine.getCaps().maxTextureSize;
  65743. this._scene.highlightLayers.push(this);
  65744. // Warn on stencil.
  65745. if (!this._engine.isStencilEnable) {
  65746. 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 }");
  65747. }
  65748. // Adapt options
  65749. this._options = options || {
  65750. mainTextureRatio: 0.25,
  65751. blurTextureSizeRatio: 0.5,
  65752. blurHorizontalSize: 1,
  65753. blurVerticalSize: 1,
  65754. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  65755. };
  65756. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  65757. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  65758. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  65759. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  65760. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  65761. // VBO
  65762. var vertices = [];
  65763. vertices.push(1, 1);
  65764. vertices.push(-1, 1);
  65765. vertices.push(-1, -1);
  65766. vertices.push(1, -1);
  65767. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65768. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  65769. // Indices
  65770. var indices = [];
  65771. indices.push(0);
  65772. indices.push(1);
  65773. indices.push(2);
  65774. indices.push(0);
  65775. indices.push(2);
  65776. indices.push(3);
  65777. this._indexBuffer = engine.createIndexBuffer(indices);
  65778. // Effect
  65779. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  65780. // Render target
  65781. this.setMainTextureSize();
  65782. // Create Textures and post processes
  65783. this.createTextureAndPostProcesses();
  65784. }
  65785. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  65786. /**
  65787. * Gets the horizontal size of the blur.
  65788. */
  65789. get: function () {
  65790. return this._horizontalBlurPostprocess.kernel;
  65791. },
  65792. /**
  65793. * Specifies the horizontal size of the blur.
  65794. */
  65795. set: function (value) {
  65796. this._horizontalBlurPostprocess.kernel = value;
  65797. },
  65798. enumerable: true,
  65799. configurable: true
  65800. });
  65801. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  65802. /**
  65803. * Gets the vertical size of the blur.
  65804. */
  65805. get: function () {
  65806. return this._verticalBlurPostprocess.kernel;
  65807. },
  65808. /**
  65809. * Specifies the vertical size of the blur.
  65810. */
  65811. set: function (value) {
  65812. this._verticalBlurPostprocess.kernel = value;
  65813. },
  65814. enumerable: true,
  65815. configurable: true
  65816. });
  65817. Object.defineProperty(HighlightLayer.prototype, "camera", {
  65818. /**
  65819. * Gets the camera attached to the layer.
  65820. */
  65821. get: function () {
  65822. return this._options.camera;
  65823. },
  65824. enumerable: true,
  65825. configurable: true
  65826. });
  65827. /**
  65828. * Creates the render target textures and post processes used in the highlight layer.
  65829. */
  65830. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  65831. var _this = this;
  65832. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  65833. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  65834. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  65835. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  65836. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  65837. width: this._mainTextureDesiredSize.width,
  65838. height: this._mainTextureDesiredSize.height
  65839. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65840. this._mainTexture.activeCamera = this._options.camera;
  65841. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65842. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65843. this._mainTexture.anisotropicFilteringLevel = 1;
  65844. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65845. this._mainTexture.renderParticles = false;
  65846. this._mainTexture.renderList = null;
  65847. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  65848. width: blurTextureWidth,
  65849. height: blurTextureHeight
  65850. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65851. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65852. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65853. this._blurTexture.anisotropicFilteringLevel = 16;
  65854. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65855. this._blurTexture.renderParticles = false;
  65856. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65857. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  65858. effect.setTexture("textureSampler", _this._mainTexture);
  65859. });
  65860. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  65861. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65862. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  65863. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65864. });
  65865. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65866. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  65867. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65868. });
  65869. }
  65870. else {
  65871. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65872. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  65873. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65874. });
  65875. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65876. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  65877. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65878. });
  65879. }
  65880. this._mainTexture.onAfterUnbindObservable.add(function () {
  65881. _this.onBeforeBlurObservable.notifyObservers(_this);
  65882. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  65883. _this.onAfterBlurObservable.notifyObservers(_this);
  65884. });
  65885. // Custom render function
  65886. var renderSubMesh = function (subMesh) {
  65887. var mesh = subMesh.getRenderingMesh();
  65888. var scene = _this._scene;
  65889. var engine = scene.getEngine();
  65890. // Culling
  65891. engine.setState(subMesh.getMaterial().backFaceCulling);
  65892. // Managing instances
  65893. var batch = mesh._getInstancesRenderList(subMesh._id);
  65894. if (batch.mustReturn) {
  65895. return;
  65896. }
  65897. // Excluded Mesh
  65898. if (_this._excludedMeshes[mesh.uniqueId]) {
  65899. return;
  65900. }
  65901. ;
  65902. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65903. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  65904. var material = subMesh.getMaterial();
  65905. var emissiveTexture = null;
  65906. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  65907. emissiveTexture = material.emissiveTexture;
  65908. }
  65909. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  65910. engine.enableEffect(_this._glowMapGenerationEffect);
  65911. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  65912. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  65913. if (highlightLayerMesh) {
  65914. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  65915. }
  65916. else {
  65917. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  65918. }
  65919. // Alpha test
  65920. if (material && material.needAlphaTesting()) {
  65921. var alphaTexture = material.getAlphaTestTexture();
  65922. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  65923. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65924. }
  65925. // Glow emissive only
  65926. if (emissiveTexture) {
  65927. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  65928. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  65929. }
  65930. // Bones
  65931. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65932. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65933. }
  65934. // Draw
  65935. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  65936. }
  65937. else {
  65938. // Need to reset refresh rate of the shadowMap
  65939. _this._mainTexture.resetRefreshCounter();
  65940. }
  65941. };
  65942. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  65943. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  65944. var index;
  65945. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65946. renderSubMesh(opaqueSubMeshes.data[index]);
  65947. }
  65948. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65949. renderSubMesh(alphaTestSubMeshes.data[index]);
  65950. }
  65951. for (index = 0; index < transparentSubMeshes.length; index++) {
  65952. renderSubMesh(transparentSubMeshes.data[index]);
  65953. }
  65954. };
  65955. this._mainTexture.onClearObservable.add(function (engine) {
  65956. engine.clear(HighlightLayer.neutralColor, true, true, true);
  65957. });
  65958. };
  65959. /**
  65960. * Checks for the readiness of the element composing the layer.
  65961. * @param subMesh the mesh to check for
  65962. * @param useInstances specify wether or not to use instances to render the mesh
  65963. * @param emissiveTexture the associated emissive texture used to generate the glow
  65964. * @return true if ready otherwise, false
  65965. */
  65966. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  65967. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  65968. return false;
  65969. }
  65970. var defines = [];
  65971. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65972. var mesh = subMesh.getMesh();
  65973. var material = subMesh.getMaterial();
  65974. var uv1 = false;
  65975. var uv2 = false;
  65976. // Alpha test
  65977. if (material && material.needAlphaTesting()) {
  65978. var alphaTexture = material.getAlphaTestTexture();
  65979. if (alphaTexture) {
  65980. defines.push("#define ALPHATEST");
  65981. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  65982. alphaTexture.coordinatesIndex === 1) {
  65983. defines.push("#define DIFFUSEUV2");
  65984. uv2 = true;
  65985. }
  65986. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65987. defines.push("#define DIFFUSEUV1");
  65988. uv1 = true;
  65989. }
  65990. }
  65991. }
  65992. // Emissive
  65993. if (emissiveTexture) {
  65994. defines.push("#define EMISSIVE");
  65995. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  65996. emissiveTexture.coordinatesIndex === 1) {
  65997. defines.push("#define EMISSIVEUV2");
  65998. uv2 = true;
  65999. }
  66000. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66001. defines.push("#define EMISSIVEUV1");
  66002. uv1 = true;
  66003. }
  66004. }
  66005. if (uv1) {
  66006. attribs.push(BABYLON.VertexBuffer.UVKind);
  66007. defines.push("#define UV1");
  66008. }
  66009. if (uv2) {
  66010. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66011. defines.push("#define UV2");
  66012. }
  66013. // Bones
  66014. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66015. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66016. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66017. if (mesh.numBoneInfluencers > 4) {
  66018. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66019. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66020. }
  66021. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66022. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66023. }
  66024. else {
  66025. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66026. }
  66027. // Instances
  66028. if (useInstances) {
  66029. defines.push("#define INSTANCES");
  66030. attribs.push("world0");
  66031. attribs.push("world1");
  66032. attribs.push("world2");
  66033. attribs.push("world3");
  66034. }
  66035. // Get correct effect
  66036. var join = defines.join("\n");
  66037. if (this._cachedDefines !== join) {
  66038. this._cachedDefines = join;
  66039. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  66040. }
  66041. return this._glowMapGenerationEffect.isReady();
  66042. };
  66043. /**
  66044. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  66045. */
  66046. HighlightLayer.prototype.render = function () {
  66047. var currentEffect = this._glowMapMergeEffect;
  66048. // Check
  66049. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  66050. return;
  66051. var engine = this._scene.getEngine();
  66052. this.onBeforeComposeObservable.notifyObservers(this);
  66053. // Render
  66054. engine.enableEffect(currentEffect);
  66055. engine.setState(false);
  66056. // Cache
  66057. var previousStencilBuffer = engine.getStencilBuffer();
  66058. var previousStencilFunction = engine.getStencilFunction();
  66059. var previousStencilMask = engine.getStencilMask();
  66060. var previousStencilOperationPass = engine.getStencilOperationPass();
  66061. var previousStencilOperationFail = engine.getStencilOperationFail();
  66062. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  66063. var previousAlphaMode = engine.getAlphaMode();
  66064. // Texture
  66065. currentEffect.setTexture("textureSampler", this._blurTexture);
  66066. // VBOs
  66067. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  66068. // Stencil operations
  66069. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  66070. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  66071. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  66072. // Draw order
  66073. engine.setAlphaMode(this._options.alphaBlendingMode);
  66074. engine.setStencilMask(0x00);
  66075. engine.setStencilBuffer(true);
  66076. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  66077. if (this.outerGlow) {
  66078. currentEffect.setFloat("offset", 0);
  66079. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  66080. engine.draw(true, 0, 6);
  66081. }
  66082. if (this.innerGlow) {
  66083. currentEffect.setFloat("offset", 1);
  66084. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  66085. engine.draw(true, 0, 6);
  66086. }
  66087. // Restore Cache
  66088. engine.setStencilFunction(previousStencilFunction);
  66089. engine.setStencilMask(previousStencilMask);
  66090. engine.setAlphaMode(previousAlphaMode);
  66091. engine.setStencilBuffer(previousStencilBuffer);
  66092. engine.setStencilOperationPass(previousStencilOperationPass);
  66093. engine.setStencilOperationFail(previousStencilOperationFail);
  66094. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  66095. engine._stencilState.reset();
  66096. this.onAfterComposeObservable.notifyObservers(this);
  66097. // Handle size changes.
  66098. var size = this._mainTexture.getSize();
  66099. this.setMainTextureSize();
  66100. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  66101. // Recreate RTT and post processes on size change.
  66102. this.onSizeChangedObservable.notifyObservers(this);
  66103. this.disposeTextureAndPostProcesses();
  66104. this.createTextureAndPostProcesses();
  66105. }
  66106. };
  66107. /**
  66108. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  66109. * @param mesh The mesh to exclude from the highlight layer
  66110. */
  66111. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  66112. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  66113. if (!meshExcluded) {
  66114. this._excludedMeshes[mesh.uniqueId] = {
  66115. mesh: mesh,
  66116. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  66117. mesh.getEngine().setStencilBuffer(false);
  66118. }),
  66119. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  66120. mesh.getEngine().setStencilBuffer(true);
  66121. }),
  66122. };
  66123. }
  66124. };
  66125. /**
  66126. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  66127. * @param mesh The mesh to highlight
  66128. */
  66129. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  66130. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  66131. if (meshExcluded) {
  66132. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  66133. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  66134. }
  66135. this._excludedMeshes[mesh.uniqueId] = undefined;
  66136. };
  66137. /**
  66138. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  66139. * @param mesh The mesh to highlight
  66140. * @param color The color of the highlight
  66141. * @param glowEmissiveOnly Extract the glow from the emissive texture
  66142. */
  66143. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  66144. var _this = this;
  66145. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  66146. var meshHighlight = this._meshes[mesh.uniqueId];
  66147. if (meshHighlight) {
  66148. meshHighlight.color = color;
  66149. }
  66150. else {
  66151. this._meshes[mesh.uniqueId] = {
  66152. mesh: mesh,
  66153. color: color,
  66154. // Lambda required for capture due to Observable this context
  66155. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  66156. if (_this._excludedMeshes[mesh.uniqueId]) {
  66157. _this.defaultStencilReference(mesh);
  66158. }
  66159. else {
  66160. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  66161. }
  66162. }),
  66163. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  66164. glowEmissiveOnly: glowEmissiveOnly
  66165. };
  66166. }
  66167. this._shouldRender = true;
  66168. };
  66169. /**
  66170. * Remove a mesh from the highlight layer in order to make it stop glowing.
  66171. * @param mesh The mesh to highlight
  66172. */
  66173. HighlightLayer.prototype.removeMesh = function (mesh) {
  66174. var meshHighlight = this._meshes[mesh.uniqueId];
  66175. if (meshHighlight) {
  66176. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  66177. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  66178. }
  66179. this._meshes[mesh.uniqueId] = undefined;
  66180. this._shouldRender = false;
  66181. for (var meshHighlightToCheck in this._meshes) {
  66182. if (meshHighlightToCheck) {
  66183. this._shouldRender = true;
  66184. break;
  66185. }
  66186. }
  66187. };
  66188. /**
  66189. * Returns true if the layer contains information to display, otherwise false.
  66190. */
  66191. HighlightLayer.prototype.shouldRender = function () {
  66192. return this.isEnabled && this._shouldRender;
  66193. };
  66194. /**
  66195. * Sets the main texture desired size which is the closest power of two
  66196. * of the engine canvas size.
  66197. */
  66198. HighlightLayer.prototype.setMainTextureSize = function () {
  66199. if (this._options.mainTextureFixedSize) {
  66200. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  66201. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  66202. }
  66203. else {
  66204. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  66205. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  66206. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  66207. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  66208. }
  66209. };
  66210. /**
  66211. * Force the stencil to the normal expected value for none glowing parts
  66212. */
  66213. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  66214. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  66215. };
  66216. /**
  66217. * Dispose only the render target textures and post process.
  66218. */
  66219. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  66220. this._blurTexture.dispose();
  66221. this._mainTexture.dispose();
  66222. this._downSamplePostprocess.dispose();
  66223. this._horizontalBlurPostprocess.dispose();
  66224. this._verticalBlurPostprocess.dispose();
  66225. };
  66226. /**
  66227. * Dispose the highlight layer and free resources.
  66228. */
  66229. HighlightLayer.prototype.dispose = function () {
  66230. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66231. if (vertexBuffer) {
  66232. vertexBuffer.dispose();
  66233. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66234. }
  66235. if (this._indexBuffer) {
  66236. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66237. this._indexBuffer = null;
  66238. }
  66239. // Clean textures and post processes
  66240. this.disposeTextureAndPostProcesses();
  66241. // Clean mesh references
  66242. for (var id in this._meshes) {
  66243. var meshHighlight = this._meshes[id];
  66244. if (meshHighlight && meshHighlight.mesh) {
  66245. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  66246. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  66247. }
  66248. }
  66249. this._meshes = null;
  66250. for (var id in this._excludedMeshes) {
  66251. var meshHighlight = this._excludedMeshes[id];
  66252. if (meshHighlight) {
  66253. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  66254. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  66255. }
  66256. }
  66257. this._excludedMeshes = null;
  66258. // Remove from scene
  66259. var index = this._scene.highlightLayers.indexOf(this, 0);
  66260. if (index > -1) {
  66261. this._scene.highlightLayers.splice(index, 1);
  66262. }
  66263. // Callback
  66264. this.onDisposeObservable.notifyObservers(this);
  66265. this.onDisposeObservable.clear();
  66266. this.onBeforeRenderMainTextureObservable.clear();
  66267. this.onBeforeBlurObservable.clear();
  66268. this.onBeforeComposeObservable.clear();
  66269. this.onAfterComposeObservable.clear();
  66270. this.onSizeChangedObservable.clear();
  66271. };
  66272. return HighlightLayer;
  66273. }());
  66274. /**
  66275. * The neutral color used during the preparation of the glow effect.
  66276. * This is black by default as the blend operation is a blend operation.
  66277. */
  66278. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  66279. /**
  66280. * Stencil value used for glowing meshes.
  66281. */
  66282. HighlightLayer.glowingMeshStencilReference = 0x02;
  66283. /**
  66284. * Stencil value used for the other meshes in the scene.
  66285. */
  66286. HighlightLayer.normalMeshStencilReference = 0x01;
  66287. BABYLON.HighlightLayer = HighlightLayer;
  66288. })(BABYLON || (BABYLON = {}));
  66289. //# sourceMappingURL=babylon.highlightlayer.js.map
  66290. var BABYLON;
  66291. (function (BABYLON) {
  66292. var MeshAssetTask = (function () {
  66293. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  66294. this.name = name;
  66295. this.meshesNames = meshesNames;
  66296. this.rootUrl = rootUrl;
  66297. this.sceneFilename = sceneFilename;
  66298. this.isCompleted = false;
  66299. }
  66300. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66301. var _this = this;
  66302. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  66303. _this.loadedMeshes = meshes;
  66304. _this.loadedParticleSystems = particleSystems;
  66305. _this.loadedSkeletons = skeletons;
  66306. _this.isCompleted = true;
  66307. if (_this.onSuccess) {
  66308. _this.onSuccess(_this);
  66309. }
  66310. onSuccess();
  66311. }, null, function () {
  66312. if (_this.onError) {
  66313. _this.onError(_this);
  66314. }
  66315. onError();
  66316. });
  66317. };
  66318. return MeshAssetTask;
  66319. }());
  66320. BABYLON.MeshAssetTask = MeshAssetTask;
  66321. var TextFileAssetTask = (function () {
  66322. function TextFileAssetTask(name, url) {
  66323. this.name = name;
  66324. this.url = url;
  66325. this.isCompleted = false;
  66326. }
  66327. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66328. var _this = this;
  66329. BABYLON.Tools.LoadFile(this.url, function (data) {
  66330. _this.text = data;
  66331. _this.isCompleted = true;
  66332. if (_this.onSuccess) {
  66333. _this.onSuccess(_this);
  66334. }
  66335. onSuccess();
  66336. }, null, scene.database, false, function () {
  66337. if (_this.onError) {
  66338. _this.onError(_this);
  66339. }
  66340. onError();
  66341. });
  66342. };
  66343. return TextFileAssetTask;
  66344. }());
  66345. BABYLON.TextFileAssetTask = TextFileAssetTask;
  66346. var BinaryFileAssetTask = (function () {
  66347. function BinaryFileAssetTask(name, url) {
  66348. this.name = name;
  66349. this.url = url;
  66350. this.isCompleted = false;
  66351. }
  66352. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66353. var _this = this;
  66354. BABYLON.Tools.LoadFile(this.url, function (data) {
  66355. _this.data = data;
  66356. _this.isCompleted = true;
  66357. if (_this.onSuccess) {
  66358. _this.onSuccess(_this);
  66359. }
  66360. onSuccess();
  66361. }, null, scene.database, true, function () {
  66362. if (_this.onError) {
  66363. _this.onError(_this);
  66364. }
  66365. onError();
  66366. });
  66367. };
  66368. return BinaryFileAssetTask;
  66369. }());
  66370. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  66371. var ImageAssetTask = (function () {
  66372. function ImageAssetTask(name, url) {
  66373. this.name = name;
  66374. this.url = url;
  66375. this.isCompleted = false;
  66376. }
  66377. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66378. var _this = this;
  66379. var img = new Image();
  66380. BABYLON.Tools.SetCorsBehavior(this.url, img);
  66381. img.onload = function () {
  66382. _this.image = img;
  66383. _this.isCompleted = true;
  66384. if (_this.onSuccess) {
  66385. _this.onSuccess(_this);
  66386. }
  66387. onSuccess();
  66388. };
  66389. img.onerror = function () {
  66390. if (_this.onError) {
  66391. _this.onError(_this);
  66392. }
  66393. onError();
  66394. };
  66395. img.src = this.url;
  66396. };
  66397. return ImageAssetTask;
  66398. }());
  66399. BABYLON.ImageAssetTask = ImageAssetTask;
  66400. var TextureAssetTask = (function () {
  66401. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  66402. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66403. this.name = name;
  66404. this.url = url;
  66405. this.noMipmap = noMipmap;
  66406. this.invertY = invertY;
  66407. this.samplingMode = samplingMode;
  66408. this.isCompleted = false;
  66409. }
  66410. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66411. var _this = this;
  66412. var onload = function () {
  66413. _this.isCompleted = true;
  66414. if (_this.onSuccess) {
  66415. _this.onSuccess(_this);
  66416. }
  66417. onSuccess();
  66418. };
  66419. var onerror = function () {
  66420. if (_this.onError) {
  66421. _this.onError(_this);
  66422. }
  66423. onError();
  66424. };
  66425. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  66426. };
  66427. return TextureAssetTask;
  66428. }());
  66429. BABYLON.TextureAssetTask = TextureAssetTask;
  66430. var CubeTextureAssetTask = (function () {
  66431. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  66432. this.name = name;
  66433. this.url = url;
  66434. this.extensions = extensions;
  66435. this.noMipmap = noMipmap;
  66436. this.files = files;
  66437. this.isCompleted = false;
  66438. }
  66439. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66440. var _this = this;
  66441. var onload = function () {
  66442. _this.isCompleted = true;
  66443. if (_this.onSuccess) {
  66444. _this.onSuccess(_this);
  66445. }
  66446. onSuccess();
  66447. };
  66448. var onerror = function () {
  66449. if (_this.onError) {
  66450. _this.onError(_this);
  66451. }
  66452. onError();
  66453. };
  66454. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  66455. };
  66456. return CubeTextureAssetTask;
  66457. }());
  66458. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  66459. var HDRCubeTextureAssetTask = (function () {
  66460. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  66461. if (noMipmap === void 0) { noMipmap = false; }
  66462. if (generateHarmonics === void 0) { generateHarmonics = true; }
  66463. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  66464. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  66465. this.name = name;
  66466. this.url = url;
  66467. this.size = size;
  66468. this.noMipmap = noMipmap;
  66469. this.generateHarmonics = generateHarmonics;
  66470. this.useInGammaSpace = useInGammaSpace;
  66471. this.usePMREMGenerator = usePMREMGenerator;
  66472. this.isCompleted = false;
  66473. }
  66474. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66475. var _this = this;
  66476. var onload = function () {
  66477. _this.isCompleted = true;
  66478. if (_this.onSuccess) {
  66479. _this.onSuccess(_this);
  66480. }
  66481. onSuccess();
  66482. };
  66483. var onerror = function () {
  66484. if (_this.onError) {
  66485. _this.onError(_this);
  66486. }
  66487. onError();
  66488. };
  66489. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  66490. };
  66491. return HDRCubeTextureAssetTask;
  66492. }());
  66493. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  66494. var AssetsManager = (function () {
  66495. function AssetsManager(scene) {
  66496. this.tasks = new Array();
  66497. this.waitingTasksCount = 0;
  66498. this.useDefaultLoadingScreen = true;
  66499. this._scene = scene;
  66500. }
  66501. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  66502. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  66503. this.tasks.push(task);
  66504. return task;
  66505. };
  66506. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  66507. var task = new TextFileAssetTask(taskName, url);
  66508. this.tasks.push(task);
  66509. return task;
  66510. };
  66511. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  66512. var task = new BinaryFileAssetTask(taskName, url);
  66513. this.tasks.push(task);
  66514. return task;
  66515. };
  66516. AssetsManager.prototype.addImageTask = function (taskName, url) {
  66517. var task = new ImageAssetTask(taskName, url);
  66518. this.tasks.push(task);
  66519. return task;
  66520. };
  66521. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  66522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66523. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  66524. this.tasks.push(task);
  66525. return task;
  66526. };
  66527. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  66528. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  66529. this.tasks.push(task);
  66530. return task;
  66531. };
  66532. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  66533. if (noMipmap === void 0) { noMipmap = false; }
  66534. if (generateHarmonics === void 0) { generateHarmonics = true; }
  66535. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  66536. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  66537. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  66538. this.tasks.push(task);
  66539. return task;
  66540. };
  66541. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  66542. this.waitingTasksCount--;
  66543. if (this.waitingTasksCount === 0) {
  66544. if (this.onFinish) {
  66545. this.onFinish(this.tasks);
  66546. }
  66547. this._scene.getEngine().hideLoadingUI();
  66548. }
  66549. };
  66550. AssetsManager.prototype._runTask = function (task) {
  66551. var _this = this;
  66552. task.run(this._scene, function () {
  66553. if (_this.onTaskSuccess) {
  66554. _this.onTaskSuccess(task);
  66555. }
  66556. _this._decreaseWaitingTasksCount();
  66557. }, function () {
  66558. if (_this.onTaskError) {
  66559. _this.onTaskError(task);
  66560. }
  66561. _this._decreaseWaitingTasksCount();
  66562. });
  66563. };
  66564. AssetsManager.prototype.reset = function () {
  66565. this.tasks = new Array();
  66566. return this;
  66567. };
  66568. AssetsManager.prototype.load = function () {
  66569. this.waitingTasksCount = this.tasks.length;
  66570. if (this.waitingTasksCount === 0) {
  66571. if (this.onFinish) {
  66572. this.onFinish(this.tasks);
  66573. }
  66574. return this;
  66575. }
  66576. if (this.useDefaultLoadingScreen) {
  66577. this._scene.getEngine().displayLoadingUI();
  66578. }
  66579. for (var index = 0; index < this.tasks.length; index++) {
  66580. var task = this.tasks[index];
  66581. this._runTask(task);
  66582. }
  66583. return this;
  66584. };
  66585. return AssetsManager;
  66586. }());
  66587. BABYLON.AssetsManager = AssetsManager;
  66588. })(BABYLON || (BABYLON = {}));
  66589. //# sourceMappingURL=babylon.assetsManager.js.map
  66590. var BABYLON;
  66591. (function (BABYLON) {
  66592. var MapTexture = (function (_super) {
  66593. __extends(MapTexture, _super);
  66594. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  66595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66596. if (useMipMap === void 0) { useMipMap = false; }
  66597. if (margin === void 0) { margin = 0; }
  66598. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  66599. _this.name = name;
  66600. _this._size = size;
  66601. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66602. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66603. // Create the rectPackMap that will allocate portion of the texture
  66604. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  66605. // Create the texture that will store the content
  66606. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  66607. return _this;
  66608. }
  66609. /**
  66610. * Allocate a rectangle of a given size in the texture map
  66611. * @param size the size of the rectangle to allocation
  66612. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  66613. */
  66614. MapTexture.prototype.allocateRect = function (size) {
  66615. return this._rectPackingMap.addRect(size);
  66616. };
  66617. /**
  66618. * Free a given rectangle from the texture map
  66619. * @param rectInfo the instance corresponding to the rect to free.
  66620. */
  66621. MapTexture.prototype.freeRect = function (rectInfo) {
  66622. if (rectInfo) {
  66623. rectInfo.freeContent();
  66624. }
  66625. };
  66626. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  66627. /**
  66628. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  66629. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  66630. * @returns {}
  66631. */
  66632. get: function () {
  66633. return this._rectPackingMap.freeSpace;
  66634. },
  66635. enumerable: true,
  66636. configurable: true
  66637. });
  66638. /**
  66639. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  66640. * 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.
  66641. * Don't forget to call unbindTexture when you're done rendering
  66642. * @param rect the zone to render to
  66643. * @param clear true to clear the portion's color/depth data
  66644. */
  66645. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  66646. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  66647. };
  66648. /**
  66649. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  66650. * 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.
  66651. * Don't forget to call unbindTexture when you're done rendering
  66652. * @param pos the position into the texture
  66653. * @param size the portion to fit the clip space to
  66654. * @param clear true to clear the portion's color/depth data
  66655. */
  66656. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  66657. var engine = this.getScene().getEngine();
  66658. engine.bindFramebuffer(this._texture);
  66659. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  66660. if (clear) {
  66661. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  66662. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  66663. }
  66664. };
  66665. /**
  66666. * Unbind the texture map from the rendering engine.
  66667. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  66668. * @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.
  66669. */
  66670. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  66671. // Dump ?
  66672. if (dumpForDebug) {
  66673. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  66674. }
  66675. var engine = this.getScene().getEngine();
  66676. if (this._replacedViewport) {
  66677. engine.setViewport(this._replacedViewport);
  66678. this._replacedViewport = null;
  66679. }
  66680. engine.unBindFramebuffer(this._texture);
  66681. };
  66682. Object.defineProperty(MapTexture.prototype, "canRescale", {
  66683. get: function () {
  66684. return false;
  66685. },
  66686. enumerable: true,
  66687. configurable: true
  66688. });
  66689. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  66690. // Anyway, there's not much point to use this method for this kind of texture I guess
  66691. MapTexture.prototype.clone = function () {
  66692. return null;
  66693. };
  66694. return MapTexture;
  66695. }(BABYLON.Texture));
  66696. BABYLON.MapTexture = MapTexture;
  66697. })(BABYLON || (BABYLON = {}));
  66698. //# sourceMappingURL=babylon.mapTexture.js.map
  66699. var BABYLON;
  66700. (function (BABYLON) {
  66701. /**
  66702. * This class describe a rectangle that were added to the map.
  66703. * You have access to its coordinates either in pixel or normalized (UV)
  66704. */
  66705. var PackedRect = (function () {
  66706. function PackedRect(root, parent, pos, size) {
  66707. this._pos = pos;
  66708. this._size = size;
  66709. this._root = root;
  66710. this._parent = parent;
  66711. this._contentSize = null;
  66712. this._bottomNode = null;
  66713. this._leftNode = null;
  66714. this._initialSize = null;
  66715. this._rightNode = null;
  66716. }
  66717. Object.defineProperty(PackedRect.prototype, "pos", {
  66718. /**
  66719. * @returns the position of this node into the map
  66720. */
  66721. get: function () {
  66722. return this._pos;
  66723. },
  66724. enumerable: true,
  66725. configurable: true
  66726. });
  66727. Object.defineProperty(PackedRect.prototype, "contentSize", {
  66728. /**
  66729. * @returns the size of the rectangle this node handles
  66730. */
  66731. get: function () {
  66732. return this._contentSize;
  66733. },
  66734. enumerable: true,
  66735. configurable: true
  66736. });
  66737. /**
  66738. * Retrieve the inner position (considering the margin) and stores it into the res object
  66739. * @param res must be a valid Vector2 that will contain the inner position after this call
  66740. */
  66741. PackedRect.prototype.getInnerPosToRef = function (res) {
  66742. var m = this._root._margin;
  66743. res.x = this._pos.x + m;
  66744. res.y = this._pos.y + m;
  66745. };
  66746. /**
  66747. * Retrieve the inner size (considering the margin) and stores it into the res object
  66748. * @param res must be a valid Size that will contain the inner size after this call
  66749. */
  66750. PackedRect.prototype.getInnerSizeToRef = function (res) {
  66751. var m = this._root._margin;
  66752. res.width = this._contentSize.width - (m * 2);
  66753. res.height = this._contentSize.height - (m * 2);
  66754. };
  66755. Object.defineProperty(PackedRect.prototype, "UVs", {
  66756. /**
  66757. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  66758. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  66759. */
  66760. get: function () {
  66761. if (!this._contentSize) {
  66762. throw new Error("Can't compute UVs for this object because it's nor allocated");
  66763. }
  66764. return this.getUVsForCustomSize(this._contentSize);
  66765. },
  66766. enumerable: true,
  66767. configurable: true
  66768. });
  66769. /**
  66770. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  66771. * and then using only a part of the PackRect.
  66772. * This method will return the UVs for this part by given the custom size of what you really use
  66773. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  66774. */
  66775. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  66776. var mainWidth = this._root._size.width;
  66777. var mainHeight = this._root._size.height;
  66778. var margin = this._root._margin;
  66779. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  66780. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  66781. var uvs = new Array();
  66782. uvs.push(topLeft);
  66783. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  66784. uvs.push(rightBottom);
  66785. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  66786. return uvs;
  66787. };
  66788. /**
  66789. * Free this rectangle from the map.
  66790. * Call this method when you no longer need the rectangle to be in the map.
  66791. */
  66792. PackedRect.prototype.freeContent = function () {
  66793. if (!this.contentSize) {
  66794. return;
  66795. }
  66796. this._contentSize = null;
  66797. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  66798. this.attemptDefrag();
  66799. };
  66800. Object.defineProperty(PackedRect.prototype, "isUsed", {
  66801. get: function () {
  66802. return this._contentSize != null || this._leftNode != null;
  66803. },
  66804. enumerable: true,
  66805. configurable: true
  66806. });
  66807. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  66808. var node = this.findNode(contentSize);
  66809. // Not enough space...
  66810. if (!node) {
  66811. return null;
  66812. }
  66813. node.splitNode(contentSize);
  66814. return node;
  66815. };
  66816. PackedRect.prototype.findNode = function (size) {
  66817. var resNode = null;
  66818. var margin = this._root._margin * 2;
  66819. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  66820. if (this.isUsed) {
  66821. if (this._leftNode) {
  66822. resNode = this._leftNode.findNode(size);
  66823. }
  66824. if (!resNode && this._rightNode) {
  66825. resNode = this._rightNode.findNode(size);
  66826. }
  66827. if (!resNode && this._bottomNode) {
  66828. resNode = this._bottomNode.findNode(size);
  66829. }
  66830. }
  66831. else if (this._initialSize) {
  66832. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  66833. resNode = this;
  66834. }
  66835. else {
  66836. return null;
  66837. }
  66838. }
  66839. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  66840. resNode = this;
  66841. }
  66842. return resNode;
  66843. };
  66844. PackedRect.prototype.splitNode = function (contentSize) {
  66845. var cs = PackedRect.TpsSize;
  66846. var margin = this._root._margin * 2;
  66847. cs.copyFrom(contentSize);
  66848. cs.width += margin;
  66849. cs.height += margin;
  66850. // 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)
  66851. if (!this._contentSize && this._initialSize) {
  66852. this._contentSize = cs.clone();
  66853. 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));
  66854. return this._leftNode.splitNode(contentSize);
  66855. }
  66856. else {
  66857. this._contentSize = cs.clone();
  66858. this._initialSize = cs.clone();
  66859. if (cs.width !== this._size.width) {
  66860. 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));
  66861. }
  66862. if (cs.height !== this._size.height) {
  66863. 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));
  66864. }
  66865. return this;
  66866. }
  66867. };
  66868. PackedRect.prototype.attemptDefrag = function () {
  66869. if (!this.isUsed && this.isRecursiveFree) {
  66870. this.clearNode();
  66871. if (this._parent) {
  66872. this._parent.attemptDefrag();
  66873. }
  66874. }
  66875. };
  66876. PackedRect.prototype.clearNode = function () {
  66877. this._initialSize = null;
  66878. this._rightNode = null;
  66879. this._bottomNode = null;
  66880. };
  66881. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  66882. get: function () {
  66883. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  66884. },
  66885. enumerable: true,
  66886. configurable: true
  66887. });
  66888. PackedRect.prototype.evalFreeSize = function (size) {
  66889. var levelSize = 0;
  66890. if (!this.isUsed) {
  66891. var margin = this._root._margin;
  66892. var is = this._initialSize;
  66893. if (is) {
  66894. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  66895. }
  66896. else {
  66897. var size_1 = this._size;
  66898. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  66899. }
  66900. }
  66901. if (this._rightNode) {
  66902. levelSize += this._rightNode.evalFreeSize(0);
  66903. }
  66904. if (this._bottomNode) {
  66905. levelSize += this._bottomNode.evalFreeSize(0);
  66906. }
  66907. return levelSize + size;
  66908. };
  66909. return PackedRect;
  66910. }());
  66911. PackedRect.TpsSize = BABYLON.Size.Zero();
  66912. BABYLON.PackedRect = PackedRect;
  66913. /**
  66914. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  66915. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  66916. * 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.
  66917. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  66918. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  66919. */
  66920. var RectPackingMap = (function (_super) {
  66921. __extends(RectPackingMap, _super);
  66922. /**
  66923. * Create an instance of the object with a dimension using the given size
  66924. * @param size The dimension of the rectangle that will contain all the sub ones.
  66925. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  66926. */
  66927. function RectPackingMap(size, margin) {
  66928. if (margin === void 0) { margin = 0; }
  66929. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  66930. _this._margin = margin;
  66931. _this._root = _this;
  66932. return _this;
  66933. }
  66934. /**
  66935. * Add a rectangle, finding the best location to store it into the map
  66936. * @param size the dimension of the rectangle to store
  66937. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  66938. */
  66939. RectPackingMap.prototype.addRect = function (size) {
  66940. var node = this.findAndSplitNode(size);
  66941. return node;
  66942. };
  66943. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  66944. /**
  66945. * Return the current space free normalized between [0;1]
  66946. * @returns {}
  66947. */
  66948. get: function () {
  66949. var freeSize = 0;
  66950. freeSize = this.evalFreeSize(freeSize);
  66951. return freeSize / (this._size.width * this._size.height);
  66952. },
  66953. enumerable: true,
  66954. configurable: true
  66955. });
  66956. return RectPackingMap;
  66957. }(PackedRect));
  66958. BABYLON.RectPackingMap = RectPackingMap;
  66959. })(BABYLON || (BABYLON = {}));
  66960. //# sourceMappingURL=babylon.rectPackingMap.js.map
  66961. var BABYLON;
  66962. (function (BABYLON) {
  66963. /**
  66964. * This groups together the common properties used for image processing either in direct forward pass
  66965. * or through post processing effect depending on the use of the image processing pipeline in your scene
  66966. * or not.
  66967. */
  66968. var ImageProcessingConfiguration = (function () {
  66969. function ImageProcessingConfiguration() {
  66970. /**
  66971. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  66972. */
  66973. this.colorCurves = new BABYLON.ColorCurves();
  66974. this._colorCurvesEnabled = false;
  66975. this._colorGradingEnabled = false;
  66976. this._colorGradingWithGreenDepth = false;
  66977. this._colorGradingBGR = false;
  66978. this._exposure = 1.0;
  66979. this._toneMappingEnabled = false;
  66980. this._contrast = 1.0;
  66981. /**
  66982. * Vignette stretch size.
  66983. */
  66984. this.vignetteStretch = 0;
  66985. /**
  66986. * Vignette centre X Offset.
  66987. */
  66988. this.vignetteCentreX = 0;
  66989. /**
  66990. * Vignette centre Y Offset.
  66991. */
  66992. this.vignetteCentreY = 0;
  66993. /**
  66994. * Vignette weight or intensity of the vignette effect.
  66995. */
  66996. this.vignetteWeight = 1.5;
  66997. /**
  66998. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  66999. * if vignetteEnabled is set to true.
  67000. */
  67001. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  67002. /**
  67003. * Camera field of view used by the Vignette effect.
  67004. */
  67005. this.vignetteCameraFov = 0.5;
  67006. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  67007. this._vignetteEnabled = false;
  67008. this._applyByPostProcess = false;
  67009. /**
  67010. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  67011. * @type {BABYLON.Observable}
  67012. */
  67013. this.onUpdateParameters = new BABYLON.Observable();
  67014. }
  67015. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  67016. /**
  67017. * Gets wether the color curves effect is enabled.
  67018. */
  67019. get: function () {
  67020. return this._colorCurvesEnabled;
  67021. },
  67022. /**
  67023. * Sets wether the color curves effect is enabled.
  67024. */
  67025. set: function (value) {
  67026. if (this._colorCurvesEnabled === value) {
  67027. return;
  67028. }
  67029. this._colorCurvesEnabled = value;
  67030. this._updateParameters();
  67031. },
  67032. enumerable: true,
  67033. configurable: true
  67034. });
  67035. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  67036. /**
  67037. * Gets wether the color grading effect is enabled.
  67038. */
  67039. get: function () {
  67040. return this._colorGradingEnabled;
  67041. },
  67042. /**
  67043. * Sets wether the color grading effect is enabled.
  67044. */
  67045. set: function (value) {
  67046. if (this._colorGradingEnabled === value) {
  67047. return;
  67048. }
  67049. this._colorGradingEnabled = value;
  67050. this._updateParameters();
  67051. },
  67052. enumerable: true,
  67053. configurable: true
  67054. });
  67055. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  67056. /**
  67057. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  67058. */
  67059. get: function () {
  67060. return this._colorGradingWithGreenDepth;
  67061. },
  67062. /**
  67063. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  67064. */
  67065. set: function (value) {
  67066. if (this._colorGradingWithGreenDepth === value) {
  67067. return;
  67068. }
  67069. this._colorGradingWithGreenDepth = value;
  67070. this._updateParameters();
  67071. },
  67072. enumerable: true,
  67073. configurable: true
  67074. });
  67075. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  67076. /**
  67077. * Gets wether the color grading texture contains BGR values.
  67078. */
  67079. get: function () {
  67080. return this._colorGradingBGR;
  67081. },
  67082. /**
  67083. * Sets wether the color grading texture contains BGR values.
  67084. */
  67085. set: function (value) {
  67086. if (this._colorGradingBGR === value) {
  67087. return;
  67088. }
  67089. this._colorGradingBGR = value;
  67090. this._updateParameters();
  67091. },
  67092. enumerable: true,
  67093. configurable: true
  67094. });
  67095. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  67096. /**
  67097. * Gets the Exposure used in the effect.
  67098. */
  67099. get: function () {
  67100. return this._exposure;
  67101. },
  67102. /**
  67103. * Sets the Exposure used in the effect.
  67104. */
  67105. set: function (value) {
  67106. if (this._exposure === value) {
  67107. return;
  67108. }
  67109. this._exposure = value;
  67110. this._updateParameters();
  67111. },
  67112. enumerable: true,
  67113. configurable: true
  67114. });
  67115. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  67116. /**
  67117. * Gets wether the tone mapping effect is enabled.
  67118. */
  67119. get: function () {
  67120. return this._toneMappingEnabled;
  67121. },
  67122. /**
  67123. * Sets wether the tone mapping effect is enabled.
  67124. */
  67125. set: function (value) {
  67126. if (this._toneMappingEnabled === value) {
  67127. return;
  67128. }
  67129. this._toneMappingEnabled = value;
  67130. this._updateParameters();
  67131. },
  67132. enumerable: true,
  67133. configurable: true
  67134. });
  67135. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  67136. /**
  67137. * Gets the contrast used in the effect.
  67138. */
  67139. get: function () {
  67140. return this._contrast;
  67141. },
  67142. /**
  67143. * Sets the contrast used in the effect.
  67144. */
  67145. set: function (value) {
  67146. if (this._contrast === value) {
  67147. return;
  67148. }
  67149. this._contrast = value;
  67150. this._updateParameters();
  67151. },
  67152. enumerable: true,
  67153. configurable: true
  67154. });
  67155. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  67156. /**
  67157. * Gets the vignette blend mode allowing different kind of effect.
  67158. */
  67159. get: function () {
  67160. return this._vignetteBlendMode;
  67161. },
  67162. /**
  67163. * Sets the vignette blend mode allowing different kind of effect.
  67164. */
  67165. set: function (value) {
  67166. if (this._vignetteBlendMode === value) {
  67167. return;
  67168. }
  67169. this._vignetteBlendMode = value;
  67170. this._updateParameters();
  67171. },
  67172. enumerable: true,
  67173. configurable: true
  67174. });
  67175. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  67176. /**
  67177. * Gets wether the vignette effect is enabled.
  67178. */
  67179. get: function () {
  67180. return this._vignetteEnabled;
  67181. },
  67182. /**
  67183. * Sets wether the vignette effect is enabled.
  67184. */
  67185. set: function (value) {
  67186. if (this._vignetteEnabled === value) {
  67187. return;
  67188. }
  67189. this._vignetteEnabled = value;
  67190. this._updateParameters();
  67191. },
  67192. enumerable: true,
  67193. configurable: true
  67194. });
  67195. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  67196. /**
  67197. * Gets wether the image processing is applied through a post process or not.
  67198. */
  67199. get: function () {
  67200. return this._applyByPostProcess;
  67201. },
  67202. /**
  67203. * Sets wether the image processing is applied through a post process or not.
  67204. */
  67205. set: function (value) {
  67206. if (this._applyByPostProcess === value) {
  67207. return;
  67208. }
  67209. this._applyByPostProcess = value;
  67210. this._updateParameters();
  67211. },
  67212. enumerable: true,
  67213. configurable: true
  67214. });
  67215. /**
  67216. * Method called each time the image processing information changes requires to recompile the effect.
  67217. */
  67218. ImageProcessingConfiguration.prototype._updateParameters = function () {
  67219. this.onUpdateParameters.notifyObservers(this);
  67220. };
  67221. /**
  67222. * Prepare the list of uniforms associated with the Image Processing effects.
  67223. * @param uniformsList The list of uniforms used in the effect
  67224. * @param defines the list of defines currently in use
  67225. */
  67226. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  67227. if (defines.EXPOSURE) {
  67228. uniforms.push("exposureLinear");
  67229. }
  67230. if (defines.CONTRAST) {
  67231. uniforms.push("contrast");
  67232. }
  67233. if (defines.COLORGRADING) {
  67234. uniforms.push("colorTransformSettings");
  67235. }
  67236. if (defines.VIGNETTE) {
  67237. uniforms.push("vInverseScreenSize");
  67238. uniforms.push("vignetteSettings1");
  67239. uniforms.push("vignetteSettings2");
  67240. }
  67241. if (defines.COLORCURVES) {
  67242. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  67243. }
  67244. };
  67245. /**
  67246. * Prepare the list of samplers associated with the Image Processing effects.
  67247. * @param uniformsList The list of uniforms used in the effect
  67248. * @param defines the list of defines currently in use
  67249. */
  67250. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  67251. if (defines.COLORGRADING) {
  67252. samplersList.push("txColorTransform");
  67253. }
  67254. };
  67255. /**
  67256. * Prepare the list of defines associated to the shader.
  67257. * @param defines the list of defines to complete
  67258. */
  67259. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  67260. defines.VIGNETTE = this.vignetteEnabled;
  67261. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  67262. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  67263. defines.TONEMAPPING = this.toneMappingEnabled;
  67264. defines.CONTRAST = (this.contrast !== 1.0);
  67265. defines.EXPOSURE = (this.exposure !== 1.0);
  67266. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  67267. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  67268. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  67269. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  67270. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  67271. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  67272. };
  67273. /**
  67274. * Returns true if all the image processing information are ready.
  67275. */
  67276. ImageProcessingConfiguration.prototype.isReady = function () {
  67277. // Color Grading texure can not be none blocking.
  67278. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  67279. };
  67280. /**
  67281. * Binds the image processing to the shader.
  67282. * @param effect The effect to bind to
  67283. */
  67284. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  67285. if (aspectRatio === void 0) { aspectRatio = 1; }
  67286. // Color Curves
  67287. if (this._colorCurvesEnabled) {
  67288. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  67289. }
  67290. // Vignette
  67291. if (this._vignetteEnabled) {
  67292. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  67293. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  67294. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  67295. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  67296. var vignetteScaleX = vignetteScaleY * aspectRatio;
  67297. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  67298. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  67299. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  67300. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  67301. var vignettePower = -2.0 * this.vignetteWeight;
  67302. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  67303. }
  67304. // Exposure
  67305. effect.setFloat("exposureLinear", this.exposure);
  67306. // Contrast
  67307. effect.setFloat("contrast", this.contrast);
  67308. // Color transform settings
  67309. if (this.colorGradingTexture) {
  67310. effect.setTexture("txColorTransform", this.colorGradingTexture);
  67311. var textureSize = this.colorGradingTexture.getSize().height;
  67312. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  67313. 0.5 / textureSize, // textureOffset
  67314. textureSize, // textureSize
  67315. this.colorGradingTexture.level // weight
  67316. );
  67317. }
  67318. };
  67319. /**
  67320. * Clones the current image processing instance.
  67321. * @return The cloned image processing
  67322. */
  67323. ImageProcessingConfiguration.prototype.clone = function () {
  67324. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  67325. };
  67326. /**
  67327. * Serializes the current image processing instance to a json representation.
  67328. * @return a JSON representation
  67329. */
  67330. ImageProcessingConfiguration.prototype.serialize = function () {
  67331. return BABYLON.SerializationHelper.Serialize(this);
  67332. };
  67333. /**
  67334. * Parses the image processing from a json representation.
  67335. * @param source the JSON source to parse
  67336. * @return The parsed image processing
  67337. */
  67338. ImageProcessingConfiguration.Parse = function (source) {
  67339. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  67340. };
  67341. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  67342. /**
  67343. * Used to apply the vignette as a mix with the pixel color.
  67344. */
  67345. get: function () {
  67346. return this._VIGNETTEMODE_MULTIPLY;
  67347. },
  67348. enumerable: true,
  67349. configurable: true
  67350. });
  67351. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  67352. /**
  67353. * Used to apply the vignette as a replacement of the pixel color.
  67354. */
  67355. get: function () {
  67356. return this._VIGNETTEMODE_OPAQUE;
  67357. },
  67358. enumerable: true,
  67359. configurable: true
  67360. });
  67361. return ImageProcessingConfiguration;
  67362. }());
  67363. // Static constants associated to the image processing.
  67364. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  67365. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  67366. __decorate([
  67367. BABYLON.serializeAsColorCurves()
  67368. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  67369. __decorate([
  67370. BABYLON.serialize()
  67371. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  67372. __decorate([
  67373. BABYLON.serializeAsTexture()
  67374. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  67375. __decorate([
  67376. BABYLON.serialize()
  67377. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  67378. __decorate([
  67379. BABYLON.serialize()
  67380. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  67381. __decorate([
  67382. BABYLON.serialize()
  67383. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  67384. __decorate([
  67385. BABYLON.serialize()
  67386. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  67387. __decorate([
  67388. BABYLON.serialize()
  67389. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  67390. __decorate([
  67391. BABYLON.serialize()
  67392. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  67393. __decorate([
  67394. BABYLON.serialize()
  67395. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  67396. __decorate([
  67397. BABYLON.serialize()
  67398. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  67399. __decorate([
  67400. BABYLON.serialize()
  67401. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  67402. __decorate([
  67403. BABYLON.serialize()
  67404. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  67405. __decorate([
  67406. BABYLON.serializeAsColor4()
  67407. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  67408. __decorate([
  67409. BABYLON.serialize()
  67410. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  67411. __decorate([
  67412. BABYLON.serialize()
  67413. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  67414. __decorate([
  67415. BABYLON.serialize()
  67416. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  67417. __decorate([
  67418. BABYLON.serialize()
  67419. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  67420. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  67421. })(BABYLON || (BABYLON = {}));
  67422. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  67423. var BABYLON;
  67424. (function (BABYLON) {
  67425. var serializedGeometries = [];
  67426. var serializeGeometry = function (geometry, serializationGeometries) {
  67427. if (serializedGeometries[geometry.id]) {
  67428. return;
  67429. }
  67430. if (geometry.doNotSerialize) {
  67431. return;
  67432. }
  67433. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  67434. serializationGeometries.boxes.push(geometry.serialize());
  67435. }
  67436. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  67437. serializationGeometries.spheres.push(geometry.serialize());
  67438. }
  67439. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  67440. serializationGeometries.cylinders.push(geometry.serialize());
  67441. }
  67442. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  67443. serializationGeometries.toruses.push(geometry.serialize());
  67444. }
  67445. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  67446. serializationGeometries.grounds.push(geometry.serialize());
  67447. }
  67448. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  67449. serializationGeometries.planes.push(geometry.serialize());
  67450. }
  67451. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  67452. serializationGeometries.torusKnots.push(geometry.serialize());
  67453. }
  67454. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  67455. throw new Error("Unknown primitive type");
  67456. }
  67457. else {
  67458. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  67459. }
  67460. serializedGeometries[geometry.id] = true;
  67461. };
  67462. var serializeMesh = function (mesh, serializationScene) {
  67463. var serializationObject = {};
  67464. // Geometry
  67465. var geometry = mesh._geometry;
  67466. if (geometry) {
  67467. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  67468. // 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
  67469. serializeGeometry(geometry, serializationScene.geometries);
  67470. }
  67471. }
  67472. // Custom
  67473. if (mesh.serialize) {
  67474. mesh.serialize(serializationObject);
  67475. }
  67476. return serializationObject;
  67477. };
  67478. var finalizeSingleMesh = function (mesh, serializationObject) {
  67479. //only works if the mesh is already loaded
  67480. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  67481. //serialize material
  67482. if (mesh.material) {
  67483. if (mesh.material instanceof BABYLON.StandardMaterial) {
  67484. serializationObject.materials = serializationObject.materials || [];
  67485. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  67486. serializationObject.materials.push(mesh.material.serialize());
  67487. }
  67488. }
  67489. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  67490. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  67491. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  67492. serializationObject.multiMaterials.push(mesh.material.serialize());
  67493. }
  67494. }
  67495. }
  67496. //serialize geometry
  67497. var geometry = mesh._geometry;
  67498. if (geometry) {
  67499. if (!serializationObject.geometries) {
  67500. serializationObject.geometries = {};
  67501. serializationObject.geometries.boxes = [];
  67502. serializationObject.geometries.spheres = [];
  67503. serializationObject.geometries.cylinders = [];
  67504. serializationObject.geometries.toruses = [];
  67505. serializationObject.geometries.grounds = [];
  67506. serializationObject.geometries.planes = [];
  67507. serializationObject.geometries.torusKnots = [];
  67508. serializationObject.geometries.vertexData = [];
  67509. }
  67510. serializeGeometry(geometry, serializationObject.geometries);
  67511. }
  67512. // Skeletons
  67513. if (mesh.skeleton) {
  67514. serializationObject.skeletons = serializationObject.skeletons || [];
  67515. serializationObject.skeletons.push(mesh.skeleton.serialize());
  67516. }
  67517. //serialize the actual mesh
  67518. serializationObject.meshes = serializationObject.meshes || [];
  67519. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  67520. }
  67521. };
  67522. var SceneSerializer = (function () {
  67523. function SceneSerializer() {
  67524. }
  67525. SceneSerializer.ClearCache = function () {
  67526. serializedGeometries = [];
  67527. };
  67528. SceneSerializer.Serialize = function (scene) {
  67529. var serializationObject = {};
  67530. SceneSerializer.ClearCache();
  67531. // Scene
  67532. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  67533. serializationObject.autoClear = scene.autoClear;
  67534. serializationObject.clearColor = scene.clearColor.asArray();
  67535. serializationObject.ambientColor = scene.ambientColor.asArray();
  67536. serializationObject.gravity = scene.gravity.asArray();
  67537. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  67538. serializationObject.workerCollisions = scene.workerCollisions;
  67539. // Fog
  67540. if (scene.fogMode && scene.fogMode !== 0) {
  67541. serializationObject.fogMode = scene.fogMode;
  67542. serializationObject.fogColor = scene.fogColor.asArray();
  67543. serializationObject.fogStart = scene.fogStart;
  67544. serializationObject.fogEnd = scene.fogEnd;
  67545. serializationObject.fogDensity = scene.fogDensity;
  67546. }
  67547. //Physics
  67548. if (scene.isPhysicsEnabled()) {
  67549. serializationObject.physicsEnabled = true;
  67550. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  67551. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  67552. }
  67553. // Metadata
  67554. if (scene.metadata) {
  67555. serializationObject.metadata = scene.metadata;
  67556. }
  67557. // Morph targets
  67558. serializationObject.morphTargetManagers = [];
  67559. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  67560. var abstractMesh = _a[_i];
  67561. var manager = abstractMesh.morphTargetManager;
  67562. if (manager) {
  67563. serializationObject.morphTargetManagers.push(manager.serialize());
  67564. }
  67565. }
  67566. // Lights
  67567. serializationObject.lights = [];
  67568. var index;
  67569. var light;
  67570. for (index = 0; index < scene.lights.length; index++) {
  67571. light = scene.lights[index];
  67572. if (!light.doNotSerialize) {
  67573. serializationObject.lights.push(light.serialize());
  67574. }
  67575. }
  67576. // Cameras
  67577. serializationObject.cameras = [];
  67578. for (index = 0; index < scene.cameras.length; index++) {
  67579. var camera = scene.cameras[index];
  67580. if (!camera.doNotSerialize) {
  67581. serializationObject.cameras.push(camera.serialize());
  67582. }
  67583. }
  67584. if (scene.activeCamera) {
  67585. serializationObject.activeCameraID = scene.activeCamera.id;
  67586. }
  67587. // Animations
  67588. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  67589. // Materials
  67590. serializationObject.materials = [];
  67591. serializationObject.multiMaterials = [];
  67592. var material;
  67593. for (index = 0; index < scene.materials.length; index++) {
  67594. material = scene.materials[index];
  67595. if (!material.doNotSerialize) {
  67596. serializationObject.materials.push(material.serialize());
  67597. }
  67598. }
  67599. // MultiMaterials
  67600. serializationObject.multiMaterials = [];
  67601. for (index = 0; index < scene.multiMaterials.length; index++) {
  67602. var multiMaterial = scene.multiMaterials[index];
  67603. serializationObject.multiMaterials.push(multiMaterial.serialize());
  67604. }
  67605. // Skeletons
  67606. serializationObject.skeletons = [];
  67607. for (index = 0; index < scene.skeletons.length; index++) {
  67608. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  67609. }
  67610. // Geometries
  67611. serializationObject.geometries = {};
  67612. serializationObject.geometries.boxes = [];
  67613. serializationObject.geometries.spheres = [];
  67614. serializationObject.geometries.cylinders = [];
  67615. serializationObject.geometries.toruses = [];
  67616. serializationObject.geometries.grounds = [];
  67617. serializationObject.geometries.planes = [];
  67618. serializationObject.geometries.torusKnots = [];
  67619. serializationObject.geometries.vertexData = [];
  67620. serializedGeometries = [];
  67621. var geometries = scene.getGeometries();
  67622. for (index = 0; index < geometries.length; index++) {
  67623. var geometry = geometries[index];
  67624. if (geometry.isReady()) {
  67625. serializeGeometry(geometry, serializationObject.geometries);
  67626. }
  67627. }
  67628. // Meshes
  67629. serializationObject.meshes = [];
  67630. for (index = 0; index < scene.meshes.length; index++) {
  67631. var abstractMesh = scene.meshes[index];
  67632. if (abstractMesh instanceof BABYLON.Mesh) {
  67633. var mesh = abstractMesh;
  67634. if (!mesh.doNotSerialize) {
  67635. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  67636. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  67637. }
  67638. }
  67639. }
  67640. }
  67641. // Particles Systems
  67642. serializationObject.particleSystems = [];
  67643. for (index = 0; index < scene.particleSystems.length; index++) {
  67644. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  67645. }
  67646. // Lens flares
  67647. serializationObject.lensFlareSystems = [];
  67648. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  67649. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  67650. }
  67651. // Shadows
  67652. serializationObject.shadowGenerators = [];
  67653. for (index = 0; index < scene.lights.length; index++) {
  67654. light = scene.lights[index];
  67655. var shadowGenerator = light.getShadowGenerator();
  67656. if (shadowGenerator) {
  67657. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  67658. }
  67659. }
  67660. // Action Manager
  67661. if (scene.actionManager) {
  67662. serializationObject.actions = scene.actionManager.serialize("scene");
  67663. }
  67664. // Audio
  67665. serializationObject.sounds = [];
  67666. for (index = 0; index < scene.soundTracks.length; index++) {
  67667. var soundtrack = scene.soundTracks[index];
  67668. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  67669. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  67670. }
  67671. }
  67672. return serializationObject;
  67673. };
  67674. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  67675. if (withParents === void 0) { withParents = false; }
  67676. if (withChildren === void 0) { withChildren = false; }
  67677. var serializationObject = {};
  67678. SceneSerializer.ClearCache();
  67679. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  67680. if (withParents || withChildren) {
  67681. //deliberate for loop! not for each, appended should be processed as well.
  67682. for (var i = 0; i < toSerialize.length; ++i) {
  67683. if (withChildren) {
  67684. toSerialize[i].getDescendants().forEach(function (node) {
  67685. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  67686. toSerialize.push(node);
  67687. }
  67688. });
  67689. }
  67690. //make sure the array doesn't contain the object already
  67691. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  67692. toSerialize.push(toSerialize[i].parent);
  67693. }
  67694. }
  67695. }
  67696. toSerialize.forEach(function (mesh) {
  67697. finalizeSingleMesh(mesh, serializationObject);
  67698. });
  67699. return serializationObject;
  67700. };
  67701. return SceneSerializer;
  67702. }());
  67703. BABYLON.SceneSerializer = SceneSerializer;
  67704. })(BABYLON || (BABYLON = {}));
  67705. //# sourceMappingURL=babylon.sceneSerializer.js.map
  67706. var BABYLON;
  67707. (function (BABYLON) {
  67708. var ReflectionProbe = (function () {
  67709. function ReflectionProbe(name, size, scene, generateMipMaps) {
  67710. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67711. var _this = this;
  67712. this.name = name;
  67713. this._viewMatrix = BABYLON.Matrix.Identity();
  67714. this._target = BABYLON.Vector3.Zero();
  67715. this._add = BABYLON.Vector3.Zero();
  67716. this.invertYAxis = false;
  67717. this.position = BABYLON.Vector3.Zero();
  67718. this._scene = scene;
  67719. this._scene.reflectionProbes.push(this);
  67720. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  67721. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  67722. switch (faceIndex) {
  67723. case 0:
  67724. _this._add.copyFromFloats(1, 0, 0);
  67725. break;
  67726. case 1:
  67727. _this._add.copyFromFloats(-1, 0, 0);
  67728. break;
  67729. case 2:
  67730. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  67731. break;
  67732. case 3:
  67733. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  67734. break;
  67735. case 4:
  67736. _this._add.copyFromFloats(0, 0, 1);
  67737. break;
  67738. case 5:
  67739. _this._add.copyFromFloats(0, 0, -1);
  67740. break;
  67741. }
  67742. if (_this._attachedMesh) {
  67743. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  67744. }
  67745. _this.position.addToRef(_this._add, _this._target);
  67746. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  67747. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  67748. });
  67749. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  67750. scene.updateTransformMatrix(true);
  67751. });
  67752. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  67753. }
  67754. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  67755. get: function () {
  67756. return this._renderTargetTexture.samples;
  67757. },
  67758. set: function (value) {
  67759. this._renderTargetTexture.samples = value;
  67760. },
  67761. enumerable: true,
  67762. configurable: true
  67763. });
  67764. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  67765. get: function () {
  67766. return this._renderTargetTexture.refreshRate;
  67767. },
  67768. set: function (value) {
  67769. this._renderTargetTexture.refreshRate = value;
  67770. },
  67771. enumerable: true,
  67772. configurable: true
  67773. });
  67774. ReflectionProbe.prototype.getScene = function () {
  67775. return this._scene;
  67776. };
  67777. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  67778. get: function () {
  67779. return this._renderTargetTexture;
  67780. },
  67781. enumerable: true,
  67782. configurable: true
  67783. });
  67784. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  67785. get: function () {
  67786. return this._renderTargetTexture.renderList;
  67787. },
  67788. enumerable: true,
  67789. configurable: true
  67790. });
  67791. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  67792. this._attachedMesh = mesh;
  67793. };
  67794. /**
  67795. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67796. *
  67797. * @param renderingGroupId The rendering group id corresponding to its index
  67798. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67799. */
  67800. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67801. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67802. };
  67803. ReflectionProbe.prototype.dispose = function () {
  67804. var index = this._scene.reflectionProbes.indexOf(this);
  67805. if (index !== -1) {
  67806. // Remove from the scene if found
  67807. this._scene.reflectionProbes.splice(index, 1);
  67808. }
  67809. if (this._renderTargetTexture) {
  67810. this._renderTargetTexture.dispose();
  67811. this._renderTargetTexture = null;
  67812. }
  67813. };
  67814. return ReflectionProbe;
  67815. }());
  67816. BABYLON.ReflectionProbe = ReflectionProbe;
  67817. })(BABYLON || (BABYLON = {}));
  67818. //# sourceMappingURL=babylon.reflectionProbe.js.map
  67819. var BABYLON;
  67820. (function (BABYLON) {
  67821. var Layer = (function () {
  67822. function Layer(name, imgUrl, scene, isBackground, color) {
  67823. this.name = name;
  67824. this.scale = new BABYLON.Vector2(1, 1);
  67825. this.offset = new BABYLON.Vector2(0, 0);
  67826. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  67827. this.layerMask = 0x0FFFFFFF;
  67828. this._vertexBuffers = {};
  67829. // Events
  67830. /**
  67831. * An event triggered when the layer is disposed.
  67832. * @type {BABYLON.Observable}
  67833. */
  67834. this.onDisposeObservable = new BABYLON.Observable();
  67835. /**
  67836. * An event triggered before rendering the scene
  67837. * @type {BABYLON.Observable}
  67838. */
  67839. this.onBeforeRenderObservable = new BABYLON.Observable();
  67840. /**
  67841. * An event triggered after rendering the scene
  67842. * @type {BABYLON.Observable}
  67843. */
  67844. this.onAfterRenderObservable = new BABYLON.Observable();
  67845. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  67846. this.isBackground = isBackground === undefined ? true : isBackground;
  67847. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  67848. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67849. this._scene.layers.push(this);
  67850. var engine = this._scene.getEngine();
  67851. // VBO
  67852. var vertices = [];
  67853. vertices.push(1, 1);
  67854. vertices.push(-1, 1);
  67855. vertices.push(-1, -1);
  67856. vertices.push(1, -1);
  67857. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67858. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  67859. // Indices
  67860. var indices = [];
  67861. indices.push(0);
  67862. indices.push(1);
  67863. indices.push(2);
  67864. indices.push(0);
  67865. indices.push(2);
  67866. indices.push(3);
  67867. this._indexBuffer = engine.createIndexBuffer(indices);
  67868. // Effects
  67869. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  67870. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  67871. }
  67872. Object.defineProperty(Layer.prototype, "onDispose", {
  67873. set: function (callback) {
  67874. if (this._onDisposeObserver) {
  67875. this.onDisposeObservable.remove(this._onDisposeObserver);
  67876. }
  67877. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  67878. },
  67879. enumerable: true,
  67880. configurable: true
  67881. });
  67882. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  67883. set: function (callback) {
  67884. if (this._onBeforeRenderObserver) {
  67885. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67886. }
  67887. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67888. },
  67889. enumerable: true,
  67890. configurable: true
  67891. });
  67892. Object.defineProperty(Layer.prototype, "onAfterRender", {
  67893. set: function (callback) {
  67894. if (this._onAfterRenderObserver) {
  67895. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67896. }
  67897. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67898. },
  67899. enumerable: true,
  67900. configurable: true
  67901. });
  67902. Layer.prototype.render = function () {
  67903. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  67904. // Check
  67905. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  67906. return;
  67907. var engine = this._scene.getEngine();
  67908. this.onBeforeRenderObservable.notifyObservers(this);
  67909. // Render
  67910. engine.enableEffect(currentEffect);
  67911. engine.setState(false);
  67912. // Texture
  67913. currentEffect.setTexture("textureSampler", this.texture);
  67914. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  67915. // Color
  67916. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  67917. // Scale / offset
  67918. currentEffect.setVector2("offset", this.offset);
  67919. currentEffect.setVector2("scale", this.scale);
  67920. // VBOs
  67921. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  67922. // Draw order
  67923. if (!this.alphaTest) {
  67924. engine.setAlphaMode(this.alphaBlendingMode);
  67925. engine.draw(true, 0, 6);
  67926. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67927. }
  67928. else {
  67929. engine.draw(true, 0, 6);
  67930. }
  67931. this.onAfterRenderObservable.notifyObservers(this);
  67932. };
  67933. Layer.prototype.dispose = function () {
  67934. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67935. if (vertexBuffer) {
  67936. vertexBuffer.dispose();
  67937. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67938. }
  67939. if (this._indexBuffer) {
  67940. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67941. this._indexBuffer = null;
  67942. }
  67943. if (this.texture) {
  67944. this.texture.dispose();
  67945. this.texture = null;
  67946. }
  67947. // Remove from scene
  67948. var index = this._scene.layers.indexOf(this);
  67949. this._scene.layers.splice(index, 1);
  67950. // Callback
  67951. this.onDisposeObservable.notifyObservers(this);
  67952. this.onDisposeObservable.clear();
  67953. this.onAfterRenderObservable.clear();
  67954. this.onBeforeRenderObservable.clear();
  67955. };
  67956. return Layer;
  67957. }());
  67958. BABYLON.Layer = Layer;
  67959. })(BABYLON || (BABYLON = {}));
  67960. //# sourceMappingURL=babylon.layer.js.map
  67961. var BABYLON;
  67962. (function (BABYLON) {
  67963. var TextureTools = (function () {
  67964. function TextureTools() {
  67965. }
  67966. /**
  67967. * Uses the GPU to create a copy texture rescaled at a given size
  67968. * @param texture Texture to copy from
  67969. * @param width Desired width
  67970. * @param height Desired height
  67971. * @return Generated texture
  67972. */
  67973. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  67974. if (useBilinearMode === void 0) { useBilinearMode = true; }
  67975. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  67976. var scene = texture.getScene();
  67977. var engine = scene.getEngine();
  67978. rtt.wrapU = texture.wrapU;
  67979. rtt.wrapV = texture.wrapV;
  67980. rtt.uOffset = texture.uOffset;
  67981. rtt.vOffset = texture.vOffset;
  67982. rtt.uScale = texture.uScale;
  67983. rtt.vScale = texture.vScale;
  67984. rtt.uAng = texture.uAng;
  67985. rtt.vAng = texture.vAng;
  67986. rtt.wAng = texture.wAng;
  67987. rtt.coordinatesIndex = texture.coordinatesIndex;
  67988. rtt.level = texture.level;
  67989. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  67990. rtt._texture.isReady = false;
  67991. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67992. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67993. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67994. passPostProcess.getEffect().executeWhenCompiled(function () {
  67995. passPostProcess.onApply = function (effect) {
  67996. effect.setTexture("textureSampler", texture);
  67997. };
  67998. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  67999. engine.unBindFramebuffer(rtt.getInternalTexture());
  68000. rtt.disposeFramebufferObjects();
  68001. passPostProcess.dispose();
  68002. rtt._texture.isReady = true;
  68003. });
  68004. return rtt;
  68005. };
  68006. return TextureTools;
  68007. }());
  68008. BABYLON.TextureTools = TextureTools;
  68009. })(BABYLON || (BABYLON = {}));
  68010. //# sourceMappingURL=babylon.textureTools.js.map
  68011. 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}"};
  68012. 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};"};
  68013. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  68014. module.exports = BABYLON;
  68015. };